Compare commits

..
57 changed files with 274 additions and 46226 deletions

View file

@ -69,21 +69,6 @@ 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=
# 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).
@ -98,25 +83,6 @@ 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, 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
# 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.

View file

@ -1,28 +1,21 @@
# Build changed OSINT images and publish them to the Forgejo container
# registry. Deployment is NOT done here: the cluster (homek8s, namespace
# `osint`) runs amd64 images pinned by tag in apps/base/osint/*.yaml, so the
# final step prints the tag to pin and a human opens that manifest PR.
# 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 on a normal merge — Postgres stays up. Rebuild it only when
# Dockerfile.pg changes, or via workflow_dispatch rebuild_pg.
#
# Registry endpoints
# CI push host: forgejo.forgejo.svc.cluster.local:3000 — plain HTTP
# ClusterIP, whitelisted by --insecure-registry on the amd64
# runner's dind daemon. 127.0.0.1:3000 stopped working when
# Forgejo moved into k8s: inside an in-cluster job pod, loopback
# is the pod itself, so login died with "connection refused".
# Public pull: forgejo.siriusdevops.com (HTTPS via Cloudflare; kubelet pulls
# from here). Do NOT push here — Cloudflare 413s layers ≳100MB.
# 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).
# Images (public names):
# forgejo.siriusdevops.com/sirius/osint-dashboard:amd64-<sha12>
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg:amd64-<sha12>
# forgejo.siriusdevops.com/sirius/osint-news-scraper:amd64-<sha12>
# forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64-<sha12>
# forgejo.siriusdevops.com/sirius/osint-dashboard
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg
# forgejo.siriusdevops.com/sirius/osint-news-scraper
# forgejo.siriusdevops.com/sirius/osint-news-summarizer
#
# Optional repo variable FORGEJO_REGISTRY overrides the *public* pull host.
# Deploy still uses the local docker socket on the runner host (rpi).
name: build-and-deploy
@ -42,19 +35,17 @@ on:
env:
PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }}
PUSH_REGISTRY: forgejo.forgejo.svc.cluster.local:3000
PUSH_REGISTRY: 127.0.0.1:3000
OWNER: sirius
# Keep compose project/volumes stable on the Pi
COMPOSE_PROJECT_NAME: osint-dashboard
jobs:
build-push:
# `amd64` only exists on siriussec-amd64, which is also the node the
# workloads run on — so the images are built on the architecture they are
# pulled to. `runs-on: docker` matched the Pi's arm64 runner, which
# produced images the amd64 cluster could never run.
# No job-level `permissions:` block: Forgejo ignores it (it emits a
# pre-execution warning) and the push authenticates with the FORGEJO_TOKEN
# user PAT instead, because the package registry rejects the Actions token.
runs-on: amd64
build-push-deploy:
runs-on: docker
permissions:
contents: read
packages: write
steps:
- name: Checkout
uses: https://code.forgejo.org/actions/checkout@v4
@ -69,6 +60,7 @@ jobs:
SCRAPER=0
SUM=0
PG=0
COMPOSE=0
mark() {
case "$1" in
@ -80,6 +72,8 @@ jobs:
SCRAPER=1 ;;
news/summerizer/*)
SUM=1 ;;
docker-compose.yml|scripts/compose-reup.sh)
COMPOSE=1 ;;
esac
}
@ -114,8 +108,9 @@ jobs:
echo "scraper=$SCRAPER"
echo "summarizer=$SUM"
echo "pg=$PG"
echo "compose=$COMPOSE"
} >> "$GITHUB_OUTPUT"
echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG"
echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG compose=$COMPOSE"
- name: Image refs
id: img
@ -125,11 +120,10 @@ jobs:
PUB="${PUBLIC_REGISTRY}"
OWN="${OWNER}"
SHA="${GITHUB_SHA::12}"
TAG="amd64-${SHA}"
{
echo "reg=$PUSH"
echo "pub=$PUB"
echo "tag=$TAG"
echo "sha=$SHA"
echo "app=$PUSH/$OWN/osint-dashboard"
echo "pg=$PUSH/$OWN/osint-dashboard-pg"
echo "scraper=$PUSH/$OWN/osint-news-scraper"
@ -137,69 +131,113 @@ jobs:
} >> "$GITHUB_OUTPUT"
echo "Push registry: $PUSH"
echo "Public pull: $PUB"
echo "Image tag: $TAG"
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
# reject the Actions token). Use a user PAT.
# The PAT must carry the `write:package` scope: Forgejo mints a push
# token even without it and then rejects every blob upload with
# `unauthorized: reqPackageAccess` (routers/api/packages/api.go
# reqPackageAccess -> AccessTokenScopeWritePackage).
# Name is REGISTRY_TOKEN, not FORGEJO_TOKEN: Forgejo reserves the
# FORGEJO_/GITHUB_ prefixes and refuses to create or update them via
# the API.
if [ -z "${{ secrets.REGISTRY_TOKEN }}" ]; then
echo "Missing repo secret REGISTRY_TOKEN (user PAT with write:package, not GITHUB_TOKEN)"
# reject the Actions token). Use a user PAT with write:package.
if [ -z "${{ secrets.FORGEJO_TOKEN }}" ]; then
echo "Missing repo secret FORGEJO_TOKEN (user PAT, not GITHUB_TOKEN)"
exit 1
fi
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \
echo "${{ secrets.FORGEJO_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \
-u sirius --password-stdin
- name: Build application image (api / ingester / cameras)
if: steps.plan.outputs.app == '1'
run: |
set -ex
IMG="${{ steps.img.outputs.app }}"
TAG="${{ steps.img.outputs.tag }}"
docker build -f Dockerfile -t "${IMG}:${TAG}" .
docker push "${IMG}:${TAG}"
APP="${{ steps.img.outputs.app }}"
SHA="${{ steps.img.outputs.sha }}"
docker build -f Dockerfile -t "${APP}:latest" -t "${APP}:${SHA}" \
-t "localhost/osint-dashboard:latest" .
docker push "${APP}:latest"
docker push "${APP}:${SHA}"
- name: Build news-scraper image
if: steps.plan.outputs.scraper == '1'
run: |
set -ex
IMG="${{ steps.img.outputs.scraper }}"
TAG="${{ steps.img.outputs.tag }}"
docker build -f news/scraper/Dockerfile -t "${IMG}:${TAG}" news/scraper
docker push "${IMG}:${TAG}"
SHA="${{ steps.img.outputs.sha }}"
docker build -f news/scraper/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \
-t "localhost/osint-news-scraper:latest" news/scraper
docker push "${IMG}:latest"
docker push "${IMG}:${SHA}"
- name: Build news-summarizer image
if: steps.plan.outputs.summarizer == '1'
run: |
set -ex
IMG="${{ steps.img.outputs.summarizer }}"
TAG="${{ steps.img.outputs.tag }}"
docker build -f news/summerizer/Dockerfile -t "${IMG}:${TAG}" news/summerizer
docker push "${IMG}:${TAG}"
SHA="${{ steps.img.outputs.sha }}"
docker build -f news/summerizer/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \
-t "localhost/osint-news-summarizer:latest" news/summerizer
docker push "${IMG}:latest"
docker push "${IMG}:${SHA}"
- name: Build / refresh Timescale+PostGIS image
if: steps.plan.outputs.pg == '1'
run: |
set -ex
IMG="${{ steps.img.outputs.pg }}"
TAG="${{ steps.img.outputs.tag }}"
docker build -f Dockerfile.pg -t "${IMG}:${TAG}" .
docker push "${IMG}:${TAG}"
PG="${{ steps.img.outputs.pg }}"
SHA="${{ steps.img.outputs.sha }}"
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; keeping existing local pg image"
else
echo "ERROR: cannot build or find osint-dashboard-pg image"
exit 1
fi
- name: Deploy on runner host (compose)
run: |
set -ex
cd "${GITHUB_WORKSPACE}"
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
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 deploy done; db image left in place unless pg=1"
- name: Summary
if: always()
run: |
TAG="${{ steps.img.outputs.tag }}"
PUB="${{ steps.img.outputs.pub }}"
{
echo "## Image plan"
echo "- app: \`${{ steps.plan.outputs.app }}\`"
@ -207,23 +245,5 @@ jobs:
echo "- news-summarizer: \`${{ steps.plan.outputs.summarizer }}\`"
echo "- pg (Timescale): \`${{ steps.plan.outputs.pg }}\`"
echo
if [ -n "$TAG" ]; then
echo "## Pin in homek8s (apps/base/osint)"
echo "Pushed tag: \`${TAG}\`. Set the workload images in"
echo "\`apps/base/osint/kustomization.yaml\` to:"
echo
echo '```yaml'
echo "images:"
echo " - name: ${PUB}/${OWNER}/osint-dashboard"
echo " newTag: ${TAG}"
echo " - name: ${PUB}/${OWNER}/osint-news-scraper"
echo " newTag: ${TAG}"
echo " - name: ${PUB}/${OWNER}/osint-news-summarizer"
echo " newTag: ${TAG}"
echo '```'
else
echo "_No tag computed — the earlier steps failed before Image refs._"
fi
echo
echo "Postgres is rebuilt only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)."
echo "Postgres is rebuilt/pulled only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)."
} >> "$GITHUB_STEP_SUMMARY"

View file

@ -1,39 +0,0 @@
"""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")

View file

@ -1,23 +0,0 @@
"""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")

View file

@ -1,40 +0,0 @@
"""article_scores geo: per-article proximate location for /api/news/blips
Revision ID: 014_article_scores_geo
Revises: 013_article_scores_duplicate_of
Create Date: 2026-11-19
Additive nullable columns on article_scores (every graded article keeps
its grading row; geo rides along when derivable). Partial bbox index for
the blips endpoint's bbox= filter. Idempotent DDL mirrors the summarizer's
ensure_tables so either start order is safe.
"""
from alembic import op
revision = "014_article_scores_geo"
down_revision = "013_article_scores_duplicate_of"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_name TEXT")
op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lat DOUBLE PRECISION")
op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lon DOUBLE PRECISION")
op.execute(
"ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_confidence TEXT"
)
op.execute(
"CREATE INDEX IF NOT EXISTS ix_article_scores_geo_bbox "
"ON article_scores (lon, lat) "
"WHERE lat IS NOT NULL AND lon IS NOT NULL"
)
def downgrade() -> None:
op.execute("DROP INDEX IF EXISTS ix_article_scores_geo_bbox")
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS location_confidence")
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS lon")
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS lat")
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS location_name")

View file

@ -1,589 +0,0 @@
"""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``) 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,
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$<iterations>$<salt_b64>$<hash_b64>``. 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",
"/api/news/blips",
# 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$<iters>$<salt_b64>$<hash_b64>``."""
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"
_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,
token,
max_age=SESSION_TTL_SECONDS,
httponly=True,
samesite="lax",
secure=cookie_secure_forced() or _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 = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Admin sign-in · OSINT//</title>
<style>
:root { --bg:#05070c; --panel:#0b1018; --line:#1c2735; --cyan:#35e0ff; --magenta:#ff2e97; --text:#d7e3f2; --dim:#7d8ea3; }
* { box-sizing:border-box; }
body { margin:0; min-height:100vh; display:grid; place-items:center; background:
radial-gradient(1000px 500px at 50% -10%, rgba(53,224,255,.10), transparent 60%),
radial-gradient(700px 400px at 90% 110%, rgba(255,46,151,.08), transparent 60%), var(--bg);
color:var(--text); font:15px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
.box { width:100%; max-width:360px; padding:2rem 1.6rem; border:1px solid var(--line);
border-radius:8px; background:linear-gradient(180deg, var(--panel), #070b12);
box-shadow:0 0 0 1px rgba(53,224,255,.06), 0 24px 60px rgba(0,0,0,.6); }
.brand { letter-spacing:.24em; font-size:.8rem; color:var(--dim); margin-bottom:1.4rem; }
.brand b { color:var(--cyan); }
h1 { font-size:1rem; letter-spacing:.12em; margin:0 0 1.2rem; text-transform:uppercase; }
label { display:block; font-size:.68rem; letter-spacing:.16em; color:var(--dim);
text-transform:uppercase; margin:.9rem 0 .35rem; }
input { width:100%; padding:.6rem .7rem; background:#04070d; color:var(--text);
border:1px solid var(--line); border-radius:4px; font:inherit; }
input:focus { outline:none; border-color:var(--cyan); box-shadow:0 0 0 2px rgba(53,224,255,.14); }
button { width:100%; margin-top:1.4rem; padding:.65rem; background:var(--cyan); color:#02121a;
border:0; border-radius:4px; font:inherit; font-weight:700; letter-spacing:.12em; cursor:pointer; }
button:hover { background:#6becff; }
button:disabled { opacity:.5; cursor:default; }
.msg { min-height:1.2rem; margin-top:.9rem; font-size:.8rem; color:var(--magenta); }
.note { margin-top:1.1rem; font-size:.74rem; color:var(--dim); }
a { color:var(--cyan); text-decoration:none; }
</style>
</head>
<body>
<form class="box" id="login-form">
<div class="brand">OSINT<b>//</b> ADMIN</div>
<h1>Sign in</h1>
<label for="username">Username</label>
<input id="username" name="username" type="text" autocomplete="username" required autofocus>
<label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password" required>
<button id="submit" type="submit">AUTHENTICATE</button>
<div class="msg" id="msg" role="alert"></div>
<div class="note"><a href="/">← Back to dashboard</a></div>
</form>
<script>
const form = document.getElementById('login-form');
const msg = document.getElementById('msg');
const submit = document.getElementById('submit');
form.addEventListener('submit', async (ev) => {
ev.preventDefault();
msg.textContent = '';
submit.disabled = true;
try {
const r = await fetch('/api/auth/login', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams(new FormData(form)),
});
const data = await r.json().catch(() => ({}));
if (r.ok) { window.location.replace('/'); return; }
msg.textContent = r.status === 429 ? 'Too many attempts. Try again later.'
: (data && data.detail ? String(data.detail) : 'Sign-in failed.');
} catch (e) {
msg.textContent = 'Network error.';
} finally {
submit.disabled = false;
}
});
</script>
</body>
</html>
"""
_NOT_CONFIGURED = ('<div class="msg">Admin auth is not configured on this server. '
'Set ADMIN_PASSWORD_HASH and ADMIN_SESSION_SECRET.</div>')
@router.get("/login", response_class=HTMLResponse)
async def login_page():
html = _LOGIN_PAGE
if not auth_configured():
html = html.replace('<div class="msg" id="msg" role="alert"></div>',
_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 '<password>'")
return 2
print(hash_password(argv[1]))
return 0
if __name__ == "__main__":
import sys
raise SystemExit(_main(sys.argv[1:]))

View file

@ -59,8 +59,7 @@ SNAPSHOT_CACHE_DIR = os.getenv("SNAPSHOT_CACHE_DIR", "/data/snapshots")
SNAPSHOT_TTL_SECONDS = int(os.getenv("SNAPSHOT_TTL_SECONDS", "300"))
SNAPSHOT_TIMEOUT = float(os.getenv("SNAPSHOT_TIMEOUT", "8.0"))
# Retained so an old CAMERA_NATS_SUBJECT env does not surprise operators.
# This service does not publish on it; cameras live in the cameras table.
# NATS subject cameras are published on (consumed by the shared ingester).
CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera")

View file

@ -11,8 +11,8 @@ Pipeline per cycle:
2. Parse cameras (Insecam-style HTML with embedded lat/lon, or plain-text
`url[|lat,lon|vendor|location]` lines).
3. Geocode missing coords via Nominatim at <=1 req/s.
4. Upsert into the `cameras` table keyed by sha256(url_hash).
Discovery is not published as an event.
4. Publish each camera to NATS (`events.camera`) for the shared ingester,
and upsert into the `cameras` table keyed by sha256(url_hash).
Snapshots are cached locally with a TTL; nothing is fetched more often than
the cache allows.

View file

@ -107,12 +107,3 @@ VESSELAPI_MAX_CALLS_PER_DAY = int(os.getenv("VESSELAPI_MAX_CALLS_PER_DAY", "5"))
# Run the VesselAPI poller inside the dashboard process (default on, like AIS).
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")
# ADS-B (ADSB.lol, no key). The dashboard's refresh loop follows browser
# viewports; with no tab open it persisted nothing and aircraft_positions went
# silent for a day. ADSB_WATCH_ENABLED=1 makes the loop sweep the chokepoint
# presets while idle, so the hypertable keeps advancing unattended.
ADSB_REFRESH_INTERVAL = float(os.getenv("ADSB_REFRESH_INTERVAL", "8"))
ADSB_WATCH_ENABLED = os.getenv("ADSB_WATCH_ENABLED", "1").lower() in ("1", "true", "yes")
# Idle sweep cadence; 30 s over 5 preset boxes ≈ 0.17 req/s to ADSB.lol.
ADSB_WATCH_INTERVAL = float(os.getenv("ADSB_WATCH_INTERVAL", "30"))

View file

@ -7,7 +7,6 @@ in ``geofence_alerts`` and fan out as WS type ``geofence_alert``.
from __future__ import annotations
import json
import logging
from datetime import datetime, timedelta, timezone
from typing import Any
from uuid import uuid4
@ -16,19 +15,6 @@ from sqlalchemy import text
from database import async_session
logger = logging.getLogger("osint.geofence")
# New hit kinds. adsb/ais/firms omit ``evidence``; these three must include it.
# ``camera`` is never a hit kind.
EVIDENCE_KINDS = frozenset({"earthquake", "fire_incident", "news"})
_CAMERA_CAP = 5
_NEWS_CAP = 3
# Process-local "already paged" set for polled incidents. The 5-minute
# cooldown still applies; this stops a later poll (or a restart that
# re-reads the DB check) from treating a durable hit as new. Not used
# for moving adsb/ais/firms targets.
_notified_once: set[tuple[str, str, str]] = set()
def _rings_from_geojson(geojson: dict) -> list[list[list[float]]]:
if not isinstance(geojson, dict):
@ -113,160 +99,6 @@ _recent_hits: dict[tuple[str, str], datetime] = {}
_HIT_COOLDOWN = timedelta(minutes=5)
def iso_z(ts: datetime) -> str:
"""UTC ISO-8601 with a Z suffix so it is safe in a query string."""
if ts.tzinfo is None:
ts = ts.replace(tzinfo=timezone.utc)
return ts.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def snapshot_path(gid: str, ts: datetime) -> str:
return f"/api/geofences/{gid}/at?ts={iso_z(ts)}"
def camera_evidence(row: dict) -> dict:
"""Proxy path only. Never copy ``cameras.snapshot_url`` (agency / rtsp)."""
cid = str(row.get("id") or "")
name = row.get("name")
if name is None:
name = row.get("location_name") or ""
return {
"id": cid,
"name": str(name or ""),
"snapshot_url": f"/api/cameras/{cid}/snapshot",
}
def news_evidence(row: dict) -> dict:
return {
"headline": str(row.get("headline") or ""),
"url": str(row.get("url") or ""),
"importance": str(row.get("importance") or ""),
}
def evidence_pack(
gid: str, ts: datetime, cameras: list[dict], news: list[dict],
) -> dict:
return {
"cameras": [camera_evidence(r) for r in cameras[:_CAMERA_CAP]],
"news": [news_evidence(r) for r in news[:_NEWS_CAP]],
"snapshot": snapshot_path(gid, ts),
}
def polygon_bbox(geojson: dict) -> str | None:
"""``minlon,minlat,maxlon,maxlat`` of the outer ring, or None."""
try:
rings = _rings_from_geojson(geojson)
except (ValueError, TypeError, KeyError):
return None
pts = rings[0]
lons = [p[0] for p in pts]
lats = [p[1] for p in pts]
return f"{min(lons)},{min(lats)},{max(lons)},{max(lats)}"
def earthquake_entity_id(row: dict) -> str:
"""Stable id shared by the insert hook and the catch-up scan."""
raw = row.get("raw")
if isinstance(raw, str):
try:
raw = json.loads(raw)
except ValueError:
raw = None
if isinstance(raw, dict) and raw.get("usgs_id"):
return str(raw["usgs_id"])
url = row.get("url")
if url and str(url).strip():
return str(url).strip()
return str(row.get("id") or row.get("event_id") or "")
def fire_incident_entity_id(marker: dict) -> str:
"""IrwinID when the feed has one, else a stable name|state|discovered key."""
extra = marker.get("extra") or {}
for key in ("irwin_id", "unique_fire_id"):
val = extra.get(key)
if val:
return str(val)
name = marker.get("id") or marker.get("label") or "incident"
state = extra.get("state") or ""
discovered = extra.get("discovered") or ""
return f"{name}|{state}|{discovered}"
# Do not SELECT cameras.snapshot_url — that column is the agency/rtsp URL.
_CAMERAS_INSIDE_SQL = """
SELECT id::text AS id,
COALESCE(location_name, '') AS name
FROM cameras
WHERE location_lat IS NOT NULL
AND location_lon IS NOT NULL
AND ST_Intersects(
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326)
)
ORDER BY ST_Distance(
ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326),
ST_SetSRID(ST_MakePoint(:lon, :lat), 4326)
)
LIMIT :limit
"""
_NEWS_INSIDE_SQL = """
SELECT headline,
COALESCE(url, '') AS url,
COALESCE(importance, '') AS importance
FROM news_items
WHERE lat IS NOT NULL
AND lon IS NOT NULL
AND ST_Intersects(
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
ST_SetSRID(ST_MakePoint(lon, lat), 4326)
)
ORDER BY created_at DESC
LIMIT :limit
"""
_ALREADY_SQL = """
SELECT 1
FROM geofence_alerts
WHERE geofence_id = CAST(:gid AS uuid)
AND source_kind = :source_kind
AND entity_id = :entity_id
LIMIT 1
"""
async def _rows(sql: str, params: dict) -> list[dict]:
async with async_session() as session:
result = await session.execute(text(sql), params)
return [dict(r) for r in result.mappings().all()]
async def build_evidence(
gid: str, *, lat: float, lon: float, now: datetime,
) -> dict:
"""Cameras nearest the hit (≤5) and news most-recent (≤3) inside the fence.
Empty arrays if none or the query fails. Snapshot is a path, not a body.
"""
cameras: list[dict] = []
news: list[dict] = []
try:
cameras = await _rows(_CAMERAS_INSIDE_SQL, {
"gid": gid, "lat": lat, "lon": lon, "limit": _CAMERA_CAP,
})
except Exception:
logger.exception("evidence cameras query failed gid=%s", gid)
try:
news = await _rows(_NEWS_INSIDE_SQL, {"gid": gid, "limit": _NEWS_CAP})
except Exception:
logger.exception("evidence news query failed gid=%s", gid)
return evidence_pack(gid, now, cameras, news)
async def refresh_cache() -> list[dict]:
global _cache
async with async_session() as session:
@ -417,24 +249,12 @@ async def record_and_notify(
lat: float,
lon: float,
payload: dict[str, Any] | None = None,
skip_existing: bool = False,
) -> int:
"""Insert a geofence_alerts row per hit and WS-push to viewport clients.
PostGIS ST_Intersects is the source of truth. The in-process GeoJSON
cache is not a reject filter — the FIRMS ingester never fills it.
``source_kind=camera`` is refused (no row, no WS). Earthquake, fire
incident, and news hits get an ``evidence`` object; adsb/ais/firms
keep the caller payload unchanged.
``skip_existing`` is for polled incidents (same id every cycle). It
does not change the 5-minute cooldown. A failed existence check
skips the hit so a broken read cannot page every fence.
"""
if source_kind == "camera":
logger.warning("refusing geofence notify for source_kind=camera")
return 0
hits = await st_intersects(lon, lat)
if not hits:
return 0
@ -455,33 +275,6 @@ async def record_and_notify(
hits = fresh
async with async_session() as session:
for fence in hits:
once_key = (str(fence["id"]), source_kind, str(entity_id))
if skip_existing:
if once_key in _notified_once:
continue
try:
existing = await session.execute(
text(_ALREADY_SQL),
{
"gid": fence["id"],
"source_kind": source_kind,
"entity_id": str(entity_id),
},
)
if existing.first() is not None:
_notified_once.add(once_key)
continue
except Exception:
logger.exception(
"geofence existing-hit check failed kind=%s entity=%s",
source_kind, entity_id,
)
continue
body_payload = dict(payload or {})
if source_kind in EVIDENCE_KINDS:
body_payload["evidence"] = await build_evidence(
str(fence["id"]), lat=lat, lon=lon, now=now,
)
aid = str(uuid4())
body = {
"id": aid,
@ -491,7 +284,7 @@ async def record_and_notify(
"entity_id": str(entity_id),
"lat": lat,
"lon": lon,
"payload": body_payload,
"payload": payload or {},
"created_at": now.isoformat(),
}
try:
@ -513,7 +306,7 @@ async def record_and_notify(
"entity_id": str(entity_id),
"lat": lat,
"lon": lon,
"payload": json.dumps(body_payload),
"payload": json.dumps(payload or {}),
},
)
except Exception:
@ -521,8 +314,6 @@ async def record_and_notify(
sent += await manager.publish_point(
"geofence_alert", body, lat=lat, lon=lon,
)
if skip_existing:
_notified_once.add(once_key)
try:
await session.commit()
except Exception:
@ -679,166 +470,3 @@ async def snapshot_at(gid: str, ts: datetime) -> dict | None:
"vessels": vessels,
"fires": fires,
}
_QUAKE_SCAN_SQL = """
SELECT id::text AS id, url, title, location_lat, location_lon, raw
FROM events
WHERE source_type = 'earthquake'
AND location_lat IS NOT NULL
AND location_lon IS NOT NULL
AND source_timestamp >= now() - interval '7 days'
ORDER BY source_timestamp DESC
LIMIT :limit
"""
# Same pin set as GET /api/news/map: kind=map, flagged, coords, last 24h.
_NEWS_SCAN_SQL = """
SELECT id::text AS id, headline, url, importance, lat, lon
FROM news_items
WHERE kind = 'map'
AND lat IS NOT NULL
AND lon IS NOT NULL
AND importance IN ('critical', 'high')
AND created_at >= now() - interval '24 hours'
ORDER BY created_at DESC
LIMIT :limit
"""
async def scan_earthquakes(limit: int = 200) -> int:
"""Catch-up: quakes already in ``events`` when a fence is drawn later."""
try:
rows = await _rows(_QUAKE_SCAN_SQL, {"limit": int(limit)})
except Exception:
logger.exception("earthquake geofence scan failed")
return 0
n = 0
for row in rows:
lat, lon = row.get("location_lat"), row.get("location_lon")
if lat is None or lon is None:
continue
eid = earthquake_entity_id(row)
if not eid:
continue
try:
n += await record_and_notify(
source_kind="earthquake",
entity_id=eid,
lat=float(lat),
lon=float(lon),
payload={"title": row.get("title"), "url": row.get("url") or ""},
skip_existing=True,
)
except Exception:
logger.exception("earthquake geofence notify failed entity=%s", eid)
return n
async def scan_news_pins(limit: int = 200) -> int:
"""Read ``news_items`` map pins. Does not import the summarizer."""
try:
rows = await _rows(_NEWS_SCAN_SQL, {"limit": int(limit)})
except Exception:
logger.exception("news geofence scan failed")
return 0
n = 0
for row in rows:
lat, lon = row.get("lat"), row.get("lon")
if lat is None or lon is None:
continue
eid = str(row.get("id") or "")
if not eid:
continue
try:
n += await record_and_notify(
source_kind="news",
entity_id=eid,
lat=float(lat),
lon=float(lon),
payload={
"headline": row.get("headline") or "",
"url": row.get("url") or "",
"importance": row.get("importance") or "",
},
skip_existing=True,
)
except Exception:
logger.exception("news geofence notify failed entity=%s", eid)
return n
async def poll_fire_incidents(fences: list[dict] | None = None) -> int:
"""WFIGS incidents are not stored. Fetch each active fence's bbox.
``load_fire_incidents`` does not mutate the map cache or correlate
aircraft. A point in the bbox but outside the polygon is dropped
before ``record_and_notify``; ST_Intersects is still the write guard.
"""
if fences is None:
fences = [f for f in cached_fences() if f.get("active", True)]
from live_layers import load_fire_incidents
n = 0
seen: set[str] = set()
for fence in fences:
if not fence.get("active", True):
continue
bbox = polygon_bbox(fence.get("geojson") or {})
if not bbox:
continue
try:
incidents = await load_fire_incidents(bbox)
except Exception:
logger.exception("wfigs fence poll failed bbox=%s", bbox)
continue
if not isinstance(incidents, list):
continue
for inc in incidents:
if not isinstance(inc, dict):
continue
lat, lon = inc.get("lat"), inc.get("lon")
if lat is None or lon is None:
continue
if not point_in_geojson(float(lon), float(lat), fence.get("geojson") or {}):
continue
eid = fire_incident_entity_id(inc)
if not eid or eid in seen:
continue
seen.add(eid)
try:
n += await record_and_notify(
source_kind="fire_incident",
entity_id=eid,
lat=float(lat),
lon=float(lon),
payload={
"label": inc.get("label"),
"extra": inc.get("extra") or {},
},
skip_existing=True,
)
except Exception:
logger.exception("fire_incident geofence notify failed entity=%s", eid)
return n
async def scan_geofence_feeds() -> int:
"""Ingester-loop catch-up. No-op when no active fence is cached.
Earthquakes also notify on insert (``ingestor.ingest_event``). This
scan covers rows already stored, WFIGS (not persisted), and news
pins written by the summarizer process.
"""
try:
await refresh_cache()
except Exception:
logger.exception("geofence cache refresh failed")
fences = [f for f in cached_fences() if f.get("active", True)]
if not fences:
return 0
n = 0
n += await scan_earthquakes()
n += await scan_news_pins()
n += await poll_fire_incidents(fences)
return n

View file

@ -219,32 +219,9 @@ async def ingest_event(msg: dict):
await session.commit()
event_id = result.inserted_primary_key[0] # type: ignore[union-attr]
logger.info("Ingested event %s from source %s", event_id, msg.get("source_type"))
# Cameras are persisted as events only. Never a geofence hit.
if event_row["source_type"] == "earthquake":
await _notify_earthquake(event_row, event_id)
return event_id
async def _notify_earthquake(event_row: dict, event_id) -> None:
"""One hit per new quake. Dedup already dropped replays; skip if no point."""
lat, lon = event_row.get("location_lat"), event_row.get("location_lon")
if lat is None or lon is None:
return
try:
from geofence import earthquake_entity_id, record_and_notify
row = {**event_row, "id": str(event_id)}
await record_and_notify(
source_kind="earthquake",
entity_id=earthquake_entity_id(row),
lat=float(lat),
lon=float(lon),
payload={"title": event_row.get("title"), "url": event_row.get("url") or ""},
skip_existing=True,
)
except Exception:
logger.exception("earthquake geofence notify failed")
async def start_nats_consumer():
"""Start NATS JetStream consumer for OSINT events."""
nc = await nats.connect(NATS_URLS)

View file

@ -743,25 +743,18 @@ def transform_wfigs_incidents(fc: dict | None) -> list[dict]:
continue
props = feat.get("properties") or {}
name = str(props.get("IncidentName") or "Incident").strip()
extra = {
"acres": props.get("IncidentSize"),
"contained": props.get("PercentContained"),
"state": props.get("POOState"),
"category": props.get("IncidentTypeCategory"),
"cause": props.get("FireCause"),
"discovered": props.get("FireDiscoveryDateTime"),
"src": "wfigs",
}
irwin = props.get("IrwinID")
if irwin:
extra["irwin_id"] = str(irwin)
ufi = props.get("UniqueFireIdentifier")
if ufi:
extra["unique_fire_id"] = str(ufi)
out.append(to_marker(
name, lat, lon,
label=name,
extra=extra,
extra={
"acres": props.get("IncidentSize"),
"contained": props.get("PercentContained"),
"state": props.get("POOState"),
"category": props.get("IncidentTypeCategory"),
"cause": props.get("FireCause"),
"discovered": props.get("FireDiscoveryDateTime"),
"src": "wfigs",
},
))
return out
@ -1091,27 +1084,17 @@ def _wfigs_params(bbox: str | None, *, offset_m: float = 250.0) -> dict:
return params
_WFIGS_INCIDENT_FIELDS = (
"IncidentName,IncidentSize,FireDiscoveryDateTime,POOState,"
"PercentContained,IncidentTypeCategory,FireCause,"
"IrwinID,UniqueFireIdentifier"
)
async def load_fire_incidents(bbox: str | None) -> list[dict]:
"""WFIGS points for a bbox. No last-known mutation, no aircraft correlate."""
async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]:
params = _wfigs_params(bbox)
params["outFields"] = _WFIGS_INCIDENT_FIELDS
params["outFields"] = (
"IncidentName,IncidentSize,FireDiscoveryDateTime,POOState,"
"PercentContained,IncidentTypeCategory,FireCause"
)
async def _load():
return transform_wfigs_incidents(await _get_json(WFIGS_INCIDENTS, params))
rows = await _ttl_get(f"wfigs:inc:{bbox_cell_key(bbox)}", 600.0, _load)
return list(rows or [])
async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]:
rows = await load_fire_incidents(bbox)
fire_last_known[:] = list(rows)
if rows and aircraft_last_known:
from fire_aircraft import correlate_and_notify

View file

@ -34,16 +34,15 @@ 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_scores, article_summaries, news_items,
articles, article_summaries, news_items,
)
from schemas import (
AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate,
ConflictZoneOut, ConflictsOut,
DashboardSummary, EntityCreate, EntityKind, EntityOut,
EventCreate, EventOut, FireOut, NewsArticleOut, NewsBlipOut, NewsMapItemOut,
EventCreate, EventOut, FireOut, NewsArticleOut, NewsMapItemOut,
NewsSummaryOut, NewsTickerItemOut,
FeedSourceCreate, FeedSourceOut, FeedSourceUpdate,
KeyOut, KeyValueIn,
@ -57,7 +56,6 @@ 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 news_title import unwrap_cdata_title
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,
@ -118,57 +116,17 @@ 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"
def _adsb_watch_boxes() -> list[tuple[float, float, float, float]]:
"""Chokepoint presets as viewport boxes (minlon, minlat, maxlon, maxlat).
Used only while no browser viewport is registered: without it the refresh
loop persists nothing and ``aircraft_positions`` silently stalls whenever
nobody has the map open.
"""
from chokepoints import chokepoints
out: list[tuple[float, float, float, float]] = []
for preset in chokepoints():
try:
# Preset bboxes are minlat,minlon,maxlat,maxlon (VesselAPI order).
minlat, minlon, maxlat, maxlon = (float(v) for v in str(preset["bbox"]).split(","))
except (KeyError, TypeError, ValueError):
continue
out.append((minlon, minlat, maxlon, maxlat))
return out
async def _adsb_refresh_loop() -> None:
"""Poll ADSB.lol for connected viewports — never from GET /api/aircraft.
When no client viewport is registered the loop sweeps the watch boxes
(chokepoint presets) at ``ADSB_WATCH_INTERVAL`` so aircraft ingest keeps
advancing with no map open.
"""
"""Poll ADSB.lol for connected viewports — never from GET /api/aircraft."""
from ws_manager import manager
from live_layers import fetch_aircraft
from config import ADSB_REFRESH_INTERVAL, ADSB_WATCH_ENABLED, ADSB_WATCH_INTERVAL
watch_boxes: list[tuple[float, float, float, float]] | None = None
while True:
interval = ADSB_REFRESH_INTERVAL
try:
boxes = manager.viewports()
if not boxes and ADSB_WATCH_ENABLED:
if watch_boxes is None:
watch_boxes = _adsb_watch_boxes()
boxes = watch_boxes
interval = ADSB_WATCH_INTERVAL
logger.debug("adsb_idle_watch", boxes=len(boxes))
for box in boxes:
bbox = f"{box[0]},{box[1]},{box[2]},{box[3]}"
try:
@ -177,7 +135,7 @@ async def _adsb_refresh_loop() -> None:
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(interval)
await asyncio.sleep(8)
class CachedStaticFiles(StaticFiles):
@ -308,14 +266,7 @@ async def _pipeline_checks(session) -> dict:
await _age("SELECT max(ingested_at) FROM events", "events", 20 * 60)
await _age("SELECT max(ingested_at) FROM fires", "fires", 30 * 60)
# Same closed-at-now window as GET /api/news. A future max() made age_s
# negative and hid a fresh list. NULL timestamps are not fresh.
await _age(
"SELECT max(timestamp) FROM articles "
"WHERE timestamp IS NOT NULL AND timestamp <= now()",
"articles",
2 * 3600,
)
await _age("SELECT max(timestamp) FROM articles", "articles", 2 * 3600)
await _age("SELECT max(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600)
return checks
@ -341,7 +292,7 @@ async def _stats_counts() -> dict:
aircraft_last_known, vessel_last_known, train_count, nws_alert_count,
)
counts: dict = {
counts: dict[str, int | str] = {
"aircraft": len(aircraft_last_known),
"vessels": len(vessel_last_known),
"trains": train_count,
@ -373,41 +324,9 @@ async def _stats_counts() -> dict:
logger.warning("stats_db_failed", error=str(exc))
counts["timestamp"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
# Public booleans only. Never include the stored value, a prefix, or last-4.
counts["feeds"] = await _feed_flags()
return counts
async def _key_configured(*names: str) -> bool:
"""True when any named key has a non-empty value in the api_keys store.
Uses keystore.get_api_key — not env, not a second store. The value is
discarded after the emptiness check.
"""
from keystore import get_api_key
for name in names:
value = await get_api_key(name)
if isinstance(value, str) and value.strip():
return True
return False
async def _feed_flags() -> dict:
"""HUD layer flags. Fail closed (configured false) if the store is down."""
try:
vessels = await _key_configured("AISSTREAM_API_KEY", "VESSELAPI_API_KEY")
fires = await _key_configured("FIRMS_MAP_KEY")
except Exception as exc: # noqa: BLE001
logger.warning("stats_feed_flags_failed", error=str(exc))
vessels = False
fires = False
return {
"vessels": {"configured": vessels},
"fires": {"configured": fires},
}
@app.get("/api/stats")
async def api_stats():
"""Cheap HUD counters (counts only — no GeoJSON). Cached ~20 s."""
@ -1368,12 +1287,7 @@ async def list_news(
):
"""Most recent scraped news articles (newest first)."""
async with async_session() as session:
stmt = select(articles).where(
or_(
articles.c.timestamp.is_(None),
articles.c.timestamp <= func.now(),
)
).order_by(
stmt = select(articles).order_by(
articles.c.timestamp.desc().nullslast()
)
if domain:
@ -1384,7 +1298,7 @@ async def list_news(
rows = (await session.execute(stmt)).mappings().all()
return [
NewsArticleOut(
id=r["id"], title=unwrap_cdata_title(r["title"]), url=r["url"],
id=r["id"], title=r["title"], url=r["url"],
content=r["content"] if include_content else None, domain=r["domain"],
timestamp=r["timestamp"],
)
@ -1537,94 +1451,6 @@ async def list_news_map(
]
@app.get("/api/news/blips", response_model=list[NewsBlipOut])
async def list_news_blips(
bbox: str | None = Query(
None,
description="Comma-separated 'minlon,minlat,maxlon,maxlat' to bound the "
"result set by article coordinates. Omit for all blips.",
),
since: datetime | None = Query(
None,
description="Only gradings created at/after this UTC instant. "
"Defaults to the last 24 hours.",
),
limit: int = Query(1000, ge=1, le=5000),
):
"""Per-article proximate geo blips: EVERY graded article with a derivable
location (not just the critical/high map pins). Deduped by article id —
the latest grading's geo wins. Only finite lat/lon rows, newest first.
"""
if since is None:
since = datetime.now(timezone.utc) - timedelta(hours=24)
async with async_session() as session:
# DISTINCT ON (article_id) + ORDER BY article_id, created_at DESC
# keeps the latest grading per article; the outer query re-sorts
# newest-first and applies the limit. NaN is excluded explicitly:
# Postgres sorts NaN above every finite value, so range checks
# alone would let it through. prefix_with keeps this renderable on
# both SQLAlchemy 2.0 and 2.1 (requirements pin >=2.0).
stmt = (
select(
article_scores.c.article_id.label("id"),
articles.c.title.label("headline"),
articles.c.url,
articles.c.domain,
article_scores.c.location_name,
article_scores.c.lat,
article_scores.c.lon,
article_scores.c.location_confidence,
article_scores.c.category,
article_scores.c.score,
article_scores.c.created_at,
)
.select_from(
article_scores.join(articles, articles.c.id == article_scores.c.article_id)
)
.where(
article_scores.c.lat.isnot(None),
article_scores.c.lon.isnot(None),
article_scores.c.lat.between(-90, 90),
article_scores.c.lon.between(-180, 180),
text("article_scores.lat <> 'NaN'::double precision"),
text("article_scores.lon <> 'NaN'::double precision"),
article_scores.c.created_at >= since,
)
.prefix_with("DISTINCT ON (article_scores.article_id)")
.order_by(article_scores.c.article_id, article_scores.c.created_at.desc())
)
if bbox:
parts = [p.strip() for p in bbox.split(",")]
if len(parts) != 4:
raise HTTPException(
422, "bbox must be 'minlon,minlat,maxlon,maxlat' (4 comma-separated values)"
)
try:
minlon, minlat, maxlon, maxlat = (float(p) for p in parts)
except ValueError:
raise HTTPException(
422, "bbox values must be floats: 'minlon,minlat,maxlon,maxlat'"
)
stmt = stmt.where(
and_(
article_scores.c.lon >= minlon, article_scores.c.lon <= maxlon,
article_scores.c.lat >= minlat, article_scores.c.lat <= maxlat,
)
)
latest = stmt.subquery()
ordered = select(latest).order_by(latest.c.created_at.desc()).limit(limit)
rows = (await session.execute(ordered)).mappings().all()
return [
NewsBlipOut(
id=r["id"], headline=r["headline"] or "", url=r["url"], domain=r["domain"],
location_name=r["location_name"], lat=r["lat"], lon=r["lon"],
location_confidence=r["location_confidence"], category=r["category"],
score=r["score"], created_at=r["created_at"],
)
for r in rows
]
@app.get("/api/news/models", response_model=NewsModelsOut)
async def list_news_models():
"""Nous model catalog for the summarizer selector. Never 502s."""
@ -1951,31 +1777,24 @@ async def api_delete_geofence(gid: str):
@app.get("/api/geofences/{gid}/at")
async def api_geofence_at(
gid: str,
timestamp: str | None = Query(
None, description="ISO-8601 instant for the 1-minute DVR bucket",
),
ts: str | None = Query(
None,
description="Alias of timestamp. Evidence snapshot URLs use this name.",
),
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
raw_ts = timestamp or ts
try:
ts_parsed = parse_timestamp(raw_ts)
ts = parse_timestamp(timestamp)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
if ts_parsed is None:
if ts is None:
raise HTTPException(422, "timestamp required")
try:
body = await snapshot_at(gid, ts_parsed)
body = await snapshot_at(gid, ts)
except Exception:
body = {
"geofence_id": gid,
"timestamp": ts_parsed.isoformat(),
"timestamp": ts.isoformat(),
"aircraft": [],
"vessels": [],
"fires": [],
@ -1990,23 +1809,15 @@ 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|earthquake|fire_incident|news",
),
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", "earthquake", "fire_incident", "news",
):
raise HTTPException(
422,
"source_kind must be one of: firms, ais, adsb, earthquake, fire_incident, news",
)
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

View file

@ -4,7 +4,7 @@ from datetime import datetime, timezone
from uuid import uuid4
from sqlalchemy import (
Boolean, Column, Enum, Float, Index, Integer, String, Text,
Column, Enum, Float, Index, Integer, String, Text,
DateTime, JSON, func, Table, PrimaryKeyConstraint,
)
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
@ -242,34 +242,3 @@ news_items = Table(
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
)
Index("ix_news_items_kind_created", news_items.c.kind, news_items.c.created_at)
# Per-article map-phase grades (alembic 012/013/014). One row per graded
# article per run; PK (article_id, created_at) lets re-grades accumulate.
# Geo columns are nullable: only articles with a derivable location carry
# coordinates, served by GET /api/news/blips.
article_scores = Table(
"article_scores",
metadata,
Column("article_id", Integer, nullable=False),
Column("summary_id", Integer),
Column("score", Integer, nullable=False),
Column("category", Text),
Column("selected", Boolean, nullable=False),
Column("model", Text),
Column("duplicate_of", Integer),
Column("location_name", Text),
Column("lat", Float),
Column("lon", Float),
Column("location_confidence", Text),
Column("created_at", DateTime(timezone=True),
server_default=func.now(), nullable=False),
PrimaryKeyConstraint("article_id", "created_at"),
)
Index("ix_article_scores_summary", article_scores.c.summary_id)
Index(
"ix_article_scores_geo_bbox",
article_scores.c.lon, article_scores.c.lat,
postgresql_where=article_scores.c.lat.isnot(None)
& article_scores.c.lon.isnot(None),
)

View file

@ -1,33 +0,0 @@
"""News title cleanup for the read path.
Same rule as ``news/scraper/newsScraper/feed_util.py:unwrap_cdata_title``.
The API image does not include the scraper package, so the function is
copied rather than imported. Existing rows are fixed here on read; this
module does not write.
"""
from __future__ import annotations
import re
# Whole-title CDATA wrapper only. Leading/trailing whitespace around the
# markers belongs to the wrapper, not the title.
_CDATA_WRAPPER = re.compile(
r"\A\s*<!\[CDATA\[(.*?)\]\]>\s*\Z",
re.DOTALL,
)
def unwrap_cdata_title(title: str | None) -> str | None:
"""Strip a surrounding CDATA wrapper. Anything else is unchanged.
``<![CDATA[Hello]]>`` and ``\\n <![CDATA[Hello]]>`` become
``Hello``. Real HTML (``<b>Hello</b>``) and a title that merely contains
the markers are returned as-is. Non-strings pass through.
"""
if not isinstance(title, str):
return title
match = _CDATA_WRAPPER.match(title)
if match is None:
return title
return match.group(1).strip()

View file

@ -1,10 +1,9 @@
"""Long-running camera discovery service.
Discovers cameras on an interval and upserts them into the `cameras` table
(dedupe by url_hash) for the /api/cameras bbox query. Discovery is not an
event: this process does not publish `events.camera` messages. Those were
inserted as events rows and flooded the HUD feed. The cameras table is the
index.
Follows the existing ingest pattern: discovers cameras on an interval and
publishes each one as a NATS message (`events.camera`) so the shared NATS ->
ingester pipeline persists them; also upserts directly into the `cameras`
table (dedupe by url_hash) for the /api/cameras bbox query.
Env:
CAMERA_SOURCE_URLS comma-separated public directory/list URLs
@ -15,6 +14,7 @@ Env:
from __future__ import annotations
import asyncio
import json
import logging
import sys
from pathlib import Path
@ -22,12 +22,16 @@ from pathlib import Path
sys_path = str(Path(__file__).parent)
sys.path.insert(0, sys_path)
import nats # noqa: E402
from camera_config import ( # noqa: E402
CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL,
CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL, CAMERA_NATS_SUBJECT,
SNAPSHOT_CACHE_DIR,
)
from camera_scraper import run_cycle # noqa: E402
from database import init_extensions # noqa: E402
from camera_models import cameras # noqa: E402
from camera_scraper import run_cycle, url_hash # noqa: E402
from database import async_session, init_extensions # noqa: E402
from config import NATS_URL # noqa: E402
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
@ -36,16 +40,48 @@ logger = logging.getLogger("osint.camera_service")
ENABLED = sys.argv[1:] != ["--once"]
async def publish_new_cameras(rows: list | None = None) -> int:
"""Do not publish camera discoveries as events.
``run_cycle`` already upserts the cameras table, which backs
``GET /api/cameras``. ``rows`` is newly seen cameras from a cycle or a
test; none are JetStream-published, so the ingester inserts 0 events
with source_type=camera.
"""
del rows
return 0
async def publish_new_cameras() -> int:
"""Publish cameras seen in the latest cycle to NATS for the ingester."""
from datetime import datetime, timezone, timedelta
cutoff = datetime.now(timezone.utc) - timedelta(seconds=CAMERA_SCRAPE_INTERVAL * 2)
published = 0
try:
nc = await nats.connect(NATS_URL)
except Exception: # noqa: BLE001
logger.warning("NATS unavailable — skipping publish pass")
return 0
try:
js = nc.jetstream()
async with async_session() as session:
rows = (await session.execute(
cameras.select().where(cameras.c.last_seen >= cutoff)
)).mappings().all()
for r in rows:
msg = {
"source_type": "camera",
"title": f"Open camera ({r['vendor'] or 'unknown vendor'})",
"url": r["source_url"],
"location_lat": r["location_lat"],
"location_lon": r["location_lon"],
"location_name": r["location_name"],
"tags": ["osint", "camera", r["discovery_source"]],
"raw": {
"url_hash": r["url_hash"],
"snapshot_url": r["snapshot_url"],
"vendor": r["vendor"],
"device_type": r["device_type"],
"first_seen": r["first_seen"].isoformat(),
"last_seen": r["last_seen"].isoformat(),
},
"source_timestamp": datetime.now(timezone.utc).isoformat(),
}
await js.publish(CAMERA_NATS_SUBJECT, json.dumps(msg).encode())
published += 1
if published >= 500: # per-cycle cap
break
finally:
await nc.close()
return published
async def main() -> None:
@ -57,7 +93,8 @@ async def main() -> None:
try:
n = await run_cycle()
p = await publish_new_cameras()
logger.info("cycle: %d stored, %d camera events published", n, p)
logger.info("cycle: %d stored, %d published to %s",
n, p, CAMERA_NATS_SUBJECT)
except Exception: # noqa: BLE001
logger.exception("camera cycle error")
if not ENABLED: # --once mode

View file

@ -56,11 +56,8 @@ async def producer_loop() -> None:
try:
g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50)
logger.info("GDELT -> %d articles", g)
except Exception as exc: # noqa: BLE001
# Quota/backoff cases are handled inside ingest_gdelt (one clean
# line); anything reaching here is a real failure and a stack
# trace every 5 minutes is not actionable, so keep it to one line.
logger.warning("GDELT fetch failed: %s", exc)
except Exception: # noqa: BLE001
logger.exception("GDELT fetch failed")
if ENABLE_QUAKES:
try:
q = await ingest_earthquakes()
@ -119,24 +116,6 @@ async def fire_loop() -> None:
await asyncio.sleep(FIRMS_INTERVAL)
async def geofence_feed_loop() -> None:
"""Hear quakes already stored, WFIGS incidents, and news map pins.
WFIGS is not persisted — fetched per active-fence bbox here (no FIRMS
or AIS key). News pins are read from ``news_items``; the summarizer
is not imported. New earthquakes also notify from ``ingest_event``.
"""
logger.info("geofence feed loop starting (interval=%ss)", INTERVAL)
while True:
try:
from geofence import scan_geofence_feeds
n = await scan_geofence_feeds()
logger.info("geofence feeds -> %d notifies", n)
except Exception: # noqa: BLE001
logger.exception("geofence feed scan failed")
await asyncio.sleep(INTERVAL)
async def main() -> None:
logger.info(
"ingester starting (rss=%d feeds, gdelt_q=%r, quakes=%s, fires=%s, interval=%ss)",
@ -147,9 +126,7 @@ async def main() -> None:
await refresh_cache()
except Exception:
logger.exception("geofence cache refresh failed (ST_Intersects still runs on ingest)")
tasks: list[asyncio.Task] = [
asyncio.create_task(geofence_feed_loop()),
]
tasks: list[asyncio.Task] = []
if ENABLE_FIRES:
# Fire ingest only starts once FIRMS_MAP_KEY is set (ingest_fires logs
# and idles otherwise).

View file

@ -314,26 +314,6 @@ class NewsMapItemOut(BaseModel):
created_at: datetime
class NewsBlipOut(BaseModel):
"""One per-article proximate geo blip as exposed by GET /api/news/blips.
Frozen wire contract (card t_bc15eb53): every graded article with a
derivable location, deduped by article id (latest grading wins).
Unlike /api/news/map this is NOT limited to critical/high items.
"""
id: int
headline: str
url: Optional[str] = None
domain: Optional[str] = None
location_name: Optional[str] = None
lat: float
lon: float
location_confidence: Optional[str] = None
category: Optional[str] = None
score: Optional[int] = None
created_at: datetime
class NewsModelId(BaseModel):
"""One model id as exposed by GET /api/news/models."""

View file

@ -2,15 +2,9 @@
from __future__ import annotations
import html
import io
import json
import logging
import os
import re
import time
import zipfile
from datetime import datetime, timedelta, timezone
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import httpx
@ -149,61 +143,6 @@ def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]:
}
# GDELT 429 backoff state. GDELT sends no Retry-After, and its block window
# grows with request volume, so the only useful reaction to a 429 is to stop
# asking: skip whole producer cycles, doubling the wait from BASE to MAX.
GDELT_BACKOFF_BASE = int(os.getenv("GDELT_BACKOFF_BASE", "300"))
GDELT_BACKOFF_MAX = int(os.getenv("GDELT_BACKOFF_MAX", "1800"))
_gdelt_backoff_secs = 0
_gdelt_backoff_until = 0.0 # time.monotonic()
def gdelt_backoff_remaining() -> float:
"""Seconds left in the GDELT cooldown window (0 = ready to call)."""
return max(0.0, _gdelt_backoff_until - time.monotonic())
def _gdelt_backoff_until_iso() -> str:
return (
datetime.now(timezone.utc).replace(microsecond=0)
+ timedelta(seconds=gdelt_backoff_remaining())
).strftime("%Y-%m-%dT%H:%M:%SZ")
def _gdelt_start_backoff(retry_after: float | None = None) -> None:
global _gdelt_backoff_secs, _gdelt_backoff_until
wait = retry_after or min(
GDELT_BACKOFF_MAX, max(GDELT_BACKOFF_BASE, _gdelt_backoff_secs * 2)
)
_gdelt_backoff_secs = int(wait)
_gdelt_backoff_until = time.monotonic() + wait
def _gdelt_clear_backoff() -> None:
global _gdelt_backoff_secs, _gdelt_backoff_until
_gdelt_backoff_secs = 0
_gdelt_backoff_until = 0.0
def _gdelt_retry_after(resp: httpx.Response) -> float | None:
"""Retry-After as seconds (delta-seconds or HTTP-date); GDELT sends neither."""
raw = resp.headers.get("retry-after")
if not raw:
return None
raw = raw.strip()
try:
return max(1.0, float(raw))
except ValueError:
pass
try:
return max(
1.0,
(parsedate_to_datetime(raw) - datetime.now(timezone.utc)).total_seconds(),
)
except (TypeError, ValueError):
return None
def _parse_gdelt_seendate(value: object) -> str:
if isinstance(value, str) and len(value) >= 15:
try:
@ -236,59 +175,25 @@ def parse_gdelt_articles(data: dict) -> list[dict]:
return events
async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50):
"""Fetch articles from the GDELT DOC 2.0 API.
GDELT enforces a per-IP quota that answers ``429`` with a plain-text body
("Please limit requests to one every 5 seconds"), sends **no** Retry-After,
and widens the block window as request volume accumulates. So a 429 is not
retried: the ingester stops calling until a backoff window expires, and the
cycle is skipped with a single log line. See ``gdelt_backoff_remaining``.
"""
remaining = gdelt_backoff_remaining()
if remaining > 0:
logger.info(
"GDELT: cooling down (%ds left after 429); skipping this cycle", int(remaining)
)
return 0
async def ingest_gdelt(query: str = "", max_articles: int = 50):
"""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)
except httpx.TransportError as exc:
# gdeltproject.org certs have expired in the wild; HTTP fallback.
# Only transport failures (TLS/connect) get the fallback — an HTTP
# error status is a quota answer and retrying it just burns the
# same per-IP budget a second time.
logger.warning("GDELT HTTPS transport error (%s); retrying HTTP", exc)
http_url = GDELT_API.replace("https://", "http://", 1)
resp = await client.get(http_url, params=params)
if resp.status_code == 429:
_gdelt_start_backoff(_gdelt_retry_after(resp))
logger.warning(
"GDELT 429 (rate limited) -> backing off until %s",
_gdelt_backoff_until_iso(),
)
return 0
try:
resp.raise_for_status()
data = resp.json()
except (httpx.HTTPStatusError, ValueError) as exc:
# GDELT also signals errors/throttling as HTTP 200 + prose, so a
# JSON decode failure is "busy", not "no results".
_gdelt_start_backoff(_gdelt_retry_after(resp))
logger.warning(
"GDELT unusable response (HTTP %s: %s) -> backing off until %s",
resp.status_code, str(exc).splitlines()[0][:120], _gdelt_backoff_until_iso(),
)
return 0
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()
_gdelt_clear_backoff()
events = parse_gdelt_articles(data if isinstance(data, dict) else {})
for event in events:
await publish_event("events.gdelt", event)
@ -296,240 +201,6 @@ async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50):
return len(events)
# ─── GDELT 2.0 15-minute bulk files (throttle-free) ─────────────────────
#
# The DOC 2.0 API is per-IP quota'd (429, no Retry-After). The same coverage is
# published every 15 minutes as static files under /gdeltv2/ with no key and no
# quota, indexed by ``lastupdate.txt``:
# *.export.CSV.zip events (CAMEO codes)
# *.mentions.CSV.zip event->article mentions (URL + confidence, no title)
# *.gkg.csv.zip Global Knowledge Graph, one row per article: URL, source
# domain, themes, locations with lat/lon, tone, and the
# page title in the V2ExtrasXML column
# GKG is the one that carries title + geo, so map a filtered row into the same
# event shape ``parse_gdelt_articles`` produces and let the existing
# ``events.gdelt`` NATS consumer + ``event_dedup`` (URL) keep working.
GDELT_BULK_ENABLED = os.getenv("GDELT_BULK_ENABLED", "1").lower() in ("1", "true", "yes")
GDELT_BULK_LASTUPDATE = os.getenv(
"GDELT_BULK_LASTUPDATE", "https://data.gdeltproject.org/gdeltv2/lastupdate.txt"
)
GDELT_BULK_MAX_EVENTS = int(os.getenv("GDELT_BULK_MAX_EVENTS", "100"))
# Newest bulk file already parsed; lastupdate.txt is re-read every cycle but the
# 15-minute file behind it only changes 4x/hour.
_gdelt_bulk_last_file: str | None = None
_PAGE_TITLE_RE = re.compile(r"<PAGE_TITLE>(.*?)</PAGE_TITLE>", re.DOTALL)
_PAGE_PUB_TS_RE = re.compile(r"<PAGE_PRECISEPUBTIMESTAMP>(\d{14})<")
def gdelt_query_terms(query: str = "") -> list[str]:
"""CONFIG GDELT query (``(unrest OR protest OR ...)``) -> plain terms.
Used to filter bulk rows against their GKG theme tokens instead of
publishing every article in the 15-minute window.
"""
q = (query or "").strip() or GDELT_DEFAULT_QUERY
terms: list[str] = []
for part in re.split(r"\s+OR\s+", q.strip().strip("()"), flags=re.IGNORECASE):
term = part.strip().strip('"').strip("'").strip().lower()
if term and term not in terms:
terms.append(term)
return terms
def _term_hits_themes(term: str, themes: str) -> bool:
"""Term matches when every word of it appears in the theme token list."""
words = [w for w in re.split(r"[\s_\-]+", term) if w]
return bool(words) and all(w in themes for w in words)
def select_gdelt_bulk_url(lastupdate_text: str) -> tuple[str, str] | None:
"""``(filename, https_url)`` of the newest GKG file in lastupdate.txt.
lastupdate.txt lists plain ``http://`` URLs, which 301 to https; normalise
so the fetch never follows a redirect into a stale mirror.
"""
for line in (lastupdate_text or "").splitlines():
parts = line.split()
if len(parts) < 3 or not parts[2].endswith(".gkg.csv.zip"):
continue
url = parts[2]
if url.startswith("http://"):
url = "https://" + url[len("http://"):]
return url.rsplit("/", 1)[-1], url
return None
def _gkg_location(field: str) -> tuple[float | None, float | None, str | None]:
"""First location in a V2Locations field -> (lat, lon, name).
V2Locations is ``type#fullname#cc#adm1[#adm2]#lat#lon#featureid``; the
adm2 slot is sometimes dropped, so read the triple from the end.
"""
segment = (field or "").split(";", 1)[0]
parts = segment.split("#")
if len(parts) < 5:
return None, None, None
name = parts[1].strip() or None
try:
lat = float(parts[-3])
lon = float(parts[-2])
except (TypeError, ValueError):
return None, None, name
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
return None, None, name
return lat, lon, name
def _gkg_tone(field: str) -> float | None:
try:
return _parse_gdelt_tone(field.split(",", 1)[0])
except (AttributeError, IndexError):
return None
def _gkg_timestamp(row: list[str], extras: str) -> str:
"""Article publish time: PAGE_PRECISEPUBTIMESTAMP, else the GKG window stamp."""
stamps = []
pub = _PAGE_PUB_TS_RE.search(extras)
if pub is not None:
stamps.append(pub.group(1))
if len(row) > 1 and isinstance(row[1], str):
stamps.append(row[1][:14])
for stamp in stamps:
try:
return datetime.strptime(stamp, "%Y%m%d%H%M%S").replace(
tzinfo=timezone.utc
).isoformat()
except ValueError:
continue
return datetime.now(timezone.utc).isoformat()
def parse_gkg_row(row: list[str], terms: list[str], bulk_file: str = "") -> dict | None:
"""Map one GKG CSV row into the ``events.gdelt`` event shape.
Returns None when the row has no usable URL or matches none of ``terms``.
"""
if len(row) < 8:
return None
url = (row[4] or "").strip()
if not url.startswith(("http://", "https://")):
return None
raw_themes = row[7] or ""
themes = raw_themes.lower()
matched = [t for t in terms if _term_hits_themes(t, themes)]
if not matched:
return None
extras = row[-1] if isinstance(row[-1], str) else ""
title_match = _PAGE_TITLE_RE.search(extras)
title = html.unescape(title_match.group(1)).strip() if title_match else None
lat = lon = loc_name = None
for idx in (9, 10):
if idx < len(row):
lat, lon, loc_name = _gkg_location(row[idx])
if lat is not None:
break
theme_tokens = [t for t in raw_themes.split(";") if t]
tags = matched + [
t for t in theme_tokens
if any(w in t.lower() for w in matched)
]
tags = list(dict.fromkeys(tags))[:10]
return {
"source_type": "gdel-t2",
"title": title,
"body": (row[3] or "").strip() or None,
"url": url,
"location_lat": lat,
"location_lon": lon,
"location_name": loc_name,
"source_timestamp": _gkg_timestamp(row, extras),
"tags": tags,
"raw": {
"gkg_record_id": row[0],
"source_common_name": row[3],
"source_collection": row[2],
"themes": theme_tokens[:12],
"tone": _gkg_tone(row[15]) if len(row) > 15 else None,
"bulk_file": bulk_file,
},
}
async def ingest_gdelt_bulk(query: str = "", max_events: int | None = None) -> int:
"""Publish new articles from the newest 15-minute GKG bulk file.
No API key, no per-IP quota, and the existing URL dedupe means re-reading
the same file after a restart publishes nothing new.
"""
global _gdelt_bulk_last_file
cap = GDELT_BULK_MAX_EVENTS if max_events is None else max_events
async with httpx.AsyncClient(
timeout=120, headers=_ua_headers(), follow_redirects=True,
) as client:
index = await client.get(GDELT_BULK_LASTUPDATE)
index.raise_for_status()
picked = select_gdelt_bulk_url(index.text)
if picked is None:
logger.warning("GDELT bulk: no .gkg file listed in lastupdate.txt")
return 0
filename, url = picked
if filename == _gdelt_bulk_last_file:
logger.debug("GDELT bulk: %s already ingested; nothing new", filename)
return 0
archive = await client.get(url)
archive.raise_for_status()
terms = gdelt_query_terms(query)
events: list[dict] = []
scanned = 0
with zipfile.ZipFile(io.BytesIO(archive.content)) as zf:
member = zf.namelist()[0]
with zf.open(member) as fh:
for line in io.TextIOWrapper(fh, encoding="utf-8", errors="replace"):
if not line.strip():
continue
scanned += 1
event = parse_gkg_row(line.rstrip("\r\n").split("\t"), terms, filename)
if event is not None and len(events) < cap:
events.append(event)
published = await _publish_unknown("events.gdelt", events)
_gdelt_bulk_last_file = filename
logger.info(
"GDELT bulk %s: %d/%d rows matched %s, %d new articles published",
filename, len(events), scanned, "/".join(terms), published,
)
return published
async def ingest_gdelt(query: str = "", max_articles: int = 50):
"""GDELT articles: throttle-free 15-minute bulk file first, DOC API fallback.
The bulk path carries the coverage; the DOC 2.0 call (with its 429 backoff)
only runs when the bulk fetch itself fails, so the per-IP quota is no longer
on the hot path.
"""
if GDELT_BULK_ENABLED:
try:
return await ingest_gdelt_bulk(query=query)
except Exception as exc: # noqa: BLE001 — any bulk failure falls back
logger.warning(
"GDELT bulk fetch failed (%s: %s); falling back to DOC API",
type(exc).__name__, str(exc)[:160],
)
return await _ingest_gdelt_doc(query=query, max_articles=max_articles)
def _parse_gdelt_tone(tone: str) -> float | None:
"""Parse GDELT tone string to a -1..1 sentiment score."""
try:

View file

@ -157,20 +157,6 @@
.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 */
@ -274,21 +260,6 @@
.marker-cluster-medium div { font-size: 11px; }
.marker-cluster-large div { font-size: 12px; }
/* ── Article blip clusters (quiet violet, matches the small blips) ── */
.marker-cluster-articles { background-color: rgba(160, 108, 213, 0.16); }
.marker-cluster-articles div {
background-color: rgba(122, 74, 160, 0.88);
color: #efe6f9;
font-weight: 600;
box-shadow: 0 0 10px rgba(160, 108, 213, 0.35), 0 0 2px rgba(3, 6, 9, 0.9);
}
.articles-sm div { font-size: 10px; }
.articles-md div { font-size: 11px; }
.articles-lg div { font-size: 12px; }
/* FIRMS heat is visual-only (no listeners) but its canvas sits on top
of the overlay pane and eats clicks meant for vector blips/pins. */
.leaflet-heatmap-layer { pointer-events: none; }
/* ── Map hint + HUD chips ── */
.map-hint {
position: absolute; left: 12px; bottom: 12px; z-index: 500;
@ -314,7 +285,6 @@
.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 .c.articles { background: #a06cd5; box-shadow: 0 0 6px rgba(160,108,213,0.6); }
.hud-chip.off { opacity: 0.4; }
#dvr-bar {
position: absolute; left: 50%; bottom: 12px; transform: translateX(-50%);
@ -373,7 +343,6 @@
.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(--cyan); box-shadow: 0 0 7px var(--cyan); }
.lp-dot.articles { background: #a06cd5; box-shadow: 0 0 7px rgba(160,108,213,0.6); }
.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; }
@ -720,7 +689,7 @@
-webkit-mask-image: linear-gradient(90deg, transparent 0, #000 26px, #000 calc(100% - 26px), transparent 100%);
}
.tick-track { display: flex; width: max-content; animation: marquee 60s linear infinite; }
.ticker.news .tick-track { animation-duration: 240s; } /* fallback; JS sets constant px/s */
.ticker.news .tick-track { animation-duration: 90s; }
.tick-wrap:hover .tick-track, .tick-wrap:focus-within .tick-track { animation-play-state: paused; }
@keyframes marquee { from { transform: translateX(0); } to { transform: translateX(-50%); } }
.tick-group { display: flex; align-items: center; }
@ -906,7 +875,6 @@
<span class="sep hide-sm" id="swpc-sep" hidden>|</span>
<span class="hide-sm" id="swpc-chip" hidden title="NOAA SWPC planetary K-index">Kp —</span>
</div>
<a class="admin-link" id="admin-link" href="/login" data-anon-label="SIGN IN">SIGN IN</a>
<div class="nav">
<button id="nav-btn" class="nav-btn" aria-haspopup="true" aria-expanded="false">
MENU <span class="nav-caret">▾</span>
@ -918,10 +886,10 @@
<button class="nav-item" role="menuitem" data-view="events"><span class="ico">≣</span>Events</button>
<button class="nav-item" role="menuitem" data-view="alerts"><span class="ico">⚠</span>Alerts</button>
<button class="nav-item" role="menuitem" data-view="entities"><span class="ico">◎</span>Entities</button>
<button class="nav-item" role="menuitem" data-view="ingest" data-admin><span class="ico">⇪</span>Ingest</button>
<button class="nav-item" role="menuitem" data-view="keys" data-admin><span class="ico">⚿</span>API Keys</button>
<div class="nav-sep" role="separator" data-admin></div>
<button class="nav-item" role="menuitem" data-view="settings" data-admin><span class="ico">⚙</span>Settings</button>
<button class="nav-item" role="menuitem" data-view="ingest"><span class="ico">⇪</span>Ingest</button>
<button class="nav-item" role="menuitem" data-view="keys"><span class="ico">⚿</span>API Keys</button>
<div class="nav-sep" role="separator"></div>
<button class="nav-item" role="menuitem" data-view="settings"><span class="ico">⚙</span>Settings</button>
</div>
</div>
</div>
@ -965,7 +933,7 @@
<div class="lp-opacity">Opacity <input type="range" id="lp-base-opacity" min="5" max="100" value="100" oninput="setBaseOpacity(this.value)"><b id="lp-base-val">100%</b></div>
</div>
<div class="lp-layer">
<div class="lp-row gf-draw-row" data-admin>
<div class="lp-row gf-draw-row">
<button class="btn" id="gf-draw" type="button" onclick="toggleGeofenceDraw()" title="Tap vertices, then Finish">Draw geofence</button>
<button class="btn" id="gf-finish" type="button" hidden onclick="onGfClose(event)">Finish</button>
<button class="btn" id="gf-cancel" type="button" hidden onclick="cancelGeofenceDraw()">Cancel</button>
@ -1034,12 +1002,6 @@
<span class="lp-count" id="lp-news-count">0</span>
</div>
</div>
<div class="lp-layer">
<div class="lp-row">
<label class="lp-name" title="Per-article proximate locations from the news feed (last 24h)"><input type="checkbox" id="lp-articles-on" onchange="toggleArticleBlips()"> <span class="lp-dot articles"></span> Article Blips</label>
<span class="lp-count" id="lp-articles-count">0</span>
</div>
</div>
<div class="lp-layer">
<div class="lp-row">
@ -1144,7 +1106,6 @@
<div class="hud-chip" id="hud-cams"><span class="c cams"></span>CAMS <b id="hud-cams-n">—</b></div>
<div class="hud-chip" id="hud-blips"><span class="c blips"></span>BLIPS <b id="hud-blips-n">—</b></div>
<div class="hud-chip" id="hud-news"><span class="c news"></span>NEWS <b id="hud-news-n">—</b></div>
<div class="hud-chip" id="hud-articles"><span class="c articles"></span>ARTICLES <b id="hud-articles-n">—</b></div>
</div>
<div id="cheat-sheet" class="cheat-sheet" hidden role="dialog" aria-label="Keyboard shortcuts">
<h3>Shortcuts</h3>
@ -1277,7 +1238,7 @@
</section>
<!-- ───────────── VIEW: INGEST ───────────── -->
<section class="view" id="view-ingest" aria-label="Ingest" data-admin>
<section class="view" id="view-ingest" aria-label="Ingest">
<div class="subview">
<h2><span class="tick">⇪</span> Data Ingestion</h2>
<p class="sub">Manually trigger feed pulls &amp; NATS processing</p>
@ -1310,7 +1271,7 @@
</section>
<!-- ───────────── VIEW: API KEYS ───────────── -->
<section class="view" id="view-keys" aria-label="API keys" data-admin>
<section class="view" id="view-keys" aria-label="API keys">
<div class="subview">
<h2><span class="tick">⚿</span> API Keys</h2>
<p class="sub">Keys used by ingest services (FIRMS, Nous Portal, Telegram, AIS, …). Stored in Postgres, never shown again — only status + last 4 chars.</p>
@ -1337,7 +1298,7 @@
</div>
<div class="set-saved" id="mkt-saved"></div>
</div>
<div class="panel" data-admin>
<div class="panel">
<h3>News Summarizer</h3>
<p class="set-note" style="margin-bottom:0.9rem">Takes effect on the next 15-min run. No container restart.</p>
<div class="set-row">
@ -1521,7 +1482,6 @@ const COUNT_HUD = {
'lp-cams-count': 'hud-cams-n',
'lp-blips-count': 'hud-blips-n',
'lp-news-count': 'hud-news-n',
'lp-articles-count': 'hud-articles-n',
};
function setLayerCount(id, value) {
const el = document.getElementById(id);
@ -1533,23 +1493,6 @@ 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 {
@ -1558,7 +1501,6 @@ 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,
@ -1684,40 +1626,6 @@ 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'];
@ -1764,7 +1672,6 @@ 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);
});
@ -1781,7 +1688,6 @@ function showView(name) {
if (camsOn) loadCams();
if (blipsOn) loadBlips();
if (newsOn) loadNewsPins();
if (articlesOn) loadArticleBlips();
}
}
if (name === 'news') loadNews(false);
@ -1874,7 +1780,6 @@ function initMarketTicker() {
/* ═══════════════ NEWS FEED + TICKER ═══════════════ */
let newsInterval = null;
const NEWS_REFRESH_MS = 180000; // 3-min ticker/brief poll
const NEWS_TICKER_PX_PER_S = 28; // constant readable scroll speed for the news ticker
let newsTickerBuilt = false;
function newsEsc(s) {
@ -2017,13 +1922,6 @@ function renderNewsTicker(articles, summaries, tickerItems) {
items = `<span class="tick-item standby">No headlines yet — scraper idle</span>`;
}
track.innerHTML = `<span class="tick-group">${items}</span><span class="tick-group">${items}</span>`;
// Constant pixel speed regardless of headline count: the marquee travels
// one group width (track = two identical copies, keyframe goes to -50%).
// Recomputed on every rebuild; market ticker keeps its own CSS duration.
const groupWidth = track.scrollWidth / 2;
track.style.animationDuration = groupWidth > 0
? `${(groupWidth / NEWS_TICKER_PX_PER_S).toFixed(2)}s`
: '';
newsTickerBuilt = true;
}
@ -2357,8 +2255,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, newsRenderer = null;
let articlesGroup = null, articlesOn = false, articlesReq = 0, articlesTimer = null, articlesRenderer = null;
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)
@ -2522,17 +2419,6 @@ function overlayFetch(url) {
return fetch(url, overlayAbort ? { signal: overlayAbort.signal } : {});
}
function isAbort(e) { return e && e.name === 'AbortError'; }
/* Leaflet 1.9.4 race guard: a moveend-driven _updatePaths() calls _redraw()
directly, which nulls _redrawRequest WITHOUT cancelling an already-pending
animation frame. If the renderer is removed before that orphaned frame
fires (e.g. layer toggle-off), _redraw crashes on the deleted 2d context
("Cannot read properties of undefined (reading 'clearRect')"). No-op
redraws on detached renderers instead; live renderers are unaffected. */
const _canvasRedraw = L.Canvas.prototype._redraw;
L.Canvas.prototype._redraw = function () {
if (!this._ctx) return;
return _canvasRedraw.apply(this, arguments);
};
const pointCanvas = () => L.canvas({ padding: 0.5 });
async function initMap() {
@ -2547,12 +2433,10 @@ async function initMap() {
const sel = document.getElementById('map-layer');
sel.innerHTML = mapLayers.map(l =>
`<option value="${l.id}">${l.title}</option>`).join('');
// Blue Marble first: static, gap-free basemap. Satellite true-color
// (VIIRS/MODIS) has cloud/coverage gaps — still selectable below.
const preferred =
mapLayers.find(l => l.id === 'BlueMarble_ShadedRelief_Bathymetry')
|| mapLayers.find(l => l.id === 'VIIRS_SNPP_CorrectedReflectance_TrueColor')
mapLayers.find(l => l.id === 'VIIRS_SNPP_CorrectedReflectance_TrueColor')
|| mapLayers.find(l => l.id === 'MODIS_Terra_CorrectedReflectance_TrueColor')
|| mapLayers.find(l => l.id === 'BlueMarble_ShadedRelief_Bathymetry')
|| mapLayers.find(l => !l.has_time)
|| mapLayers[0];
if (preferred) sel.value = preferred.id;
@ -2659,7 +2543,6 @@ async function initMap() {
if (camsOn) loadCams();
if (blipsOn) loadBlips();
if (newsOn) loadNewsPins();
if (articlesOn) loadArticleBlips();
refreshLiveOverlays();
sendLiveViewport();
}, 500);
@ -2672,7 +2555,6 @@ async function initMap() {
camsOn = document.getElementById('lp-cams-on').checked;
blipsOn = document.getElementById('lp-blips-on').checked;
newsOn = document.getElementById('lp-news-on').checked;
articlesOn = document.getElementById('lp-articles-on').checked;
firesSince = document.getElementById('lp-fires-since').value;
blipsSince = document.getElementById('lp-blips-since').value;
radarOn = document.getElementById('lp-radar-on').checked;
@ -2695,7 +2577,6 @@ async function initMap() {
if (camsOn) loadCams();
if (blipsOn) loadBlips();
if (newsOn) loadNewsPins();
if (articlesOn) loadArticleBlips();
refreshLiveOverlays();
}, 250);
});
@ -2718,9 +2599,8 @@ function syncHud() {
set('cams', camsOn);
set('blips', blipsOn);
set('news', newsOn);
set('articles', articlesOn);
}
let hudFiresCount = null, hudCamsCount = null, hudBlipsCount = null, hudNewsCount = null, hudArticlesCount = null;
let hudFiresCount = null, hudCamsCount = null, hudBlipsCount = null, hudNewsCount = null;
function setMapAttribution(text) {
if (!map) return;
@ -3302,7 +3182,6 @@ async function toggleNewsPins() {
}
newsReq++;
if (newsGroup && map) { map.removeLayer(newsGroup); newsGroup = null; }
if (newsRenderer && map) { map.removeLayer(newsRenderer); newsRenderer = null; }
hudNewsCount = null;
setLayerCount('lp-news-count', '0');
syncHud();
@ -3318,16 +3197,11 @@ async function loadNewsPins() {
const items = Array.isArray(data) ? data : [];
if (newsGroup) map.removeLayer(newsGroup);
const col = '#35e0ff';
// One persistent canvas renderer shared by ALL pins: L.Canvas
// hit-tests every drawn path, so each pin stays clickable (a fresh
// canvas per pin stacked empty siblings over all but the last), and
// reusing it across refreshes leaks no full-viewport containers.
const renderer = newsRenderer || (newsRenderer = L.canvas({ padding: 0.5 }));
const pins = items.filter(it => Number.isFinite(Number(it.lat)) && Number.isFinite(Number(it.lon)));
newsGroup = L.layerGroup(pins.map(it => {
return L.circleMarker([it.lat, it.lon], {
radius: 6, weight: 1, color: col, fillColor: col, fillOpacity: 0.7,
renderer,
renderer: pointCanvas(),
})
.bindPopup(`<div class="blip-pop">` +
`<div class="blip-src">◈ ${esc(it.importance || '')}${it.category ? ' · ' + esc(it.category) : ''}</div>` +
@ -3347,106 +3221,6 @@ async function loadNewsPins() {
}
}
/* ── ARTICLE BLIPS (per-article proximate geo, all severities) ──
GET /api/news/blips — dense field of small clustered circleMarkers.
Separate from the critical-pin layer above; default OFF. Until the
backend endpoint lands, a 404 idles the layer at 0 without breaking
the map or the critical pins. */
const ARTICLE_BLIP_COL = '#a06cd5'; // quiet violet — critical pins are cyan
function articleBlipPopup(b) {
const loc = esc(b.location_name || 'no location label') +
(b.location_confidence ? ' (' + esc(b.location_confidence) + ')' : '');
const meta = [newsTimeAgo(b.created_at), loc];
if (b.score != null) meta.push('score ' + esc(b.score));
return `<div class="blip-pop">` +
`<div class="blip-src">◈ ${esc(b.domain || 'article')}${b.category ? ' · ' + esc(b.category) : ''}</div>` +
`<b>${esc(b.headline || 'Untitled article')}</b>` +
`<div class="blip-time">${meta.join(' · ')}</div>` +
(b.url ? `<a href="${esc(b.url)}" target="_blank" rel="noopener">source ↗</a>` : '') +
`</div>`;
}
async function toggleArticleBlips() {
articlesOn = document.getElementById('lp-articles-on').checked;
if (articlesOn) {
await loadArticleBlips();
// Same cadence as the news poll; own timer so the layer refreshes
// even when the News view (which starts newsInterval) was never opened.
if (!articlesTimer) articlesTimer = setInterval(() => { if (articlesOn) loadArticleBlips(); }, NEWS_REFRESH_MS);
return;
}
articlesReq++;
if (articlesTimer) { clearInterval(articlesTimer); articlesTimer = null; }
articlesGroup = dropLayer(articlesGroup);
if (articlesRenderer && map) { map.removeLayer(articlesRenderer); articlesRenderer = null; }
hudArticlesCount = null;
setLayerCount('lp-articles-count', '0');
syncHud();
}
async function loadArticleBlips() {
if (!map) return;
const req = ++articlesReq;
const zero = () => {
articlesGroup = dropLayer(articlesGroup);
hudArticlesCount = 0;
setLayerCount('lp-articles-count', '0');
syncHud();
};
try {
const r = await overlayFetch(`${API}/api/news/blips?bbox=${currentBBox()}&limit=1000`);
if (req !== articlesReq) return; // superseded by a newer pan/zoom
if (!r.ok) {
console.warn(`Article blips: /api/news/blips ${r.status} — layer idle`);
zero();
return;
}
const data = await r.json();
if (req !== articlesReq) return;
const seen = new Set();
const rows = (Array.isArray(data) ? data : []).filter(b => {
if (!Number.isFinite(Number(b.lat)) || !Number.isFinite(Number(b.lon))) return false;
if (b.id != null) { if (seen.has(b.id)) return false; seen.add(b.id); }
return true;
});
articlesGroup = dropLayer(articlesGroup);
// One persistent SVG renderer: paths are individually clickable and
// the pe:none root lets clicks fall through to the canvas pins below
// (Leaflet stacks svg z200 over canvas z100). A fresh renderer per
// refresh would leak a full-viewport container on every pan/zoom.
const renderer = articlesRenderer || (articlesRenderer = L.svg({ padding: 0.5 }));
const markers = rows.map(b => L.circleMarker([Number(b.lat), Number(b.lon)], {
radius: 3, weight: 1, color: ARTICLE_BLIP_COL, fillColor: ARTICLE_BLIP_COL,
fillOpacity: 0.5, opacity: 0.75, renderer,
}).bindPopup(articleBlipPopup(b)));
articlesGroup = L.markerClusterGroup({
maxClusterRadius: 40,
showCoverageOnHover: false,
spiderfyOnMaxZoom: true,
chunkedLoading: true,
chunkInterval: 100,
chunkDelay: 10,
iconCreateFunction: (cluster) => {
const n = cluster.getChildCount();
const size = n < 10 ? 'sm' : n < 100 ? 'md' : 'lg';
return L.divIcon({
html: '<div><span>' + n + '</span></div>',
className: 'marker-cluster marker-cluster-articles articles-' + size,
iconSize: L.point(40, 40),
});
},
});
articlesGroup.addLayers(markers);
articlesGroup.addTo(map);
setLayerCount('lp-articles-count', rows.length.toLocaleString());
hudArticlesCount = rows.length;
syncHud();
} catch (e) {
if (isAbort(e)) return;
if (req !== articlesReq) return;
console.warn('Article blips load failed', e);
zero();
}
}
/* ── Live overlays (radar / alerts / WFIGS / aircraft / trains / AIS / NHC) ── */
function refreshLiveOverlays() {
if (!map) return;
@ -4380,8 +4154,6 @@ async function loadConflicts(paint) {
}
/* ═══════════════ INITIAL LOAD ═══════════════ */
document.getElementById('admin-link').addEventListener('click', onAdminLink);
initAuth();
initNav();
initHudKeys();
initSettings();
@ -4525,53 +4297,6 @@ function gfHitTime(p) {
if (Number.isNaN(d.getTime())) return String(raw).slice(11, 19) || '—';
return d.toISOString().slice(11, 19) + 'Z';
}
function gfEvidence(p) {
if (!p || typeof p !== 'object') return null;
let payload = p.payload;
if (typeof payload === 'string') {
try { payload = JSON.parse(payload); }
catch (e) { payload = null; }
}
if (payload && typeof payload === 'object' && payload.evidence && typeof payload.evidence === 'object') {
return payload.evidence;
}
if (p.evidence && typeof p.evidence === 'object') return p.evidence;
return null;
}
function gfNewsHref(url) {
const u = String(url == null ? '' : url).trim();
if (!u) return '';
const low = u.slice(0, 16).toLowerCase();
if (low.startsWith('rtsp:') || low.startsWith('javascript:') || low.startsWith('data:')) return '';
return u;
}
function gfHitEvidenceHtml(ev) {
if (!ev || typeof ev !== 'object' || Array.isArray(ev)) return '';
const cams = Array.isArray(ev.cameras) ? ev.cameras.slice(0, 5) : [];
const news = Array.isArray(ev.news) ? ev.news.slice(0, 3) : [];
const bits = [];
if (cams.length) {
const first = cams[0] && typeof cams[0] === 'object' ? cams[0] : {};
const name = first.name == null ? '' : String(first.name).trim();
let line = cams.length + ' cams';
if (name) line += ' · ' + newsEsc(name);
bits.push(line);
}
const item = news[0] && typeof news[0] === 'object' ? news[0] : null;
const headline = item && item.headline != null ? String(item.headline).trim() : '';
if (headline) {
const href = gfNewsHref(item.url);
if (href) {
bits.push(
`<a href="${newsEsc(href)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">${newsEsc(headline)}</a>`
);
} else {
bits.push(newsEsc(headline));
}
}
if (!bits.length) return '';
return `<span class="gf-hit-ev">${bits.join(' · ')}</span>`;
}
function pushGfInbox(p) {
if (!p) return;
const box = document.getElementById('gf-inbox');
@ -4584,16 +4309,9 @@ function pushGfInbox(p) {
el.dataset.gid = gid;
if (p.lat != null) el.dataset.lat = String(p.lat);
if (p.lon != null) el.dataset.lon = String(p.lon);
const meta = `<span class="gf-hit-meta">${newsEsc(gfHitTime(p))}</span> · ${newsEsc(name)}` +
el.innerHTML = `<span class="gf-hit-meta">${newsEsc(gfHitTime(p))}</span> · ${newsEsc(name)}` +
` · ${newsEsc(p.source_kind || '')} · ${newsEsc(p.entity_id || '')}`;
let ev = '';
try { ev = gfHitEvidenceHtml(gfEvidence(p)); } catch (e) { ev = ''; }
el.innerHTML = ev ? meta + '<br>' + ev : meta;
el.onclick = (clickEv) => {
const t = clickEv && clickEv.target;
if (t && t.closest && t.closest('a')) return;
onGfHitClick(el);
};
el.onclick = () => onGfHitClick(el);
box.prepend(el);
while (box.children.length > 50) box.removeChild(box.lastChild);
}
@ -4775,13 +4493,13 @@ async function loadGeofences() {
const on = f.active === false ? '' : ' checked';
const sel = f.id === gfSelectedId ? ' selected' : '';
return `<div class="gf-item${sel}" data-id="${id}">` +
`<input class="gf-active" type="checkbox"${on} aria-label="Active" data-admin ` +
`<input class="gf-active" type="checkbox"${on} aria-label="Active" ` +
`onchange="patchGfActive('${id}', this.checked)">` +
`<button type="button" class="gf-name" title="${name}" onclick="onGfNameClick('${id}')">${name}</button>` +
`<span class="gf-actions">` +
`<button class="gf-go" type="button" onclick="goGeofence('${id}')">Go</button>` +
`<button class="gf-ren" type="button" aria-label="Rename" data-admin onclick="renameGeofence('${id}')">Aa</button>` +
`<button class="gf-del" type="button" data-admin onclick="deleteGeofence('${id}')">Delete</button>` +
`<button class="gf-ren" type="button" aria-label="Rename" onclick="renameGeofence('${id}')">Aa</button>` +
`<button class="gf-del" type="button" onclick="deleteGeofence('${id}')">Delete</button>` +
`</span></div>`;
}).join('');
}
@ -4806,8 +4524,8 @@ async function loadGeofences() {
const chk = active ? ' checked' : '';
layer.bindPopup(
`<div class="gf-pop"><b>${name}</b><br>` +
`<label data-admin><input type="checkbox"${chk} onchange="patchGfActive('${newsEsc(id)}', this.checked)"> active</label><br>` +
`<button class="gf-del" type="button" data-admin onclick="deleteGeofence('${newsEsc(id)}')">Delete</button></div>`
`<label><input type="checkbox"${chk} onchange="patchGfActive('${newsEsc(id)}', this.checked)"> active</label><br>` +
`<button class="gf-del" type="button" onclick="deleteGeofence('${newsEsc(id)}')">Delete</button></div>`
);
},
}).addTo(map);

View file

@ -1,86 +0,0 @@
# 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$<iterations>$<salt_b64>$<hash_b64>`. |
| `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.
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
`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.

View file

@ -43,10 +43,7 @@ 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 `<item>` link, extracts the main article body, and
the `PostgresPipeline` writes to `articles` with URL-based dedup
(`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.
(`ON CONFLICT (url) DO NOTHING`).
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
@ -63,46 +60,8 @@ 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` 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 <n>:` 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, 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
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.
`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items`.
Container startup order doesn't matter.
## Keys and Settings
@ -281,13 +240,7 @@ 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_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). |
| `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. |

View file

@ -3,7 +3,6 @@
from __future__ import annotations
import datetime
import re
from email.utils import parsedate_to_datetime
from urllib.parse import urlparse
@ -31,26 +30,3 @@ def article_timestamp(pub_date: str | None) -> datetime.datetime:
except ValueError:
pass
return datetime.datetime.now(datetime.timezone.utc)
# Whole-title CDATA wrapper only. Keep in sync with app/news_title.py —
# the scraper image and the API image do not share a package.
_CDATA_WRAPPER = re.compile(
r"\A\s*<!\[CDATA\[(.*?)\]\]>\s*\Z",
re.DOTALL,
)
def unwrap_cdata_title(title):
"""Strip a surrounding CDATA wrapper. Anything else is unchanged.
``<![CDATA[Hello]]>`` and ``\\n <![CDATA[Hello]]>`` become
``Hello``. Real HTML (``<b>Hello</b>``) and a title that merely contains
the markers are returned as-is. Non-strings pass through.
"""
if not isinstance(title, str):
return title
match = _CDATA_WRAPPER.match(title)
if match is None:
return title
return match.group(1).strip()

View file

@ -3,51 +3,10 @@
# 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
from newsScraper.feed_util import unwrap_cdata_title
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):
@ -55,8 +14,6 @@ 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):
@ -97,16 +54,9 @@ 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)
item['title'] = unwrap_cdata_title(item['title'])
try:
self.cur.execute("""
INSERT INTO articles (title, url, content, domain, timestamp)
@ -132,11 +82,6 @@ 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()

View file

@ -13,8 +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 intel.py nous_client.py gazetteer.py ./
COPY data/ ./data/
COPY summarizer.py run_news_summarizer.py intel.py nous_client.py ./
# Security: run as a non-privileged user.
RUN useradd -m summarizer_user

View file

@ -1,28 +0,0 @@
# GeoNames reference data (offline gazetteer)
Vendored from GeoNames (https://www.geonames.org/), licensed CC-BY 4.0
(https://creativecommons.org/licenses/by/4.0/). Attribution: "GeoNames"
(https://www.geonames.org/) — the summarizer resolves place names to
proximate coordinates fully offline from these files; no geocoding API
is called at runtime.
## Files
- `cities15000.tsv` — trimmed `cities15000.txt` dump (all cities with
population > 15000, ~34k rows). Columns (tab-separated, no header):
`name asciiname latitude longitude population country_code admin1_code`
Source: https://download.geonames.org/export/dump/cities15000.zip
- `admin1.tsv` — trimmed `admin1CodesASCII.txt` (~3.9k first-level
divisions: states/regions). Columns: `code name asciiname`
(code is `CC.A1`, e.g. `US.TX`). Used to disambiguate "Paris, Texas"
from "Paris, France".
Source: https://download.geonames.org/export/dump/admin1CodesASCII.txt
- `countries.tsv` — trimmed `countryInfo.txt` (252 rows). Columns:
`iso_code country_name capital`
Source: https://download.geonames.org/export/dump/countryInfo.txt
Country-level lookups resolve to the capital's coordinates (the
countryInfo dump carries no centroid), confidence "approx".
Refresh: re-download the dumps, keep the same column layout. The loader
(`../gazetteer.py`) tolerates extra/missing trailing columns and skips
malformed rows.

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,252 +0,0 @@
AD Andorra Andorra la Vella
AE United Arab Emirates Abu Dhabi
AF Afghanistan Kabul
AG Antigua and Barbuda St. John's
AI Anguilla The Valley
AL Albania Tirana
AM Armenia Yerevan
AO Angola Luanda
AQ Antarctica
AR Argentina Buenos Aires
AS American Samoa Pago Pago
AT Austria Vienna
AU Australia Canberra
AW Aruba Oranjestad
AX Aland Islands Mariehamn
AZ Azerbaijan Baku
BA Bosnia and Herzegovina Sarajevo
BB Barbados Bridgetown
BD Bangladesh Dhaka
BE Belgium Brussels
BF Burkina Faso Ouagadougou
BG Bulgaria Sofia
BH Bahrain Manama
BI Burundi Gitega
BJ Benin Porto-Novo
BL Saint Barthelemy Gustavia
BM Bermuda Hamilton
BN Brunei Bandar Seri Begawan
BO Bolivia Sucre
BQ Bonaire, Saint Eustatius and Saba
BR Brazil Brasilia
BS Bahamas Nassau
BT Bhutan Thimphu
BV Bouvet Island
BW Botswana Gaborone
BY Belarus Minsk
BZ Belize Belmopan
CA Canada Ottawa
CC Cocos Islands West Island
CD Democratic Republic of the Congo Kinshasa
CF Central African Republic Bangui
CG Republic of the Congo Brazzaville
CH Switzerland Bern
CI Ivory Coast Yamoussoukro
CK Cook Islands Avarua
CL Chile Santiago
CM Cameroon Yaounde
CN China Beijing
CO Colombia Bogota
CR Costa Rica San Jose
CU Cuba Havana
CV Cabo Verde Praia
CW Curacao Willemstad
CX Christmas Island Flying Fish Cove
CY Cyprus Nicosia
CZ Czechia Prague
DE Germany Berlin
DJ Djibouti Djibouti
DK Denmark Copenhagen
DM Dominica Roseau
DO Dominican Republic Santo Domingo
DZ Algeria Algiers
EC Ecuador Quito
EE Estonia Tallinn
EG Egypt Cairo
EH Western Sahara El-Aaiun
ER Eritrea Asmara
ES Spain Madrid
ET Ethiopia Addis Ababa
FI Finland Helsinki
FJ Fiji Suva
FK Falkland Islands Stanley
FM Micronesia Palikir
FO Faroe Islands Torshavn
FR France Paris
GA Gabon Libreville
GB United Kingdom London
GD Grenada St. George's
GE Georgia Tbilisi
GF French Guiana Cayenne
GG Guernsey St Peter Port
GH Ghana Accra
GI Gibraltar Gibraltar
GL Greenland Nuuk
GM Gambia Banjul
GN Guinea Conakry
GP Guadeloupe Basse-Terre
GQ Equatorial Guinea Ciudad de la Paz
GR Greece Athens
GS South Georgia and the South Sandwich Islands Grytviken
GT Guatemala Guatemala City
GU Guam Hagatna
GW Guinea-Bissau Bissau
GY Guyana Georgetown
HK Hong Kong Hong Kong
HM Heard Island and McDonald Islands
HN Honduras Tegucigalpa
HR Croatia Zagreb
HT Haiti Port-au-Prince
HU Hungary Budapest
ID Indonesia Jakarta
IE Ireland Dublin
IL Israel Jerusalem
IM Isle of Man Douglas
IN India New Delhi
IO British Indian Ocean Territory Diego Garcia
IQ Iraq Baghdad
IR Iran Tehran
IS Iceland Reykjavik
IT Italy Rome
JE Jersey Saint Helier
JM Jamaica Kingston
JO Jordan Amman
JP Japan Tokyo
KE Kenya Nairobi
KG Kyrgyzstan Bishkek
KH Cambodia Phnom Penh
KI Kiribati Tarawa
KM Comoros Moroni
KN Saint Kitts and Nevis Basseterre
KP North Korea Pyongyang
KR South Korea Seoul
XK Kosovo Pristina
KW Kuwait Kuwait City
KY Cayman Islands George Town
KZ Kazakhstan Nur-Sultan
LA Laos Vientiane
LB Lebanon Beirut
LC Saint Lucia Castries
LI Liechtenstein Vaduz
LK Sri Lanka Colombo
LR Liberia Monrovia
LS Lesotho Maseru
LT Lithuania Vilnius
LU Luxembourg Luxembourg
LV Latvia Riga
LY Libya Tripoli
MA Morocco Rabat
MC Monaco Monaco
MD Moldova Chisinau
ME Montenegro Podgorica
MF Saint Martin Marigot
MG Madagascar Antananarivo
MH Marshall Islands Majuro
MK North Macedonia Skopje
ML Mali Bamako
MM Myanmar Nay Pyi Taw
MN Mongolia Ulaanbaatar
MO Macao Macao
MP Northern Mariana Islands Saipan
MQ Martinique Fort-de-France
MR Mauritania Nouakchott
MS Montserrat Plymouth
MT Malta Valletta
MU Mauritius Port Louis
MV Maldives Male
MW Malawi Lilongwe
MX Mexico Mexico City
MY Malaysia Kuala Lumpur
MZ Mozambique Maputo
NA Namibia Windhoek
NC New Caledonia Noumea
NE Niger Niamey
NF Norfolk Island Kingston
NG Nigeria Abuja
NI Nicaragua Managua
NL The Netherlands Amsterdam
NO Norway Oslo
NP Nepal Kathmandu
NR Nauru Yaren
NU Niue Alofi
NZ New Zealand Wellington
OM Oman Muscat
PA Panama Panama City
PE Peru Lima
PF French Polynesia Papeete
PG Papua New Guinea Port Moresby
PH Philippines Manila
PK Pakistan Islamabad
PL Poland Warsaw
PM Saint Pierre and Miquelon Saint-Pierre
PN Pitcairn Adamstown
PR Puerto Rico San Juan
PS Palestinian Territory East Jerusalem
PT Portugal Lisbon
PW Palau Melekeok
PY Paraguay Asuncion
QA Qatar Doha
RE Reunion Saint-Denis
RO Romania Bucharest
RS Serbia Belgrade
RU Russia Moscow
RW Rwanda Kigali
SA Saudi Arabia Riyadh
SB Solomon Islands Honiara
SC Seychelles Victoria
SD Sudan Khartoum
SS South Sudan Juba
SE Sweden Stockholm
SG Singapore Singapore
SH Saint Helena Jamestown
SI Slovenia Ljubljana
SJ Svalbard and Jan Mayen Longyearbyen
SK Slovakia Bratislava
SL Sierra Leone Freetown
SM San Marino San Marino
SN Senegal Dakar
SO Somalia Mogadishu
SR Suriname Paramaribo
ST Sao Tome and Principe Sao Tome
SV El Salvador San Salvador
SX Sint Maarten Philipsburg
SY Syria Damascus
SZ Eswatini Mbabane
TC Turks and Caicos Islands Cockburn Town
TD Chad N'Djamena
TF French Southern Territories Port-aux-Francais
TG Togo Lome
TH Thailand Bangkok
TJ Tajikistan Dushanbe
TK Tokelau
TL Timor Leste Dili
TM Turkmenistan Ashgabat
TN Tunisia Tunis
TO Tonga Nuku'alofa
TR Turkey Ankara
TT Trinidad and Tobago Port of Spain
TV Tuvalu Funafuti
TW Taiwan Taipei
TZ Tanzania Dodoma
UA Ukraine Kyiv
UG Uganda Kampala
UM United States Minor Outlying Islands
US United States Washington
UY Uruguay Montevideo
UZ Uzbekistan Tashkent
VA Vatican Vatican City
VC Saint Vincent and the Grenadines Kingstown
VE Venezuela Caracas
VG British Virgin Islands Road Town
VI U.S. Virgin Islands Charlotte Amalie
VN Vietnam Hanoi
VU Vanuatu Port Vila
WF Wallis and Futuna Mata Utu
WS Samoa Apia
YE Yemen Sanaa
YT Mayotte Mamoudzou
ZA South Africa Pretoria
ZM Zambia Lusaka
ZW Zimbabwe Harare
CS Serbia and Montenegro Belgrade
AN Netherlands Antilles Willemstad
1 AD Andorra Andorra la Vella
2 AE United Arab Emirates Abu Dhabi
3 AF Afghanistan Kabul
4 AG Antigua and Barbuda St. John's
5 AI Anguilla The Valley
6 AL Albania Tirana
7 AM Armenia Yerevan
8 AO Angola Luanda
9 AQ Antarctica
10 AR Argentina Buenos Aires
11 AS American Samoa Pago Pago
12 AT Austria Vienna
13 AU Australia Canberra
14 AW Aruba Oranjestad
15 AX Aland Islands Mariehamn
16 AZ Azerbaijan Baku
17 BA Bosnia and Herzegovina Sarajevo
18 BB Barbados Bridgetown
19 BD Bangladesh Dhaka
20 BE Belgium Brussels
21 BF Burkina Faso Ouagadougou
22 BG Bulgaria Sofia
23 BH Bahrain Manama
24 BI Burundi Gitega
25 BJ Benin Porto-Novo
26 BL Saint Barthelemy Gustavia
27 BM Bermuda Hamilton
28 BN Brunei Bandar Seri Begawan
29 BO Bolivia Sucre
30 BQ Bonaire, Saint Eustatius and Saba
31 BR Brazil Brasilia
32 BS Bahamas Nassau
33 BT Bhutan Thimphu
34 BV Bouvet Island
35 BW Botswana Gaborone
36 BY Belarus Minsk
37 BZ Belize Belmopan
38 CA Canada Ottawa
39 CC Cocos Islands West Island
40 CD Democratic Republic of the Congo Kinshasa
41 CF Central African Republic Bangui
42 CG Republic of the Congo Brazzaville
43 CH Switzerland Bern
44 CI Ivory Coast Yamoussoukro
45 CK Cook Islands Avarua
46 CL Chile Santiago
47 CM Cameroon Yaounde
48 CN China Beijing
49 CO Colombia Bogota
50 CR Costa Rica San Jose
51 CU Cuba Havana
52 CV Cabo Verde Praia
53 CW Curacao Willemstad
54 CX Christmas Island Flying Fish Cove
55 CY Cyprus Nicosia
56 CZ Czechia Prague
57 DE Germany Berlin
58 DJ Djibouti Djibouti
59 DK Denmark Copenhagen
60 DM Dominica Roseau
61 DO Dominican Republic Santo Domingo
62 DZ Algeria Algiers
63 EC Ecuador Quito
64 EE Estonia Tallinn
65 EG Egypt Cairo
66 EH Western Sahara El-Aaiun
67 ER Eritrea Asmara
68 ES Spain Madrid
69 ET Ethiopia Addis Ababa
70 FI Finland Helsinki
71 FJ Fiji Suva
72 FK Falkland Islands Stanley
73 FM Micronesia Palikir
74 FO Faroe Islands Torshavn
75 FR France Paris
76 GA Gabon Libreville
77 GB United Kingdom London
78 GD Grenada St. George's
79 GE Georgia Tbilisi
80 GF French Guiana Cayenne
81 GG Guernsey St Peter Port
82 GH Ghana Accra
83 GI Gibraltar Gibraltar
84 GL Greenland Nuuk
85 GM Gambia Banjul
86 GN Guinea Conakry
87 GP Guadeloupe Basse-Terre
88 GQ Equatorial Guinea Ciudad de la Paz
89 GR Greece Athens
90 GS South Georgia and the South Sandwich Islands Grytviken
91 GT Guatemala Guatemala City
92 GU Guam Hagatna
93 GW Guinea-Bissau Bissau
94 GY Guyana Georgetown
95 HK Hong Kong Hong Kong
96 HM Heard Island and McDonald Islands
97 HN Honduras Tegucigalpa
98 HR Croatia Zagreb
99 HT Haiti Port-au-Prince
100 HU Hungary Budapest
101 ID Indonesia Jakarta
102 IE Ireland Dublin
103 IL Israel Jerusalem
104 IM Isle of Man Douglas
105 IN India New Delhi
106 IO British Indian Ocean Territory Diego Garcia
107 IQ Iraq Baghdad
108 IR Iran Tehran
109 IS Iceland Reykjavik
110 IT Italy Rome
111 JE Jersey Saint Helier
112 JM Jamaica Kingston
113 JO Jordan Amman
114 JP Japan Tokyo
115 KE Kenya Nairobi
116 KG Kyrgyzstan Bishkek
117 KH Cambodia Phnom Penh
118 KI Kiribati Tarawa
119 KM Comoros Moroni
120 KN Saint Kitts and Nevis Basseterre
121 KP North Korea Pyongyang
122 KR South Korea Seoul
123 XK Kosovo Pristina
124 KW Kuwait Kuwait City
125 KY Cayman Islands George Town
126 KZ Kazakhstan Nur-Sultan
127 LA Laos Vientiane
128 LB Lebanon Beirut
129 LC Saint Lucia Castries
130 LI Liechtenstein Vaduz
131 LK Sri Lanka Colombo
132 LR Liberia Monrovia
133 LS Lesotho Maseru
134 LT Lithuania Vilnius
135 LU Luxembourg Luxembourg
136 LV Latvia Riga
137 LY Libya Tripoli
138 MA Morocco Rabat
139 MC Monaco Monaco
140 MD Moldova Chisinau
141 ME Montenegro Podgorica
142 MF Saint Martin Marigot
143 MG Madagascar Antananarivo
144 MH Marshall Islands Majuro
145 MK North Macedonia Skopje
146 ML Mali Bamako
147 MM Myanmar Nay Pyi Taw
148 MN Mongolia Ulaanbaatar
149 MO Macao Macao
150 MP Northern Mariana Islands Saipan
151 MQ Martinique Fort-de-France
152 MR Mauritania Nouakchott
153 MS Montserrat Plymouth
154 MT Malta Valletta
155 MU Mauritius Port Louis
156 MV Maldives Male
157 MW Malawi Lilongwe
158 MX Mexico Mexico City
159 MY Malaysia Kuala Lumpur
160 MZ Mozambique Maputo
161 NA Namibia Windhoek
162 NC New Caledonia Noumea
163 NE Niger Niamey
164 NF Norfolk Island Kingston
165 NG Nigeria Abuja
166 NI Nicaragua Managua
167 NL The Netherlands Amsterdam
168 NO Norway Oslo
169 NP Nepal Kathmandu
170 NR Nauru Yaren
171 NU Niue Alofi
172 NZ New Zealand Wellington
173 OM Oman Muscat
174 PA Panama Panama City
175 PE Peru Lima
176 PF French Polynesia Papeete
177 PG Papua New Guinea Port Moresby
178 PH Philippines Manila
179 PK Pakistan Islamabad
180 PL Poland Warsaw
181 PM Saint Pierre and Miquelon Saint-Pierre
182 PN Pitcairn Adamstown
183 PR Puerto Rico San Juan
184 PS Palestinian Territory East Jerusalem
185 PT Portugal Lisbon
186 PW Palau Melekeok
187 PY Paraguay Asuncion
188 QA Qatar Doha
189 RE Reunion Saint-Denis
190 RO Romania Bucharest
191 RS Serbia Belgrade
192 RU Russia Moscow
193 RW Rwanda Kigali
194 SA Saudi Arabia Riyadh
195 SB Solomon Islands Honiara
196 SC Seychelles Victoria
197 SD Sudan Khartoum
198 SS South Sudan Juba
199 SE Sweden Stockholm
200 SG Singapore Singapore
201 SH Saint Helena Jamestown
202 SI Slovenia Ljubljana
203 SJ Svalbard and Jan Mayen Longyearbyen
204 SK Slovakia Bratislava
205 SL Sierra Leone Freetown
206 SM San Marino San Marino
207 SN Senegal Dakar
208 SO Somalia Mogadishu
209 SR Suriname Paramaribo
210 ST Sao Tome and Principe Sao Tome
211 SV El Salvador San Salvador
212 SX Sint Maarten Philipsburg
213 SY Syria Damascus
214 SZ Eswatini Mbabane
215 TC Turks and Caicos Islands Cockburn Town
216 TD Chad N'Djamena
217 TF French Southern Territories Port-aux-Francais
218 TG Togo Lome
219 TH Thailand Bangkok
220 TJ Tajikistan Dushanbe
221 TK Tokelau
222 TL Timor Leste Dili
223 TM Turkmenistan Ashgabat
224 TN Tunisia Tunis
225 TO Tonga Nuku'alofa
226 TR Turkey Ankara
227 TT Trinidad and Tobago Port of Spain
228 TV Tuvalu Funafuti
229 TW Taiwan Taipei
230 TZ Tanzania Dodoma
231 UA Ukraine Kyiv
232 UG Uganda Kampala
233 UM United States Minor Outlying Islands
234 US United States Washington
235 UY Uruguay Montevideo
236 UZ Uzbekistan Tashkent
237 VA Vatican Vatican City
238 VC Saint Vincent and the Grenadines Kingstown
239 VE Venezuela Caracas
240 VG British Virgin Islands Road Town
241 VI U.S. Virgin Islands Charlotte Amalie
242 VN Vietnam Hanoi
243 VU Vanuatu Port Vila
244 WF Wallis and Futuna Mata Utu
245 WS Samoa Apia
246 YE Yemen Sanaa
247 YT Mayotte Mamoudzou
248 ZA South Africa Pretoria
249 ZM Zambia Lusaka
250 ZW Zimbabwe Harare
251 CS Serbia and Montenegro Belgrade
252 AN Netherlands Antilles Willemstad

View file

@ -1,193 +0,0 @@
"""Offline GeoNames gazetteer — proximate geolocation for graded articles.
When a map-phase block names a place but gives no coordinates, resolve the
name against vendored GeoNames data (``data/``): cities15000 first, then
country -> capital. Fully offline: no paid API, no rate-limited Nominatim,
no network at runtime. Every resolution is labelled confidence "approx"
by the caller — a gazetteer point is a proximate guess, never an exact fix.
Matching is best-effort and conservative: normalised (case/diacritic-folded)
exact-name lookups with country/admin1 context disambiguation ("Paris,
Texas" vs "Paris, France"), highest population wins ties. A miss returns
None — the article simply gets no blip. Never invents a place.
"""
from __future__ import annotations
import unicodedata
from functools import lru_cache
from pathlib import Path
_DATA_DIR = Path(__file__).resolve().parent / "data"
# Common short forms the model writes that GeoNames spells out.
_COUNTRY_ALIASES = {
"usa": "US",
"u.s.a.": "US",
"u.s.": "US",
"us": "US",
"uk": "GB",
"u.k.": "GB",
"united states of america": "US",
"england": "GB",
"south korea": "KR",
"north korea": "KP",
}
def _norm(text: str) -> str:
"""Casefold + strip diacritics + collapse whitespace for matching."""
text = unicodedata.normalize("NFKD", text)
text = "".join(ch for ch in text if not unicodedata.combining(ch))
return " ".join(text.casefold().split())
def _read_tsv(filename: str) -> list[list[str]]:
path = _DATA_DIR / filename
rows: list[list[str]] = []
try:
with open(path, encoding="utf-8") as fh:
for line in fh:
parts = line.rstrip("\n").split("\t")
if parts and parts[0]:
rows.append(parts)
except OSError:
return []
return rows
@lru_cache(maxsize=1)
def _city_index() -> dict[str, list[tuple[float, float, int, str, str]]]:
"""norm name -> [(lat, lon, population, country_code, admin1_code)]."""
index: dict[str, list[tuple[float, float, int, str, str]]] = {}
for parts in _read_tsv("cities15000.tsv"):
if len(parts) < 7:
continue
name, asciiname, lat, lon, pop, cc, admin1 = parts[:7]
try:
lat_f, lon_f, pop_i = float(lat), float(lon), int(pop)
except ValueError:
continue
if not (-90 <= lat_f <= 90 and -180 <= lon_f <= 180):
continue
entry = (lat_f, lon_f, pop_i, cc, admin1)
for key in {name, asciiname}:
key = _norm(key)
if key:
index.setdefault(key, []).append(entry)
return index
@lru_cache(maxsize=1)
def _country_index() -> dict[str, tuple[str, str]]:
"""norm country name/iso -> (iso_code, capital)."""
index: dict[str, tuple[str, str]] = {}
for parts in _read_tsv("countries.tsv"):
if len(parts) < 3:
continue
iso, name, capital = parts[:3]
value = (iso, capital)
index[_norm(name)] = value
index[iso.casefold()] = value
for alias, iso in _COUNTRY_ALIASES.items():
hit = index.get(iso.casefold())
if hit:
index[_norm(alias)] = hit
return index
@lru_cache(maxsize=1)
def _admin1_index() -> dict[str, list[tuple[str, str]]]:
"""norm division name -> [(country_code, admin1_code)]."""
index: dict[str, list[tuple[str, str]]] = {}
for parts in _read_tsv("admin1.tsv"):
if len(parts) < 3 or "." not in parts[0]:
continue
code, name, asciiname = parts[:3]
cc, _, a1 = code.partition(".")
for key in {name, asciiname}:
key = _norm(key)
if key:
index.setdefault(key, []).append((cc, a1))
return index
def _pick(entries: list[tuple[float, float, int, str, str]]) -> tuple[float, float]:
best = max(entries, key=lambda e: e[2])
return (best[0], best[1])
def resolve_place(location_name) -> tuple[float, float] | None:
"""Proximate (lat, lon) for a model-written place name, else None.
Tries the full string, then the comma-leading part, with trailing
parts as country/admin1 context. Falls back to country -> capital.
"""
if not isinstance(location_name, str):
return None
text = location_name.strip()
if not text:
return None
parts = [p.strip() for p in text.split(",") if p.strip()]
if not parts:
return None
countries = _country_index()
admin1s = _admin1_index()
context_country: str | None = None
context_admin1: list[tuple[str, str]] = []
for part in parts[1:]:
key = _norm(part)
hit = countries.get(key)
if hit:
context_country = hit[0]
continue
context_admin1.extend(admin1s.get(key, []))
cities = _city_index()
for candidate in (text, parts[0]):
entries = cities.get(_norm(candidate))
if not entries:
continue
if context_admin1:
scoped = [
e for e in entries
if any(e[3] == cc and e[4] == a1 for cc, a1 in context_admin1)
]
if scoped:
return _pick(scoped)
if context_country:
scoped = [e for e in entries if e[3] == context_country]
if scoped:
return _pick(scoped)
return _pick(entries)
# Country-only location ("Ukraine"): resolve to the capital.
hit = countries.get(_norm(parts[0]))
if hit:
entries = cities.get(_norm(hit[1]))
if entries:
return _pick(entries)
return None
def fill_block_geo(block: dict) -> dict:
"""Fill missing coords on a parsed map block from the gazetteer.
Blocks that already carry model coordinates are untouched. A resolved
place is labelled confidence "approx"; a miss leaves the block as-is
(name preserved, no coords) — never invents a place.
"""
if not isinstance(block, dict):
return block
if block.get("lat") is not None and block.get("lon") is not None:
return block
name = block.get("location_name")
if not name:
return block
coords = resolve_place(name)
if coords is None:
return block
block["lat"], block["lon"] = coords
block["location_confidence"] = "approx"
return block

View file

@ -1,8 +1,7 @@
"""Pure parser for the news-summarizer map grading / reduce JSON / geo contract."""
"""Pure parser for the news-summarizer reduce JSON / geo / importance contract."""
from __future__ import annotations
import difflib
import json
import re
@ -17,94 +16,6 @@ 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)
_LOCATION_RE = re.compile(r"Location:[ \t]*(.+)", re.IGNORECASE)
_CONFIDENCE_RE = re.compile(
r"Confidence:[ \t]*(exact|city|region|country|approx)", re.IGNORECASE
)
# Numeric token, optional degree sign, optional hemisphere letter. The
# trailing lookahead keeps "12.3 South Sudan" from reading the S of a word
# as a south marker (and from truncating the number to dodge it).
_LAT_RE = re.compile(
r"Lat:[ \t]*([+-]?\d+(?:\.\d+)?)[ \t]*°?[ \t]*([NS])?(?![A-Za-z\d.])", re.IGNORECASE
)
_LON_RE = re.compile(
r"Lon:[ \t]*([+-]?\d+(?:\.\d+)?)[ \t]*°?[ \t]*([EW])?(?![A-Za-z\d.])", re.IGNORECASE
)
LOCATION_NAME_MAX = 120
_UNKNOWN_LOCATIONS = frozenset(
{"unknown", "n/a", "none", "null", "unspecified", "not specified"}
)
GEO_CONFIDENCES = frozenset({"exact", "city", "region", "country", "approx"})
def clean_location_name(raw) -> str | None:
"""Normalise a model-written place name; Unknown/empty -> None.
Strips markdown decoration and trailing periods, caps the length.
Never invents a place: a name the model did not write stays None.
"""
if not isinstance(raw, str):
return None
value = raw.strip().rstrip(".").strip().strip("*_`").strip()
if not value:
return None
lowered = value.lower()
if lowered in _UNKNOWN_LOCATIONS or lowered.startswith("unknown"):
return None
return value[:LOCATION_NAME_MAX]
def _coord_from_block(text: str, kind: str) -> float | None:
"""One Lat:/Lon: value from a block; hemisphere S/W negates."""
match = (_LAT_RE if kind == "lat" else _LON_RE).search(text)
if not match:
return None
try:
value = float(match.group(1))
except (TypeError, ValueError):
return None
hemisphere = (match.group(2) or "").upper()
if hemisphere in ("S", "W") and value > 0:
value = -value
return value
def _geo_from_block(text: str) -> dict:
"""Structured geo for one article block (pure).
Model coords are only trusted alongside a real place name — coords
next to ``Location: Unknown`` are dropped (never invent a place).
Missing/invalid coords leave lat/lon None for the offline gazetteer
step; confidence defaults to "city" when the model gave coords but
no Confidence line.
"""
loc_match = _LOCATION_RE.search(text)
location_name = clean_location_name(loc_match.group(1) if loc_match else None)
lat = lon = None
confidence = None
if location_name is not None:
coords = clamp_coords(_coord_from_block(text, "lat"), _coord_from_block(text, "lon"))
if coords is not None:
lat, lon = coords
conf_match = _CONFIDENCE_RE.search(text)
confidence = conf_match.group(1).lower() if conf_match else "city"
return {
"location_name": location_name,
"lat": lat,
"lon": lon,
"location_confidence": confidence,
}
def parse_reduce_json(raw: str) -> dict:
try:
@ -191,401 +102,3 @@ 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 <n>`` 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",
"location_name", "lat", "lon", "location_confidence",
"text", "position"}
Geo is best-effort: ``location_name`` is the model's place name
(Unknown -> None), ``lat``/``lon`` are clamp_coords-validated model
coordinates (None when absent/invalid — the caller may resolve them
via the offline gazetteer), ``location_confidence`` is the block's
label or "city" when coords came without one.
"""
text = raw or ""
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"),
"title": article.get("title"),
"score": score,
"importance": importance,
"category": _category_from_block(block_text),
**_geo_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,
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 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))
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
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:
"""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())
# Headline must clear this to take an article URL. Above the
# "storm hits Texas" vs "storm hits Tennessee" band (~0.67) so a near-miss
# cannot steal another story's URL. A tie stores "" — a wrong URL is worse
# than a blank one.
ARTICLE_URL_MIN_SIMILARITY = 0.85
# Word-sequence containment only counts when the shorter side is specific.
_URL_CONTAIN_MIN_WORDS = 4
def _contains_word_sequence(outer: str, inner: str) -> bool:
outer_words = outer.split()
inner_words = inner.split()
if len(inner_words) < _URL_CONTAIN_MIN_WORDS or len(inner_words) > len(outer_words):
return False
width = len(inner_words)
return any(
outer_words[i : i + width] == inner_words
for i in range(len(outer_words) - width + 1)
)
def article_url_for_row(row: dict, articles: list | None) -> str:
"""URL of the selected article this ticker/map row refers to, else ``""``.
Matches the row headline to an article title. Never reads the model's
``url`` field. A null, missing, or non-string article url stores ``""``.
Two articles that score the same (or no article that clears the bar)
store ``""`` so a headline cannot be wired to the wrong story.
"""
if not isinstance(row, dict):
return ""
headline = normalize_title(row.get("headline"))
if not headline:
return ""
best_score = 0.0
best: list[dict] = []
for article in articles or []:
if not isinstance(article, dict):
continue
title = normalize_title(article.get("title"))
if not title:
continue
if headline == title:
score = 1.0
elif _contains_word_sequence(headline, title) or _contains_word_sequence(title, headline):
score = 0.95
else:
score = title_similarity(headline, title)
if score + 1e-9 < ARTICLE_URL_MIN_SIMILARITY:
continue
if score > best_score + 1e-9:
best_score = score
best = [article]
elif abs(score - best_score) <= 1e-9:
best.append(article)
if len(best) != 1:
return ""
url = best[0].get("url")
if not isinstance(url, str):
return ""
return url.strip()
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

View file

@ -14,12 +14,6 @@ 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)
@ -37,20 +31,7 @@ from zoneinfo import ZoneInfo
import psycopg2
from gazetteer import fill_block_geo
from intel import (
GEO_CONFIDENCES,
article_url_for_row,
clamp_coords,
clean_location_name,
dedupe_blocks,
join_blocks,
parse_map_scores,
parse_reduce_json,
select_graded,
select_map,
select_ticker,
)
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")
@ -69,58 +50,6 @@ 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
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()
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 _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)))
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))
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:
hours = (os.getenv("SUMMARY_WINDOW_HOURS") or "").strip()
@ -165,41 +94,30 @@ 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. Extract every article; the Score below decides what reaches the operator brief.
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.
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. 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. Confidence: how precise that location is — exact (a specific site/address), city, region, or country. Never invent a place.
4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
5. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
6. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
7. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none. Keep it consistent with the Score.
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.
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, Score and Importance first:
Output format — strictly one block per article:
Article 1:
- Score: <0-100>
- Importance: critical|high|medium|low|none
- Fact bullet 1
- Fact bullet 2
- Location: ...
- Confidence: exact|city|region|country
- Entities: ...
- Category: ...
- OSINT signal: ...
- Importance: ...
- Lat: ...
- Lon: ...
@ -215,11 +133,9 @@ 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.
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.
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.
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.
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.
@ -244,11 +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.
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.
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.
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.
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:
@ -412,27 +326,6 @@ 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,
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;
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_name TEXT;
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lat DOUBLE PRECISION;
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lon DOUBLE PRECISION;
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_confidence TEXT;
CREATE INDEX IF NOT EXISTS ix_article_scores_summary
ON article_scores (summary_id);
CREATE INDEX IF NOT EXISTS ix_article_scores_geo_bbox
ON article_scores (lon, lat)
WHERE lat IS NOT NULL AND lon IS NOT NULL;
"""
try:
conn = psycopg2.connect(**DB_CONFIG)
@ -446,18 +339,12 @@ def ensure_tables() -> None:
def get_recent_news(window_minutes: int | None = None) -> list[dict]:
"""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.
"""
"""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 id, title, content, url, domain
SELECT 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;
"""
@ -469,7 +356,7 @@ def get_recent_news(window_minutes: int | None = None) -> list[dict]:
cur.close()
conn.close()
return [
{"id": r[0], "title": r[1], "content": r[2], "url": r[3], "domain": r[4]}
{"title": r[0], "content": r[1], "url": r[2], "domain": r[3]}
for r in rows
]
except Exception as exc: # noqa: BLE001
@ -524,25 +411,15 @@ def _already_recapped_today() -> bool:
def save_batch(
summary_en: str,
model: str,
ticker: list,
map_items: list,
*,
kind: str = "interval",
articles: list | None = None,
) -> int | None:
"""Insert the master brief plus flagged ticker/map rows. Returns the new summary id.
``news_items.url`` is the matched selected article's url, never the model's
``url`` field. A null article url is stored as ``""``.
"""
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 [])
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 None
return
insert_item = """
INSERT INTO news_items (
summary_id, kind, headline, importance, location_name,
@ -570,7 +447,7 @@ def save_batch(
None,
None,
None,
article_url_for_row(row, articles),
row.get("url"),
),
)
for row in map_rows:
@ -586,7 +463,7 @@ def save_batch(
row.get("lon"),
row.get("location_confidence"),
row.get("category"),
article_url_for_row(row, articles),
row.get("url"),
),
)
conn.commit()
@ -596,77 +473,8 @@ 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).
Syndication duplicates are written too, with ``selected=false`` and
``duplicate_of`` pointing at the surviving article id — the representative
carries the selection even when the copy itself scores above the bar.
Per-article geo (location_name/lat/lon/location_confidence) rides along
for the /api/news/blips layer; coords are re-validated and confidence
is restricted to the contract vocabulary at write time.
Best-effort: a failure here is logged and never aborts the run.
"""
rows = []
for block in graded or []:
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
coords = clamp_coords(block.get("lat"), block.get("lon"))
lat, lon = coords if coords is not None else (None, None)
location_name = clean_location_name(block.get("location_name"))
confidence = block.get("location_confidence")
if lat is None or confidence not in GEO_CONFIDENCES:
confidence = None
rows.append(
(
article_id,
summary_id,
int(block.get("score") or 0),
block.get("category"),
bool(block.get("selected")) and duplicate_of is None,
model,
duplicate_of,
location_name,
lat,
lon,
confidence,
)
)
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, duplicate_of, "
" location_name, lat, lon, location_confidence) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
rows,
)
conn.commit()
cur.close()
conn.close()
logger.info(
"article_scores persisted rows=%d selected=%d duplicates=%d geo=%d summary_id=%s",
len(rows), sum(1 for r in rows if r[4]),
sum(1 for r in rows if r[6] is not None),
sum(1 for r in rows if r[8] is not None), summary_id,
)
except Exception as exc: # noqa: BLE001
logger.error("Error persisting article_scores (run continues): %s", exc)
# ── Orchestration ──────────────────────────────────────────────────────────
@ -725,99 +533,34 @@ def summarize_news() -> None:
logger.info("No new articles found in the last %s min.", window)
return
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, fallback_min_score=%d)...",
"Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s)...",
len(articles), model, BATCH_SIZE, recap, window,
min_score, top_n, fallback_top, fallback_min_score,
)
graded: list[dict] = []
partial_summaries: list[str] = []
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)",
batch_index + 1, -(-len(articles) // BATCH_SIZE), len(batch),
i // BATCH_SIZE + 1, -(-len(articles) // BATCH_SIZE), len(batch),
)
response = call_llm(
summary = call_llm(
build_map_prompt(batch),
api_key=api_key,
model=model,
base_url=base_url,
json_mode=False,
)
if not response:
continue
blocks, stats = parse_map_scores(
response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE
)
# Best-effort proximate geo: place-name-only blocks get offline
# gazetteer coords (confidence "approx"); misses stay coord-less.
for block in blocks:
fill_block_geo(block)
logger.info(
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d, geo=%d)",
batch_index + 1, stats["graded"], len(batch),
stats["fallback"], stats["unattributed"],
sum(1 for b in blocks if b.get("lat") is not None),
)
graded.extend(blocks)
if summary:
partial_summaries.append(summary)
if not graded:
logger.warning("No article blocks parsed from the map phase — nothing to reduce.")
final_input = "\n\n".join(partial_summaries)
if not final_input.strip():
logger.warning("No partial summaries produced — 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(
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 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 "
"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 distinct articles for reduce (scores=%s)",
len(selected), len(distinct), [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, "
"fallback_min_score=%d) — reduce gets empty DATA.",
min_score, fallback_top, fallback_min_score,
)
logger.info("reduce phase over %d partial summaries", len(partial_summaries))
master_raw = call_llm(
build_master_prompt(final_input, recap=recap),
api_key=api_key,
@ -829,20 +572,13 @@ def summarize_news() -> None:
logger.warning("Reduce phase returned empty — nothing to persist.")
return
parsed = parse_reduce_json(master_raw)
selected_articles = [
block["article"]
for block in selected
if isinstance(block.get("article"), dict)
]
summary_id = save_batch(
save_batch(
parsed["summary_en"],
model,
parsed["ticker"],
parsed["map_items"],
kind="daily_recap" if recap else "interval",
articles=selected_articles,
)
persist_article_scores(distinct + duplicate_blocks, summary_id=summary_id, model=model)
if __name__ == "__main__":

View file

@ -1,214 +0,0 @@
"""Ticker and map rows persist the selected article URL, never the model's."""
from __future__ import annotations
import json
import pytest
import summarizer
from intel import article_url_for_row
ARTICLES = [
{
"id": 1,
"title": "Strike in Kyiv",
"content": "x" * 120,
"url": "https://ex.com/1",
"domain": "ex.com",
},
{
"id": 2,
"title": "Floods in Paris",
"content": "y" * 120,
"url": "https://ex.com/2",
"domain": "ex.com",
},
{
"id": 3,
"title": "Quiet day in Oslo",
"content": "z" * 120,
"url": None,
"domain": "ex.com",
},
]
def _block(n: int, score: int) -> str:
return "\n".join(
[
f"Article {n}:",
f"- Score: {score}",
"- Importance: high",
"- Fact bullet",
"- Location: Kyiv",
"- Category: politics",
"- Lat: 50.45",
"- Lon: 30.52",
]
)
REDUCE = {
"summary_en": "Lead: strike in Kyiv. Also floods in Paris and a quiet day in Oslo.",
# Headlines are swapped vs article order so a positional stamp would cross-wire.
# Model url is blank or a decoy — neither may be stored.
"ticker": [
{"headline": "Floods in Paris", "importance": "high", "url": ""},
{
"headline": "Strike in Kyiv",
"importance": "critical",
"url": "https://wrong.example/model",
},
{
"headline": "Quiet day in Oslo",
"importance": "high",
"url": "https://invented.example",
},
],
"map_items": [
{
"headline": "Floods in Paris",
"importance": "high",
"location_name": "Paris",
"lat": 48.85,
"lon": 2.35,
"location_confidence": "city",
"category": "environment/disaster",
"url": "",
},
{
"headline": "Strike in Kyiv",
"importance": "critical",
"location_name": "Kyiv",
"lat": 50.45,
"lon": 30.52,
"location_confidence": "city",
"category": "military/conflict",
"url": "",
},
{
"headline": "Quiet day in Oslo",
"importance": "high",
"location_name": "Oslo",
"lat": 59.91,
"lon": 10.75,
"location_confidence": "city",
"category": "society",
"url": "https://invented.example",
},
],
}
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 _news_item_urls(db_log: list, kind: str) -> list:
urls = []
for entry in db_log:
if entry[0] != "execute" or "INSERT INTO news_items" not in entry[1]:
continue
params = entry[2]
if not params or params[1] != kind:
continue
urls.append(params[-1])
return urls
def test_matcher_uses_article_url_not_model_url():
row = {"headline": "Strike in Kyiv", "importance": "critical", "url": ""}
assert article_url_for_row(row, ARTICLES) == "https://ex.com/1"
def test_matcher_does_not_cross_wire_and_null_url_stays_blank():
paris = {"headline": "Floods in Paris", "url": "https://ex.com/1"}
oslo = {"headline": "Quiet day in Oslo", "url": "https://invented.example"}
assert article_url_for_row(paris, ARTICLES) == "https://ex.com/2"
assert article_url_for_row(oslo, ARTICLES) == ""
def test_matcher_refuses_a_tie_instead_of_guessing():
twins = [
{"title": "Same story", "url": "https://ex.com/1"},
{"title": "Same story", "url": "https://ex.com/2"},
]
assert article_url_for_row({"headline": "Same story", "url": ""}, twins) == ""
def test_unmatched_headline_does_not_invent_a_url():
row = {"headline": "Unrelated market tape", "url": "https://model.example/kept"}
assert article_url_for_row(row, ARTICLES) == ""
@pytest.fixture
def harness(monkeypatch):
calls: list[tuple[str, str]] = []
db_log: list = []
map_reply = "\n\n".join([_block(1, 92), _block(2, 88), _block(3, 80)])
reduce_reply = json.dumps(REDUCE)
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_reply
monkeypatch.setenv("NOUS_API_KEY", "test-key")
monkeypatch.setenv("SUMMARY_MODEL", "test-model")
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 test_persist_stamps_article_url_on_ticker_and_map(harness):
_, db_log = harness
summarizer.summarize_news()
assert _news_item_urls(db_log, "ticker") == [
"https://ex.com/2",
"https://ex.com/1",
"",
]
assert _news_item_urls(db_log, "map") == [
"https://ex.com/2",
"https://ex.com/1",
"",
]

View file

@ -1,432 +0,0 @@
"""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,
"<![CDATA[Muere a los 43 años Christian Cousins; su hermano revela sus últimos problemas de salud]]>"),
(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

View file

@ -1,405 +0,0 @@
"""Per-article geo: map-block Location/Lat/Lon parsing + offline gazetteer.
Covers the blips pipeline (card t_bc15eb53): parse_map_scores extracts
structured geo per graded block, clamp_coords rejects invalid values, and
the vendored GeoNames gazetteer resolves place-name-only blocks to
proximate coordinates with confidence "approx".
"""
from __future__ import annotations
import math
import pytest
from intel import clamp_coords, parse_map_scores
def _articles(n: int = 1, start: int = 100) -> list[dict]:
return [
{
"id": start + i,
"title": f"title {i}",
"content": "body",
"url": f"https://ex.com/{i}",
"domain": "ex.com",
}
for i in range(n)
]
def _block(n: int, *lines: str, score: int = 55) -> str:
return "\n".join([f"Article {n}:", f"- Score: {score}", *lines])
# ── parse_map_scores: structured geo ──────────────────────────────────────
def test_parses_location_lat_lon_and_confidence():
raw = _block(
1,
"- Location: Kyiv, Ukraine",
"- Lat: 50.45",
"- Lon: 30.52",
"- Confidence: city",
"- Category: politics",
)
blocks, stats = parse_map_scores(raw, articles=_articles())
assert stats["graded"] == 1
b = blocks[0]
assert b["location_name"] == "Kyiv, Ukraine"
assert b["lat"] == pytest.approx(50.45)
assert b["lon"] == pytest.approx(30.52)
assert b["location_confidence"] == "city"
def test_coords_without_confidence_default_to_city():
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_confidence"] == "city"
assert b["lat"] == pytest.approx(50.45)
@pytest.mark.parametrize("confidence", ["exact", "city", "region", "country"])
def test_block_confidence_labels_pass_through(confidence):
raw = _block(
1, "- Location: somewhere", "- Lat: 10", "- Lon: 20",
f"- Confidence: {confidence}",
)
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_confidence"] == confidence
def test_place_name_only_keeps_name_without_coords():
raw = _block(1, "- Location: Odesa, Ukraine")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_name"] == "Odesa, Ukraine"
assert b["lat"] is None
assert b["lon"] is None
assert b["location_confidence"] is None
@pytest.mark.parametrize("location", ["Unknown", "unknown", "N/A", "None", ""])
def test_unknown_location_yields_no_geo(location):
raw = _block(1, f"- Location: {location}", "- Lat: 50.45", "- Lon: 30.52")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_name"] is None
# No usable place name: model coords alone are not trusted either.
assert b["lat"] is None
assert b["lon"] is None
assert b["location_confidence"] is None
def test_no_location_line_yields_no_geo():
b = parse_map_scores(_block(1, "- Category: politics"), articles=_articles())[0][0]
assert b["location_name"] is None
assert b["lat"] is None
assert b["lon"] is None
assert b["location_confidence"] is None
def test_out_of_range_coords_are_dropped_but_name_kept():
raw = _block(1, "- Location: Nowhere", "- Lat: 95.0", "- Lon: 30.52")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_name"] == "Nowhere"
assert b["lat"] is None
assert b["lon"] is None
assert b["location_confidence"] is None
def test_lon_out_of_range_drops_both():
raw = _block(1, "- Location: Nowhere", "- Lat: 10", "- Lon: 181")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] is None and b["lon"] is None
def test_missing_lon_drops_lat_too():
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] is None and b["lon"] is None
def test_non_numeric_coords_drop_both():
raw = _block(1, "- Location: Kyiv", "- Lat: about 50", "- Lon: 30.52")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] is None and b["lon"] is None
def test_hemisphere_suffixes_negate_south_and_west():
raw = _block(
1, "- Location: Sydney", "- Lat: 33.87 S", "- Lon: 151.21 E"
)
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] == pytest.approx(-33.87)
assert b["lon"] == pytest.approx(151.21)
raw = _block(1, "- Location: Rio", "- Lat: 22.9 S", "- Lon: 43.2 W")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] == pytest.approx(-22.9)
assert b["lon"] == pytest.approx(-43.2)
def test_hemisphere_letter_of_a_word_is_not_a_suffix():
# "12.3 South Sudan" must NOT negate — the S belongs to a word.
raw = _block(1, "- Location: Juba", "- Lat: 12.3 South Sudan", "- Lon: 31.6")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["lat"] == pytest.approx(12.3)
def test_location_name_is_cleaned_and_capped():
raw = _block(1, "- Location: **Kyiv**.")
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["location_name"] == "Kyiv"
raw = _block(1, "- Location: " + "x" * 300)
b = parse_map_scores(raw, articles=_articles())[0][0]
assert len(b["location_name"]) <= 120
def test_each_block_gets_its_own_geo():
raw = "\n\n".join(
[
_block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52"),
_block(2, "- Location: Tehran", "- Lat: 35.69", "- Lon: 51.39"),
_block(3, "- Location: Unknown"),
]
)
blocks, stats = parse_map_scores(raw, articles=_articles(3))
assert stats["graded"] == 3
assert blocks[0]["lat"] == pytest.approx(50.45)
assert blocks[1]["location_name"] == "Tehran"
assert blocks[1]["lon"] == pytest.approx(51.39)
assert blocks[2]["location_name"] is None
assert blocks[2]["lat"] is None
def test_geo_fields_never_break_score_parsing():
raw = _block(
1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52",
"- Importance: high", score=83,
)
b = parse_map_scores(raw, articles=_articles())[0][0]
assert b["score"] == 83
assert b["importance"] == "high"
# ── clamp_coords hardening ────────────────────────────────────────────────
@pytest.mark.parametrize(
"lat,lon",
[
(90.1, 0), (-90.1, 0), (0, 180.1), (0, -180.1),
(float("nan"), 0), (0, float("nan")),
(float("inf"), 0), (0, float("-inf")),
("abc", 0), (None, None),
],
)
def test_clamp_coords_rejects_invalid(lat, lon):
assert clamp_coords(lat, lon) is None
def test_clamp_coords_accepts_boundaries():
assert clamp_coords(90, 180) == (90.0, 180.0)
assert clamp_coords(-90, -180) == (-90.0, -180.0)
# ── Offline gazetteer ─────────────────────────────────────────────────────
def test_gazetteer_resolves_known_city():
from gazetteer import resolve_place
coords = resolve_place("Kyiv")
assert coords is not None
lat, lon = coords
assert lat == pytest.approx(50.45, abs=0.1)
assert lon == pytest.approx(30.52, abs=0.1)
def test_gazetteer_resolves_city_with_country_context():
from gazetteer import resolve_place
coords = resolve_place("Kyiv, Ukraine")
assert coords is not None
assert coords[0] == pytest.approx(50.45, abs=0.1)
def test_gazetteer_disambiguates_by_country():
from gazetteer import resolve_place
france = resolve_place("Paris, France")
texas = resolve_place("Paris, Texas")
assert france is not None and texas is not None
assert france[0] == pytest.approx(48.85, abs=0.2)
assert texas[0] == pytest.approx(33.66, abs=0.3)
assert france != texas
def test_gazetteer_resolves_country_to_capital():
from gazetteer import resolve_place
coords = resolve_place("Ukraine")
assert coords is not None
# Capital Kyiv.
assert coords[0] == pytest.approx(50.45, abs=0.1)
assert coords[1] == pytest.approx(30.52, abs=0.1)
def test_gazetteer_handles_diacritics_and_case():
from gazetteer import resolve_place
assert resolve_place("KYIV") is not None
assert resolve_place("Tehrān") is not None or resolve_place("Tehran") is not None
@pytest.mark.parametrize("name", ["Unknown", "", None, " ", "Zzzqx Not A Real Place 999"])
def test_gazetteer_misses_return_none(name):
from gazetteer import resolve_place
assert resolve_place(name) is None
def test_fill_block_geo_resolves_place_name_only_block():
from gazetteer import fill_block_geo
raw = _block(1, "- Location: Kyiv, Ukraine")
b = parse_map_scores(raw, articles=_articles())[0][0]
fill_block_geo(b)
assert b["lat"] == pytest.approx(50.45, abs=0.1)
assert b["lon"] == pytest.approx(30.52, abs=0.1)
assert b["location_confidence"] == "approx"
assert b["location_name"] == "Kyiv, Ukraine"
def test_fill_block_geo_keeps_model_coords():
from gazetteer import fill_block_geo
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52")
b = parse_map_scores(raw, articles=_articles())[0][0]
fill_block_geo(b)
assert b["lat"] == pytest.approx(50.45)
assert b["location_confidence"] == "city"
def test_fill_block_geo_omits_when_no_location():
from gazetteer import fill_block_geo
raw = _block(1, "- Location: Unknown")
b = parse_map_scores(raw, articles=_articles())[0][0]
fill_block_geo(b)
assert b["lat"] is None and b["lon"] is None
assert b["location_confidence"] is None
def test_fill_block_geo_omits_when_gazetteer_misses():
from gazetteer import fill_block_geo
raw = _block(1, "- Location: Zzzqx Not A Real Place 999")
b = parse_map_scores(raw, articles=_articles())[0][0]
fill_block_geo(b)
assert b["lat"] is None and b["lon"] is None
assert b["location_confidence"] is None
# The name the model actually wrote is still preserved.
assert b["location_name"] == "Zzzqx Not A Real Place 999"
# ── Persistence carries geo ───────────────────────────────────────────────
def test_persist_article_scores_writes_geo_columns(monkeypatch):
import summarizer
captured: list = []
class _Cur:
def execute(self, sql, params=None):
pass
def executemany(self, sql, rows):
captured.append((" ".join(sql.split()), list(rows)))
def close(self):
pass
class _Conn:
def cursor(self):
return _Cur()
def commit(self):
pass
def close(self):
pass
monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kw: _Conn())
graded = [
{
"article_id": 1, "score": 80, "category": "politics",
"selected": True, "location_name": "Kyiv, Ukraine",
"lat": 50.45, "lon": 30.52, "location_confidence": "city",
},
{
"article_id": 2, "score": 30, "category": "crime",
"selected": False, "location_name": "Unknown",
"lat": None, "lon": None, "location_confidence": None,
},
]
summarizer.persist_article_scores(graded, summary_id=7, model="m")
assert captured, "no executemany captured"
sql, rows = captured[-1]
for col in ("location_name", "lat", "lon", "location_confidence"):
assert col in sql
by_id = {row[0]: row for row in rows}
assert by_id[1][7] == "Kyiv, Ukraine"
assert by_id[1][8] == pytest.approx(50.45)
assert by_id[1][9] == pytest.approx(30.52)
assert by_id[1][10] == "city"
assert by_id[2][7] is None
assert by_id[2][8] is None
assert by_id[2][9] is None
assert by_id[2][10] is None
def test_persist_article_scores_sanitizes_bad_geo(monkeypatch):
import summarizer
captured: list = []
class _Cur:
def execute(self, sql, params=None):
pass
def executemany(self, sql, rows):
captured.append(list(rows))
def close(self):
pass
class _Conn:
def cursor(self):
return _Cur()
def commit(self):
pass
def close(self):
pass
monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kw: _Conn())
graded = [
{
"article_id": 1, "score": 80, "selected": True,
"location_name": "Kyiv", "lat": float("nan"), "lon": 30.52,
"location_confidence": "bogus",
},
]
summarizer.persist_article_scores(graded, summary_id=7, model="m")
row = captured[-1][0]
assert row[8] is None and row[9] is None # NaN lat drops the pair
assert row[10] is None # confidence outside the contract vocabulary
def test_map_prompt_asks_for_confidence():
from summarizer import MAP_PROMPT_DEFAULT
assert "Confidence:" in MAP_PROMPT_DEFAULT
assert "exact|city|region|country" in MAP_PROMPT_DEFAULT

View file

@ -1,231 +0,0 @@
"""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_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)
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

View file

@ -1,231 +0,0 @@
"""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_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
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)

View file

@ -22,42 +22,12 @@ def test_summary_prompt_focuses_on_breaking_news_not_futures():
assert "commodity" in p or "market" in p
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():
def test_summary_prompt_covers_critical_then_incidents():
p = SUMMARY_PROMPT_DEFAULT.lower()
assert "critical" 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
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():

View file

@ -1,19 +1,10 @@
"""Summarizer window, recap flag, no futures injection, and grading env knobs."""
"""Summarizer window, recap flag, and no futures injection into prompts."""
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,
)
@ -52,164 +43,3 @@ 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

View file

@ -30,38 +30,11 @@ 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

View file

@ -1,62 +0,0 @@
"""Tests for the idle ADS-B watch sweep.
Regression: the refresh loop only persisted aircraft for *connected browser
viewports*, so ``aircraft_positions`` went silent for a day whenever nobody had
the map open (observed 2026-11-20 04:58 -> 2026-11-21). When no viewport is
registered the loop must sweep the chokepoint presets instead.
"""
from __future__ import annotations
import asyncio
from chokepoints import chokepoints
from live_layers import bbox_center_radius_nm, parse_bbox
from main import _adsb_watch_boxes, _adsb_refresh_loop
from ws_manager import manager
def test_watch_boxes_cover_every_chokepoint() -> None:
boxes = _adsb_watch_boxes()
assert len(boxes) == len(chokepoints())
for box in boxes:
minlon, minlat, maxlon, maxlat = box
# Preset catalog order is minlat,minlon,maxlat,maxlon: a lon/lat swap
# would put e.g. Hormuz at lat 56 lon 26.
assert -90 <= minlat < maxlat <= 90
assert -180 <= minlon < maxlon <= 180
# ADSB.lol 403s any dist > 250 nm; live_layer clamps to 150 nm.
assert bbox_center_radius_nm(minlon, minlat, maxlon, maxlat)[2] <= 150
def test_watch_box_order_matches_catalog() -> None:
hormuz = next(p for p in chokepoints() if p["id"] == "hormuz")
minlat, minlon, maxlat, maxlon = (float(v) for v in hormuz["bbox"].split(","))
assert (minlon, minlat, maxlon, maxlat) in _adsb_watch_boxes()
# parse_bbox (the app's viewport order) agrees with the converted box.
assert parse_bbox(f"{minlon},{minlat},{maxlon},{maxlat}") == (minlon, minlat, maxlon, maxlat)
def test_idle_loop_polls_watch_boxes(monkeypatch) -> None:
"""With no client viewport the loop must call fetch_aircraft(persist=True)."""
calls: list[tuple[str, bool]] = []
async def fake_fetch(bbox: str, limit: int = 2000, persist: bool = False):
calls.append((bbox, persist))
return []
monkeypatch.setattr("live_layers.fetch_aircraft", fake_fetch)
assert manager.viewports() == []
async def run() -> None:
try:
await asyncio.wait_for(_adsb_refresh_loop(), 0.5)
except asyncio.TimeoutError:
pass
asyncio.run(run())
assert calls, "idle loop persisted nothing"
assert all(persist for _, persist in calls)
assert {bbox for bbox, _ in calls} == {
f"{b[0]},{b[1]},{b[2]},{b[3]}" for b in _adsb_watch_boxes()
}

View file

@ -7,22 +7,18 @@ 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)

View file

@ -10,7 +10,7 @@ from __future__ import annotations
import asyncio
import os
from datetime import datetime, timedelta, timezone
from datetime import datetime, timezone
import asyncpg
import httpx
@ -157,70 +157,6 @@ 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_unwraps_stored_cdata_title(clean_news):
"""Dirty rows are fixed on read. A plain title, and HTML that is not a
CDATA wrapper, are returned unchanged. No UPDATE of historical rows.
"""
stored = "\n <![CDATA[Hello]]> "
_seed_article(
stored,
"https://www.excelsior.com.mx/cdata",
"www.excelsior.com.mx",
"2026-08-24T18:00:00+00:00",
)
_seed_article(
"Hello",
"https://a.example/plain",
"a.example",
"2026-08-24T17:00:00+00:00",
)
_seed_article(
"<b>Keep</b>",
"https://a.example/html",
"a.example",
"2026-08-24T16:00:00+00:00",
)
body = _get("/api/news").json()
by_url = {row["url"]: row["title"] for row in body}
assert by_url["https://www.excelsior.com.mx/cdata"] == "Hello"
assert by_url["https://a.example/plain"] == "Hello"
assert by_url["https://a.example/html"] == "<b>Keep</b>"
# Read-path only: the stored row stays dirty.
async def _stored_title() -> str:
conn = await asyncpg.connect(**_conn_kwargs())
try:
return await conn.fetchval(
"SELECT title FROM articles WHERE url = $1",
"https://www.excelsior.com.mx/cdata",
)
finally:
await conn.close()
assert asyncio.run(_stored_title()) == stored
@requires_db
def test_api_news_summaries_contract(clean_news):
_seed_summary("master summary markdown…", "2026-08-24T18:05:00+00:00")

View file

@ -1,337 +0,0 @@
"""Integration tests for GET /api/news/blips (per-article proximate geo).
DB-backed: marked `requires_db` and auto-skip when the test database is
unreachable (see tests/conftest.py). Seeding writes directly to `articles`
and `article_scores`, exactly as the summarizer's persist step would.
Frozen wire contract (card t_bc15eb53):
200 -> JSON array, EXACT keys: id, headline, url, domain, location_name,
lat, lon, location_confidence, category, score, created_at.
Only finite lat/lon; created_at DESC; dedup by article id (latest wins).
"""
from __future__ import annotations
import asyncio
import math
import os
from datetime import datetime, timedelta, timezone
from urllib.parse import quote
import asyncpg
import httpx
import pytest
from conftest import requires_db
from main import app
BASE = "http://test"
CONTRACT_KEYS = {
"id", "headline", "url", "domain", "location_name",
"lat", "lon", "location_confidence", "category", "score", "created_at",
}
def _conn_kwargs() -> dict:
return {
"host": os.environ["DB_HOST"],
"port": int(os.environ["DB_PORT"]),
"user": os.environ["DB_USER"],
"password": os.environ["DB_PASSWORD"],
"database": os.environ["DB_NAME"],
}
def _run(coro):
return asyncio.run(coro)
def _truncate() -> None:
async def run():
conn = await asyncpg.connect(**_conn_kwargs())
try:
await conn.execute("TRUNCATE articles, article_scores CASCADE")
finally:
await conn.close()
_run(run())
@pytest.fixture()
def clean_blips():
_truncate()
yield
_truncate()
def _seed_article(title: str, url: str | None, domain: str | None) -> int:
async def run() -> int:
conn = await asyncpg.connect(**_conn_kwargs())
try:
row = await conn.fetchrow(
"INSERT INTO articles (title, url, content, domain, timestamp) "
"VALUES ($1, $2, $3, $4, $5) RETURNING id",
title, url, "body text " * 20, domain,
datetime.now(timezone.utc),
)
return int(row["id"])
finally:
await conn.close()
return _run(run())
def _seed_score(
article_id: int,
*,
score: int = 50,
category: str | None = "politics",
location_name: str | None = "Kyiv, Ukraine",
lat: float | None = 50.45,
lon: float | None = 30.52,
location_confidence: str | None = "city",
created_at: datetime | None = None,
) -> None:
async def run():
conn = await asyncpg.connect(**_conn_kwargs())
try:
await conn.execute(
"INSERT INTO article_scores "
"(article_id, summary_id, score, category, selected, model, "
" duplicate_of, location_name, lat, lon, location_confidence, created_at) "
"VALUES ($1, NULL, $2, $3, false, 'test-model', NULL, $4, $5, $6, $7, $8)",
article_id, score, category, location_name, lat, lon,
location_confidence,
created_at or datetime.now(timezone.utc),
)
finally:
await conn.close()
_run(run())
async def _get(path: str) -> httpx.Response:
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
return await client.get(path)
def _get_sync(path: str) -> httpx.Response:
return _run(_get(path))
@requires_db
def test_blips_exact_contract_keys(clean_blips):
aid = _seed_article("Strike in Kyiv", "https://ex.com/1", "ex.com")
_seed_score(aid, score=82)
resp = _get_sync("/api/news/blips")
assert resp.status_code == 200
rows = resp.json()
assert len(rows) == 1
row = rows[0]
assert set(row.keys()) == CONTRACT_KEYS
assert row["id"] == aid
assert row["headline"] == "Strike in Kyiv"
assert row["url"] == "https://ex.com/1"
assert row["domain"] == "ex.com"
assert row["location_name"] == "Kyiv, Ukraine"
assert row["lat"] == pytest.approx(50.45)
assert row["lon"] == pytest.approx(30.52)
assert row["location_confidence"] == "city"
assert row["category"] == "politics"
assert row["score"] == 82
assert isinstance(row["created_at"], str)
datetime.fromisoformat(row["created_at"]) # ISO8601 parseable
@requires_db
def test_blips_nullable_fields(clean_blips):
aid = _seed_article("Untitled", None, None)
_seed_score(
aid, category=None, location_name=None, location_confidence=None,
lat=10.0, lon=20.0,
)
row = _get_sync("/api/news/blips").json()[0]
assert row["url"] is None
assert row["domain"] is None
assert row["location_name"] is None
assert row["location_confidence"] is None
assert row["category"] is None
assert row["headline"] == "Untitled"
@requires_db
def test_blips_dedup_by_article_id_latest_geo_wins(clean_blips):
aid = _seed_article("Regraded story", "https://ex.com/r", "ex.com")
now = datetime.now(timezone.utc)
_seed_score(
aid, lat=1.0, lon=2.0, location_name="Old place",
location_confidence="approx", created_at=now - timedelta(hours=3),
)
_seed_score(
aid, lat=50.45, lon=30.52, location_name="Kyiv",
location_confidence="city", created_at=now - timedelta(hours=1),
)
rows = _get_sync("/api/news/blips").json()
assert len(rows) == 1
assert rows[0]["id"] == aid
assert rows[0]["location_name"] == "Kyiv"
assert rows[0]["lat"] == pytest.approx(50.45)
assert rows[0]["location_confidence"] == "city"
@requires_db
def test_blips_dedup_latest_geo_wins_even_if_newer_row_has_none(clean_blips):
"""Latest grading without geo: the newest FINITE-geo row still blips.
The contract filters to finite lat/lon rows first, then dedups by id
(latest geo wins) — a coord-less re-grade does not erase an article's
last known location.
"""
aid = _seed_article("Keeps its place", "https://ex.com/x", "ex.com")
now = datetime.now(timezone.utc)
_seed_score(aid, lat=50.45, lon=30.52, created_at=now - timedelta(hours=3))
_seed_score(
aid, lat=None, lon=None, location_name=None,
location_confidence=None, created_at=now - timedelta(hours=1),
)
rows = _get_sync("/api/news/blips").json()
assert len(rows) == 1
assert rows[0]["id"] == aid
assert rows[0]["lat"] == pytest.approx(50.45)
@requires_db
def test_blips_only_finite_coords(clean_blips):
now = datetime.now(timezone.utc)
good = _seed_article("Good", "https://ex.com/g", "ex.com")
_seed_score(good, created_at=now)
bad_cases = [
{"lat": None, "lon": None},
{"lat": float("nan"), "lon": 30.52},
{"lat": 50.45, "lon": float("nan")},
{"lat": float("inf"), "lon": 30.52},
{"lat": 50.45, "lon": float("-inf")},
{"lat": 91.0, "lon": 30.52},
{"lat": 50.45, "lon": 181.0},
]
for i, geo in enumerate(bad_cases):
aid = _seed_article(f"Bad {i}", f"https://ex.com/b{i}", "ex.com")
_seed_score(aid, created_at=now - timedelta(minutes=i + 1), **geo)
rows = _get_sync("/api/news/blips").json()
assert [r["id"] for r in rows] == [good]
assert all(math.isfinite(r["lat"]) and math.isfinite(r["lon"]) for r in rows)
@requires_db
def test_blips_includes_non_critical_articles(clean_blips):
"""No importance/score filter: low-scored graded articles are blips too."""
now = datetime.now(timezone.utc)
ids = []
for i, score in enumerate((95, 78, 50, 30, 12)):
aid = _seed_article(f"Story {score}", f"https://ex.com/{i}", "ex.com")
_seed_score(aid, score=score, created_at=now - timedelta(minutes=i))
ids.append(aid)
rows = _get_sync("/api/news/blips").json()
assert {r["id"] for r in rows} == set(ids)
assert {r["score"] for r in rows} == {95, 78, 50, 30, 12}
@requires_db
def test_blips_order_created_at_desc(clean_blips):
now = datetime.now(timezone.utc)
ids = []
for i in range(4):
aid = _seed_article(f"Story {i}", f"https://ex.com/{i}", "ex.com")
_seed_score(aid, created_at=now - timedelta(hours=i + 1))
ids.append(aid)
rows = _get_sync("/api/news/blips").json()
assert [r["id"] for r in rows] == ids # newest first
stamps = [datetime.fromisoformat(r["created_at"]) for r in rows]
assert stamps == sorted(stamps, reverse=True)
@requires_db
def test_blips_bbox_filter(clean_blips):
now = datetime.now(timezone.utc)
kyiv = _seed_article("Kyiv story", "https://ex.com/k", "ex.com")
_seed_score(kyiv, lat=50.45, lon=30.52, created_at=now)
sydney = _seed_article("Sydney story", "https://ex.com/s", "ex.com")
_seed_score(sydney, lat=-33.87, lon=151.21, created_at=now)
rows = _get_sync("/api/news/blips?bbox=20,40,40,60").json()
assert [r["id"] for r in rows] == [kyiv]
rows = _get_sync("/api/news/blips?bbox=-180,-90,180,90").json()
assert {r["id"] for r in rows} == {kyiv, sydney}
assert _get_sync("/api/news/blips?bbox=0,0,1,1").json() == []
@requires_db
@pytest.mark.parametrize(
"bbox",
["1,2,3", "1,2,3,4,5", "a,b,c,d", "1,2,,4", "1,2,3,"],
)
def test_blips_bbox_malformed_422(clean_blips, bbox):
resp = _get_sync(f"/api/news/blips?bbox={bbox}")
assert resp.status_code == 422
@requires_db
def test_blips_bbox_empty_is_omitted(clean_blips):
"""Same semantics as /api/news/map: an empty bbox means 'no filter'."""
aid = _seed_article("Any place", "https://ex.com/a", "ex.com")
_seed_score(aid)
assert _get_sync("/api/news/blips?bbox=").status_code == 200
assert len(_get_sync("/api/news/blips?bbox=").json()) == 1
@requires_db
def test_blips_since_honored(clean_blips):
now = datetime.now(timezone.utc)
fresh = _seed_article("Fresh", "https://ex.com/f", "ex.com")
_seed_score(fresh, created_at=now - timedelta(hours=1))
stale = _seed_article("Stale", "https://ex.com/s", "ex.com")
_seed_score(stale, created_at=now - timedelta(hours=30))
# Default window is 24h: the 30h-old row is out.
rows = _get_sync("/api/news/blips").json()
assert [r["id"] for r in rows] == [fresh]
# Explicit since widens the window.
since = quote((now - timedelta(hours=48)).isoformat())
rows = _get_sync(f"/api/news/blips?since={since}").json()
assert {r["id"] for r in rows} == {fresh, stale}
# Explicit since narrows it.
since = quote((now - timedelta(minutes=30)).isoformat())
assert _get_sync(f"/api/news/blips?since={since}").json() == []
@requires_db
def test_blips_limit_honored_and_validated(clean_blips):
now = datetime.now(timezone.utc)
for i in range(5):
aid = _seed_article(f"Story {i}", f"https://ex.com/{i}", "ex.com")
_seed_score(aid, created_at=now - timedelta(minutes=i))
rows = _get_sync("/api/news/blips?limit=2").json()
assert len(rows) == 2
assert _get_sync("/api/news/blips?limit=0").status_code == 422
assert _get_sync("/api/news/blips?limit=5001").status_code == 422
assert _get_sync("/api/news/blips?limit=abc").status_code == 422
# Max boundary is accepted.
assert _get_sync("/api/news/blips?limit=5000").status_code == 200
@requires_db
def test_blips_empty_db_returns_empty_array(clean_blips):
resp = _get_sync("/api/news/blips")
assert resp.status_code == 200
assert resp.json() == []
@requires_db
def test_news_map_unchanged_by_blips(clean_blips):
"""Critical-pin layer keeps its own contract while blips exist."""
aid = _seed_article("Critical story", "https://ex.com/c", "ex.com")
_seed_score(aid, score=95)
resp = _get_sync("/api/news/map")
assert resp.status_code == 200
assert resp.json() == [] # no news_items seeded; blips do not leak in

View file

@ -9,7 +9,7 @@ import asyncpg
import httpx
import pytest
from conftest import admin_cookies, requires_db
from conftest import requires_db
from main import app
@ -51,7 +51,6 @@ 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())

View file

@ -8,7 +8,7 @@ from datetime import timezone
import httpx
from main import app, _stats_counts, _stats_cache
from main import app, _stats_counts
BASE = "http://test"
@ -85,79 +85,3 @@ def test_stats_db_failure_degrades_to_zero(monkeypatch):
assert body["fires"] == 0
assert body["quakes"] == 0
assert isinstance(body["timestamp"], str)
def _clear_stats_cache() -> None:
_stats_cache.clear()
def test_stats_feeds_unconfigured_without_keys(monkeypatch):
"""No stored AIS/FIRMS key → both flags false; existing counters stay.
Env vars do not count. The HUD flag is the api_keys store only.
"""
monkeypatch.setenv("FIRMS_MAP_KEY", "env-firms-should-not-count")
monkeypatch.setenv("AISSTREAM_API_KEY", "env-ais-should-not-count")
monkeypatch.setenv("VESSELAPI_API_KEY", "env-vessel-should-not-count")
async def _unset(name: str):
if name == "FIRMS_MAP_KEY":
return " "
return None
monkeypatch.setattr("keystore.get_api_key", _unset)
_clear_stats_cache()
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 body["feeds"] == {
"vessels": {"configured": False},
"fires": {"configured": False},
}
assert "trains" not in body["feeds"]
assert "env-firms-should-not-count" not in resp.text
assert "env-ais-should-not-count" not in resp.text
def test_stats_feeds_fires_configured_does_not_leak_key(monkeypatch):
secret = "firms-map-key-do-not-leak-9f3a2c1b"
async def _keys(name: str):
if name == "FIRMS_MAP_KEY":
return secret
return None
monkeypatch.setattr("keystore.get_api_key", _keys)
_clear_stats_cache()
resp = asyncio.run(_get("/api/stats"))
body = resp.json()
assert body["feeds"]["fires"]["configured"] is True
assert body["feeds"]["vessels"]["configured"] is False
assert secret not in resp.text
assert secret[-4:] not in resp.text
def test_stats_feeds_vessels_configured_from_either_key(monkeypatch):
async def _ais_only(name: str):
if name == "AISSTREAM_API_KEY":
return "aisstream-stored-value"
return None
monkeypatch.setattr("keystore.get_api_key", _ais_only)
_clear_stats_cache()
body = asyncio.run(_get("/api/stats")).json()
assert body["feeds"]["vessels"]["configured"] is True
assert body["feeds"]["fires"]["configured"] is False
async def _vesselapi_only(name: str):
if name == "VESSELAPI_API_KEY":
return "vesselapi-stored-value"
return ""
monkeypatch.setattr("keystore.get_api_key", _vesselapi_only)
_clear_stats_cache()
body = asyncio.run(_get("/api/stats")).json()
assert body["feeds"]["vessels"]["configured"] is True
assert body["feeds"]["fires"]["configured"] is False

View file

@ -1,549 +0,0 @@
"""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/news/blips",
"/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/news/blips",
"/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(monkeypatch):
monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False)
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(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)}
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")

View file

@ -1,59 +0,0 @@
"""Camera discovery must not become an events row."""
from __future__ import annotations
import asyncio
import inspect
import json
from datetime import datetime, timezone
def _camera() -> dict:
now = datetime(2026, 11, 14, 3, 43, tzinfo=timezone.utc)
return {
"vendor": "UCSD",
"source_url": "https://example.test/cameras/ucsd.jpg",
"location_lat": 32.88,
"location_lon": -117.24,
"location_name": "UCSD",
"discovery_source": "ucsd",
"url_hash": "abc123",
"snapshot_url": "https://example.test/cameras/ucsd.jpg",
"device_type": "snapshot",
"first_seen": now,
"last_seen": now,
}
def test_publish_new_cameras_does_not_emit_camera_event(monkeypatch):
"""One newly seen camera must not produce a NATS message with source_type=camera."""
import nats
import run_camera_service as svc
published: list[dict] = []
class _JS:
async def publish(self, _subject, payload):
published.append(json.loads(payload))
class _NC:
def jetstream(self):
return _JS()
async def close(self):
return None
async def _connect(*_a, **_k):
return _NC()
monkeypatch.setattr(nats, "connect", _connect)
if getattr(svc, "nats", None) is not None:
monkeypatch.setattr(svc.nats, "connect", _connect)
n = asyncio.run(svc.publish_new_cameras([_camera()]))
assert n == 0
assert published == []
src = inspect.getsource(svc.publish_new_cameras)
assert "Open camera" not in src
assert '"source_type": "camera"' not in src

View file

@ -1,152 +0,0 @@
"""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('<div class="lp-layer"', 0, idx)
assert start != -1, elem_id
end = HTML.find('<div class="lp-layer"', idx)
if end == -1:
end = idx + 400
return HTML[start:end]
def test_hide_keyed_on_feeds_configured_not_counts():
js = _feed_fns()
assert "function applyFeedConfig" not in js # sliced after the name
assert "feeds.vessels" in js
assert "feeds.fires" in js
assert "configured === false" in js
assert "lp-vessels-on" in js
assert "lp-fires-on" in js
for stay in ("lp-incidents-on", "lp-perim-on", "lp-trains-on", "lp-ac-on"):
assert stay not in js, stay
assert "=== 0" not in js
assert ".closest('.lp-layer')" in js
assert "row.hidden = hide" in js
assert "display = hide ? 'none'" in js
poll = _between("async function pollLayerStats", "function hideSwpcChip")
assert "applyFeedConfig(s)" in poll
assert 'class="lp-layer"' in _layer_chunk("lp-vessels-on")
assert 'class="lp-layer"' in _layer_chunk("lp-fires-on")
assert "FIRMS Fires" in _layer_chunk("lp-fires-on")
assert "Vessels" in _layer_chunk("lp-vessels-on")
assert "WFIGS" not in _layer_chunk("lp-fires-on")
def test_payloads_hide_only_unconfigured_vessel_and_firms_rows():
"""Run the real functions against stats payloads. Count 0 is not a hide signal."""
src = "function applyFeedConfig" + _feed_fns()
harness = r"""
const fs = require('fs');
const src = fs.readFileSync(process.argv[2], 'utf8');
const cases = JSON.parse(fs.readFileSync(process.argv[3], 'utf8'));
const IDS = ['lp-vessels-on','lp-fires-on','lp-incidents-on','lp-perim-on','lp-trains-on'];
function makeDoc() {
const byId = {};
function node(className, id) {
const el = {
id: id || '',
className,
hidden: false,
style: { display: '' },
parentElement: null,
closest(sel) {
const want = sel.replace(/^\./, '');
let n = this;
while (n) {
if ((n.className || '').split(/\s+/).includes(want)) return n;
n = n.parentElement;
}
return null;
},
};
if (id) byId[id] = el;
return el;
}
for (const id of IDS) {
const row = node('lp-layer');
const input = node('', id);
input.parentElement = row;
}
global.document = { getElementById(id) { return byId[id] || null; } };
}
eval(src);
const out = {};
for (const [name, payload] of Object.entries(cases)) {
makeDoc();
applyFeedConfig(payload);
out[name] = {};
for (const id of IDS) {
const row = document.getElementById(id).closest('.lp-layer');
out[name][id] = { hidden: row.hidden, display: row.style.display };
}
}
process.stdout.write(JSON.stringify(out));
"""
cases = {
"both_false": {
"vessels": 0,
"fires": 0,
"feeds": {"vessels": {"configured": False}, "fires": {"configured": False}},
},
"both_true": {
"vessels": 0,
"fires": 0,
"feeds": {"vessels": {"configured": True}, "fires": {"configured": True}},
},
"no_feeds": {"vessels": 0, "fires": 0, "trains": 0},
"counts_only_zero": {"vessels": 0, "fires": 0},
"vessels_only_unset": {
"feeds": {"vessels": {"configured": False}, "fires": {"configured": True}},
},
}
scratch = Path("/home/lancelot/.hermes/profiles/frontend/cache/scratch")
scratch.mkdir(parents=True, exist_ok=True)
src_path = scratch / "t_617c8a08-feed-fns.js"
cases_path = scratch / "t_617c8a08-feed-cases.json"
harness_path = scratch / "t_617c8a08-feed-harness.js"
src_path.write_text(src)
cases_path.write_text(json.dumps(cases))
harness_path.write_text(harness)
proc = subprocess.run(
["node", str(harness_path), str(src_path), str(cases_path)],
check=True,
capture_output=True,
text=True,
)
got = json.loads(proc.stdout)
hidden = {"hidden": True, "display": "none"}
shown = {"hidden": False, "display": ""}
stay = ("lp-incidents-on", "lp-perim-on", "lp-trains-on")
assert got["both_false"]["lp-vessels-on"] == hidden
assert got["both_false"]["lp-fires-on"] == hidden
for eid in stay:
assert got["both_false"][eid] == shown, eid
for name in ("both_true", "no_feeds", "counts_only_zero"):
for eid in ("lp-vessels-on", "lp-fires-on", *stay):
assert got[name][eid] == shown, (name, eid)
assert got["vessels_only_unset"]["lp-vessels-on"] == hidden
assert got["vessels_only_unset"]["lp-fires-on"] == shown
for eid in stay:
assert got["vessels_only_unset"][eid] == shown, eid

View file

@ -1,199 +0,0 @@
"""GDELT DOC 2.0 quota handling: no http retry on 429, backoff, prose bodies.
GDELT answers ``429`` with a plain-text "Please limit requests to one every 5
seconds" body and no Retry-After header. The ingester must not spend a second
request from the same IP on a status error, and must stop calling until the
backoff window expires instead of raising a traceback every cycle.
"""
from __future__ import annotations
import asyncio
import httpx
import pytest
@pytest.fixture(autouse=True)
def _reset_backoff(monkeypatch):
import sources
sources._gdelt_clear_backoff()
monkeypatch.setattr(sources, "GDELT_BACKOFF_BASE", 300)
monkeypatch.setattr(sources, "GDELT_BACKOFF_MAX", 1800)
# These tests cover the DOC 2.0 path, which is now the fallback behind the
# 15-minute bulk GKG file (tests/test_gdelt_bulk.py covers that path).
monkeypatch.setattr(sources, "GDELT_BULK_ENABLED", False)
yield
sources._gdelt_clear_backoff()
class _FakeClient:
"""Stands in for httpx.AsyncClient; records every GET it is asked for."""
def __init__(self, responses, calls):
self._responses = list(responses)
self._calls = calls
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def get(self, url, params=None):
self._calls.append(url)
resp = self._responses.pop(0)
resp.request = httpx.Request("GET", url)
return resp
def _install(monkeypatch, responses):
import sources
calls: list[str] = []
monkeypatch.setattr(
sources.httpx, "AsyncClient", lambda **kw: _FakeClient(responses, calls)
)
return calls
def _no_publish(monkeypatch):
import sources
published: list[str] = []
async def _fake(subject, event):
published.append(subject)
monkeypatch.setattr(sources, "publish_event", _fake)
return published
def test_429_does_not_retry_http_and_starts_backoff(monkeypatch):
import sources
calls = _install(
monkeypatch,
[httpx.Response(429, text="Please limit requests to one every 5 seconds")],
)
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
assert n == 0
assert calls == [sources.GDELT_API] # exactly one request, no http fallback
assert sources.gdelt_backoff_remaining() > 250
def test_cycle_skipped_while_backing_off(monkeypatch):
import sources
calls = _install(
monkeypatch, [httpx.Response(429, text="Please limit requests to one every 5 seconds")]
)
asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
assert len(calls) == 1
# A second cycle inside the window must not touch the network at all.
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
assert n == 0
assert len(calls) == 1
def test_backoff_doubles_then_caps(monkeypatch):
import sources
sources._gdelt_start_backoff()
first = sources._gdelt_backoff_secs
sources._gdelt_start_backoff()
second = sources._gdelt_backoff_secs
for _ in range(6):
sources._gdelt_start_backoff()
assert first == 300
assert second == 600
assert sources._gdelt_backoff_secs == 1800
def test_retry_after_header_is_honoured(monkeypatch):
import sources
_install(monkeypatch, [httpx.Response(429, headers={"Retry-After": "45"}, text="busy")])
asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
assert 40 <= sources.gdelt_backoff_remaining() <= 45
def test_200_prose_body_treated_as_throttle(monkeypatch):
import sources
calls = _install(
monkeypatch,
[httpx.Response(200, text="Please limit requests to one every 5 seconds")],
)
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
assert n == 0
assert len(calls) == 1
assert sources.gdelt_backoff_remaining() > 250
def test_success_publishes_and_clears_backoff(monkeypatch):
import sources
sources._gdelt_start_backoff()
sources._gdelt_clear_backoff()
published = _no_publish(monkeypatch)
_install(
monkeypatch,
[
httpx.Response(
200,
json={
"articles": [
{
"url": "https://example.com/a",
"title": "Protest",
"domain": "example.com",
"seendate": "20261121T120000Z",
"language": "English",
"sourcecountry": "United States",
}
]
},
)
],
)
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
assert n == 1
assert published == ["events.gdelt"]
assert sources.gdelt_backoff_remaining() == 0
def test_transport_error_still_falls_back_to_http(monkeypatch):
import sources
class _BoomClient(_FakeClient):
async def get(self, url, params=None):
self._calls.append(url)
if url.startswith("https://"):
raise httpx.ConnectError("tls handshake failed")
resp = self._responses.pop(0)
resp.request = httpx.Request("GET", url)
return resp
calls: list[str] = []
responses = [httpx.Response(200, json={"articles": []})]
monkeypatch.setattr(
sources.httpx, "AsyncClient", lambda **kw: _BoomClient(responses, calls)
)
_no_publish(monkeypatch)
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
assert n == 0
assert calls == [sources.GDELT_API, sources.GDELT_API.replace("https://", "http://", 1)]
assert sources.gdelt_backoff_remaining() == 0

View file

@ -1,274 +0,0 @@
"""GDELT 15-minute bulk GKG ingest (throttle-free path).
The DOC 2.0 API is per-IP quota'd (429). The same article coverage is served as
static 15-minute files with no key and no quota. These tests pin the mapping
from a GKG row into the existing ``events.gdelt`` event shape, the CONFIG-term
filter that keeps volume bounded, and the DOC fallback contract.
"""
from __future__ import annotations
import io
import zipfile
import httpx
import pytest
LASTUPDATE = """33287 99e984fd826497ae5765484af3b11521 http://data.gdeltproject.org/gdeltv2/20261121234500.export.CSV.zip
46052 c09f32f728f695f2bf753540aa92e6ce http://data.gdeltproject.org/gdeltv2/20261121234500.mentions.CSV.zip
2361330 0804c7df5b359f177aeff85cad63d539 http://data.gdeltproject.org/gdeltv2/20261121234500.gkg.csv.zip
"""
# GKG row shape (27 tab-separated fields): id, date, collection, common name,
# document id, V1Counts, V2Counts, V1Themes, V2Themes, V2Locations, ..., tone,
# ..., V2ExtrasXML.
GKG_ROW = "\t".join([
"20261121234500-11",
"20261121234500",
"1",
"dominicanrepublicpost.com",
"https://dominicanrepublicpost.com/protest-in-iowa/",
"PROTEST#29000##0######;",
"PROTEST#29000##0#######287;",
"PROTEST;TAX_FNCACT;VIOLENT_UNREST;",
"PROTEST,12;TAX_FNCACT,4;",
"",
"",
"",
"",
"",
"",
"-4.75,0.5,6.1,7.2,18.3,0,206",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
(
"<PAGE_AUTHORS>Gary Stevens</PAGE_AUTHORS>"
"<PAGE_PRECISEPUBTIMESTAMP>20261121211600</PAGE_PRECISEPUBTIMESTAMP>"
"<PAGE_TITLE>Protest in Iowa &amp; Nebraska</PAGE_TITLE>"
),
])
LOCATIONS_ROW = "\t".join([
"20261121234500-12", "20261121234500", "1", "wkzo.com",
"https://wkzo.com/power-outage/",
"", "", "POWER_OUTAGE;CYBER_ATTACK;", "POWER_OUTAGE,9;", "",
"", "", "", "", "", "-2.0,0.1,1.0,1.0,1.0,0,10", "", "", "", "", "", "", "",
"", "", "", "<PAGE_TITLE>Power outage hits grid</PAGE_TITLE>",
])
@pytest.fixture(autouse=True)
def _reset_bulk_state(monkeypatch):
import sources
monkeypatch.setattr(sources, "_gdelt_bulk_last_file", None)
monkeypatch.setattr(sources, "GDELT_BULK_MAX_EVENTS", 100)
sources._gdelt_clear_backoff()
yield
sources._gdelt_clear_backoff()
def _gkg_zip(rows: list[str]) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr("20261121234500.gkg.csv", "\n".join(rows) + "\n")
return buf.getvalue()
class _FakeClient:
def __init__(self, index_text: str, archive: bytes | None, calls: list[str], fail_archive=False):
self._index_text = index_text
self._archive = archive
self._calls = calls
self._fail_archive = fail_archive
async def __aenter__(self):
return self
async def __aexit__(self, *exc):
return False
async def get(self, url, params=None, **kw):
self._calls.append(url)
request = httpx.Request("GET", url)
if url.endswith("lastupdate.txt"):
return httpx.Response(200, text=self._index_text, request=request)
if self._fail_archive:
raise httpx.TransportError("boom")
return httpx.Response(200, content=self._archive or b"", request=request)
def _install(monkeypatch, index_text=LASTUPDATE, archive=None, fail_archive=False):
import sources
calls: list[str] = []
monkeypatch.setattr(
sources.httpx, "AsyncClient",
lambda **kw: _FakeClient(index_text, archive, calls, fail_archive),
)
return calls
def _collect(monkeypatch):
import sources
published: list[dict] = []
async def _fake_publish(subject, events):
assert subject == "events.gdelt"
published.extend(events)
return len(events)
monkeypatch.setattr(sources, "_publish_unknown", _fake_publish)
return published
def _no_network(monkeypatch):
"""Fail the run if anything reaches the DOC 2.0 API."""
import sources
async def _boom(*a, **kw):
raise AssertionError("DOC API must not be called when bulk data lands")
monkeypatch.setattr(sources, "_ingest_gdelt_doc", _boom)
def test_query_terms_from_config_string():
import sources
assert sources.gdelt_query_terms("") == [
"unrest", "protest", "outage", "cyber", "power outage",
]
assert sources.gdelt_query_terms('(flood OR "power outage")') == [
"flood", "power outage",
]
def test_select_gdelt_bulk_url_picks_gkg_and_forces_https():
import sources
picked = sources.select_gdelt_bulk_url(LASTUPDATE)
assert picked == (
"20261121234500.gkg.csv.zip",
"https://data.gdeltproject.org/gdeltv2/20261121234500.gkg.csv.zip",
)
assert sources.select_gdelt_bulk_url("") is None
def test_parse_gkg_row_maps_into_event_shape():
import sources
terms = sources.gdelt_query_terms("")
event = sources.parse_gkg_row(GKG_ROW.split("\t"), terms, "20261121234500.gkg.csv.zip")
assert event["source_type"] == "gdel-t2"
assert event["url"] == "https://dominicanrepublicpost.com/protest-in-iowa/"
assert event["title"] == "Protest in Iowa & Nebraska"
assert event["body"] == "dominicanrepublicpost.com"
# Publish time comes from PAGE_PRECISEPUBTIMESTAMP, not the window stamp.
assert event["source_timestamp"] == "2026-11-21T21:16:00+00:00"
assert "protest" in event["tags"] and "VIOLENT_UNREST" in event["tags"]
assert event["raw"]["bulk_file"] == "20261121234500.gkg.csv.zip"
assert event["raw"]["tone"] == pytest.approx(-4.75 / 4249.0)
# No V2Locations in this row -> no fake geo.
assert event["location_lat"] is None and event["location_lon"] is None
def test_parse_gkg_row_reads_geo_from_v2locations():
import sources
row = GKG_ROW.split("\t")
row[9] = (
"4#Middletown, Iowa, United States#US#IA#40.8284#-91.259#-1834425"
";1#United States#US#US#39.8283#-98.5795#US"
)
event = sources.parse_gkg_row(row, sources.gdelt_query_terms(""))
assert event["location_lat"] == pytest.approx(40.8284)
assert event["location_lon"] == pytest.approx(-91.259)
assert event["location_name"] == "Middletown, Iowa, United States"
def test_gkg_location_tolerates_short_and_bad_forms():
import sources
# adm2 slot dropped: lat/lon are still the last two before the feature id.
assert sources._gkg_location("2#California, United States#US#USCA#36.17#-119.746#CA") == (
pytest.approx(36.17), pytest.approx(-119.746), "California, United States",
)
assert sources._gkg_location("")[0] is None
assert sources._gkg_location("1#Nowhere#US#US#999#999#X")[0] is None
def test_parse_gkg_row_drops_rows_without_query_terms():
import sources
row = GKG_ROW.split("\t")
row[7] = "SPORTS;ENTERTAINMENT;"
assert sources.parse_gkg_row(row, sources.gdelt_query_terms("")) is None
row = GKG_ROW.split("\t")
row[4] = ""
assert sources.parse_gkg_row(row, sources.gdelt_query_terms("")) is None
@pytest.mark.asyncio
async def test_ingest_gdelt_bulk_publishes_filtered_rows_and_skips_repeat(monkeypatch):
import sources
_install(monkeypatch, archive=_gkg_zip([GKG_ROW, LOCATIONS_ROW]))
published = _collect(monkeypatch)
_no_network(monkeypatch)
count = await sources.ingest_gdelt()
assert count == 2
assert {e["url"] for e in published} == {
"https://dominicanrepublicpost.com/protest-in-iowa/",
"https://wkzo.com/power-outage/",
}
# Second cycle: same file, nothing new fetched or published.
before = len(published)
assert await sources.ingest_gdelt() == 0
assert len(published) == before
@pytest.mark.asyncio
async def test_ingest_gdelt_bulk_caps_events_per_file(monkeypatch):
import sources
rows = []
for i in range(5):
row = GKG_ROW.split("\t")
row[0] = f"20261121234500-{i}"
row[4] = f"https://example.com/story-{i}"
rows.append("\t".join(row))
_install(monkeypatch, archive=_gkg_zip(rows))
published = _collect(monkeypatch)
_no_network(monkeypatch)
assert await sources.ingest_gdelt_bulk(max_events=2) == 2
assert len(published) == 2
@pytest.mark.asyncio
async def test_ingest_gdelt_falls_back_to_doc_when_bulk_fails(monkeypatch):
import sources
_install(monkeypatch, fail_archive=True)
calls = {"doc": 0}
async def _doc(query="", max_articles=50):
calls["doc"] += 1
return 7
monkeypatch.setattr(sources, "_ingest_gdelt_doc", _doc)
assert await sources.ingest_gdelt() == 7
assert calls["doc"] == 1

View file

@ -361,484 +361,3 @@ def test_snapshot_queries_st_intersects(monkeypatch):
assert "aircraft_tracks_1min" in blob
assert "vessel_tracks_1min" in blob
assert "from fires" in blob
def _reset_geofence_state():
geofence._cache.clear()
geofence._recent_hits.clear()
geofence._notified_once.clear()
class _MapResult:
def __init__(self, rows):
self._rows = rows
self.rowcount = 1
self.inserted_primary_key = ["evt-1"]
def mappings(self):
return self
def all(self):
return self._rows
def first(self):
return self._rows[0] if self._rows else None
def _fence_session(inserts, cameras, news, already=None):
"""Fake session: evidence queries return rows; inserts are recorded."""
already_rows = [] if already is None else already
class Sess:
async def execute(self, stmt, params=None):
sql = str(stmt).lower()
if "insert into geofence_alerts" in sql:
inserts.append(params or {})
return _MapResult([])
if "from cameras" in sql:
return _MapResult(cameras)
if "from news_items" in sql and "kind = 'map'" not in sql and "kind = " not in sql:
return _MapResult(news)
if "from geofence_alerts" in sql:
return _MapResult(already_rows)
return _MapResult([])
async def commit(self):
inserts.append("commit")
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
return Sess
def _install_polygon(monkeypatch, inserts, cameras=None, news=None, already=None):
_reset_geofence_state()
fence = {"id": FENCE_ID, "name": "NC", "geojson": NC_BOX, "active": True}
async def fake_st(lon, lat):
return matching_geofences(lon, lat, [fence])
monkeypatch.setattr(geofence, "st_intersects", fake_st)
if cameras is None:
cameras = [{
"id": "cam-1",
"name": "Dock",
"snapshot_url": "rtsp://agency.example/stream",
}]
if news is None:
news = [{
"headline": "Quake felt",
"url": "https://example.com/q",
"importance": "high",
}]
monkeypatch.setattr(
geofence, "async_session",
lambda: _fence_session(inserts, cameras, news, already)(),
)
return fence
def _alert_rows(inserts):
return [p for p in inserts if isinstance(p, dict)]
def _evidence(row):
import json
return json.loads(row["payload"])["evidence"]
def test_camera_evidence_never_copies_agency_or_rtsp_url():
from geofence import _CAMERAS_INSIDE_SQL, camera_evidence
assert "snapshot_url" not in _CAMERAS_INSIDE_SQL.lower()
row = camera_evidence({
"id": "abc",
"name": "",
"snapshot_url": "rtsp://agency.example/live",
"location_name": "ignored-when-name-set",
})
assert row == {
"id": "abc",
"name": "",
"snapshot_url": "/api/cameras/abc/snapshot",
}
assert "rtsp" not in row["snapshot_url"]
assert not row["snapshot_url"].startswith("http")
def test_evidence_caps_and_empty_arrays():
from datetime import datetime, timezone
from geofence import evidence_pack
now = datetime(2026, 8, 28, 12, 4, tzinfo=timezone.utc)
cams = [{"id": f"c{i}", "name": f"n{i}"} for i in range(8)]
news = [
{"headline": f"h{i}", "url": "", "importance": ""} for i in range(6)
]
pack = evidence_pack(FENCE_ID, now, cams, news)
assert len(pack["cameras"]) == 5
assert len(pack["news"]) == 3
empty = evidence_pack(FENCE_ID, now, [], [])
assert empty["cameras"] == []
assert empty["news"] == []
assert empty["snapshot"] == f"/api/geofences/{FENCE_ID}/at?ts=2026-08-28T12:04:00Z"
def test_inside_writes_evidence_outside_writes_nothing(monkeypatch):
"""Polygon fixture: inside → 1 row + evidence; outside → 0. Each new kind."""
import json
from urllib.parse import parse_qs, urlsplit
from tracks import parse_timestamp
for kind, entity in (
("earthquake", "ci1"),
("fire_incident", "IRWIN-1"),
("news", "42"),
):
inserts: list = []
_install_polygon(monkeypatch, inserts)
async def run(k=kind, eid=entity):
inside = await geofence.record_and_notify(
source_kind=k, entity_id=eid, lat=35.5, lon=-79.0,
payload={"label": "inside"},
)
outside = await geofence.record_and_notify(
source_kind=k, entity_id=eid + "-out", lat=37.7, lon=-122.4,
payload={"label": "outside"},
)
return inside, outside
n_in, n_out = asyncio.run(run())
rows = _alert_rows(inserts)
assert n_out == 0
assert rows and len(rows) == 1, kind
assert rows[0]["source_kind"] == kind
ev = json.loads(rows[0]["payload"])["evidence"]
assert set(ev) == {"cameras", "news", "snapshot"}
assert set(ev["cameras"][0]) == {"id", "name", "snapshot_url"}
assert set(ev["news"][0]) == {"headline", "url", "importance"}
assert ev["cameras"][0]["id"] == "cam-1"
assert ev["cameras"][0]["name"] == "Dock"
assert ev["cameras"][0]["snapshot_url"] == "/api/cameras/cam-1/snapshot"
assert ev["news"][0] == {
"headline": "Quake felt",
"url": "https://example.com/q",
"importance": "high",
}
assert ev["snapshot"].startswith(f"/api/geofences/{FENCE_ID}/at?ts=")
assert "rtsp" not in json.dumps(ev)
assert "http" not in ev["cameras"][0]["snapshot_url"]
qs = parse_qs(urlsplit(ev["snapshot"]).query)
assert "ts" in qs and "timestamp" not in qs
assert parse_timestamp(qs["ts"][0]) is not None
assert n_in == 0 or n_in >= 0 # WS fan-out may be 0 with no clients
def test_firms_hit_omits_evidence(monkeypatch):
inserts: list = []
_install_polygon(monkeypatch, inserts)
async def run():
return await geofence.record_and_notify(
source_kind="firms", entity_id="35.5,-79.0,N",
lat=35.5, lon=-79.0, payload={"satellite": "N"},
)
asyncio.run(run())
rows = _alert_rows(inserts)
import json
body = json.loads(rows[0]["payload"])
assert "evidence" not in body
assert body["satellite"] == "N"
def test_same_entity_inside_five_minutes_is_one_row(monkeypatch):
inserts: list = []
_install_polygon(monkeypatch, inserts)
async def run():
a = await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-1",
lat=35.5, lon=-79.0, payload={"label": "Foster"},
)
b = await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-1",
lat=35.5, lon=-79.0, payload={"label": "Foster"},
)
return a, b
asyncio.run(run())
assert len(_alert_rows(inserts)) == 1
def test_skip_existing_does_not_renotify_after_cooldown(monkeypatch):
"""A later poll of the same incident id must not insert again."""
inserts: list = []
already = []
_install_polygon(monkeypatch, inserts, already=already)
async def run():
await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-9",
lat=35.5, lon=-79.0, skip_existing=True,
)
geofence._recent_hits.clear()
geofence._notified_once.clear()
already.append({"one": 1})
await geofence.record_and_notify(
source_kind="fire_incident", entity_id="IRWIN-9",
lat=35.5, lon=-79.0, skip_existing=True,
)
asyncio.run(run())
assert len(_alert_rows(inserts)) == 1
def test_camera_kind_is_refused(monkeypatch):
inserts: list = []
called = {"st": 0}
_install_polygon(monkeypatch, inserts)
async def fake_st(lon, lat):
called["st"] += 1
return [{"id": FENCE_ID, "name": "NC", "active": True}]
monkeypatch.setattr(geofence, "st_intersects", fake_st)
async def run():
return await geofence.record_and_notify(
source_kind="camera", entity_id="cam-1", lat=35.5, lon=-79.0,
)
assert asyncio.run(run()) == 0
assert called["st"] == 0
assert _alert_rows(inserts) == []
def test_camera_publish_and_insert_do_not_notify(monkeypatch):
import camera_scraper
import ingestor
import run_camera_service
from datetime import datetime, timezone
called = []
async def fake_record(**kwargs):
called.append(kwargs)
return 0
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
class Sess:
async def execute(self, stmt, params=None):
return _MapResult([])
async def commit(self):
return None
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(camera_scraper, "async_session", lambda: Sess())
async def upsert():
return await camera_scraper.upsert_cameras([{
"source_url": "http://cam.example/snap",
"discovery_source": "test",
"location_lat": 35.5,
"location_lon": -79.0,
"location_name": "Dock",
"snapshot_url": "rtsp://agency.example/stream",
}])
assert asyncio.run(upsert()) == 1
assert called == []
monkeypatch.setattr(ingestor, "async_session", lambda: Sess())
async def ingest_cam():
return await ingestor.ingest_event({
"source_type": "camera",
"title": "Open camera",
"url": "http://cam.example/snap",
"location_lat": 35.5,
"location_lon": -79.0,
"location_name": "Dock",
"source_timestamp": "2026-08-28T12:00:00+00:00",
})
assert asyncio.run(ingest_cam()) == "evt-1"
assert called == []
now = datetime(2026, 8, 28, 12, tzinfo=timezone.utc)
class Pub:
async def publish(self, *a, **k):
return None
class NC:
def jetstream(self):
return Pub()
async def close(self):
return None
class _Nats:
@staticmethod
async def connect(*a, **k):
return NC()
class CamSess:
async def execute(self, stmt, params=None):
return _MapResult([{
"vendor": "x",
"source_url": "http://cam.example/snap",
"location_lat": 35.5,
"location_lon": -79.0,
"location_name": "Dock",
"discovery_source": "test",
"url_hash": "abc",
"snapshot_url": "rtsp://agency.example/stream",
"device_type": "rtsp",
"first_seen": now,
"last_seen": now,
}])
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(run_camera_service, "nats", _Nats)
monkeypatch.setattr(run_camera_service, "async_session", lambda: CamSess())
async def publish():
return await run_camera_service.publish_new_cameras()
assert asyncio.run(publish()) == 1
assert called == []
assert all(c.get("source_kind") != "camera" for c in called)
def test_fire_poll_inside_notifies_outside_does_not(monkeypatch):
calls = []
async def fake_load(bbox):
assert bbox == "-80.0,35.0,-78.0,36.0"
return [
{
"id": "In Fire", "lat": 35.5, "lon": -79.0, "label": "In Fire",
"extra": {"irwin_id": "IRWIN-IN", "src": "wfigs"},
},
{
"id": "Out Fire", "lat": 37.7, "lon": -122.4, "label": "Out Fire",
"extra": {"irwin_id": "IRWIN-OUT", "src": "wfigs"},
},
]
async def fake_record(**kwargs):
calls.append(kwargs)
return 1
monkeypatch.setattr("live_layers.load_fire_incidents", fake_load)
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
fence = {"id": FENCE_ID, "name": "NC", "geojson": NC_BOX, "active": True}
async def run():
return await geofence.poll_fire_incidents([fence])
assert asyncio.run(run()) == 1
assert len(calls) == 1
assert calls[0]["source_kind"] == "fire_incident"
assert calls[0]["entity_id"] == "IRWIN-IN"
assert calls[0]["skip_existing"] is True
def test_ingest_earthquake_notifies_camera_message_does_not(monkeypatch):
import ingestor
calls = []
async def fake_record(**kwargs):
calls.append(kwargs)
return 1
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
class Sess:
async def execute(self, stmt, params=None):
return _MapResult([])
async def commit(self):
return None
async def __aenter__(self):
return self
async def __aexit__(self, *a):
return False
monkeypatch.setattr(ingestor, "async_session", lambda: Sess())
async def run():
qid = await ingestor.ingest_event({
"source_type": "earthquake",
"title": "M 2.1",
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci1",
"location_lat": 35.5,
"location_lon": -79.0,
"raw": {"usgs_id": "ci1"},
"source_timestamp": "2026-08-28T12:00:00+00:00",
})
cid = await ingestor.ingest_event({
"source_type": "camera",
"title": "cam",
"url": "http://cam.example/a",
"location_lat": 35.5,
"location_lon": -79.0,
"source_timestamp": "2026-08-28T12:00:00+00:00",
})
return qid, cid
qid, cid = asyncio.run(run())
assert qid == "evt-1"
assert cid == "evt-1"
assert len(calls) == 1
assert calls[0]["source_kind"] == "earthquake"
assert calls[0]["entity_id"] == "ci1"
assert calls[0]["lat"] == 35.5
assert calls[0]["lon"] == -79.0
def test_news_scan_reads_pins_without_summarizer(monkeypatch):
calls = []
async def fake_rows(sql, params):
assert "news_items" in sql
assert "kind = 'map'" in sql
return [{
"id": "9", "headline": "Bridge", "url": "https://n.example/b",
"importance": "critical", "lat": 35.5, "lon": -79.0,
}]
async def fake_record(**kwargs):
calls.append(kwargs)
return 1
monkeypatch.setattr(geofence, "_rows", fake_rows)
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
async def run():
return await geofence.scan_news_pins()
assert asyncio.run(run()) == 1
assert calls[0]["source_kind"] == "news"
assert calls[0]["entity_id"] == "9"
assert calls[0]["skip_existing"] is True

View file

@ -2,9 +2,6 @@
from __future__ import annotations
import json
import subprocess
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
@ -57,151 +54,3 @@ 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
def _inbox_src() -> str:
news = HTML.split("function newsEsc", 1)[1].split("function newsTimeAgo", 1)[0]
inbox = HTML.split("function gfHitTime", 1)[1].split("function onGfHitClick", 1)[0]
return "function newsEsc" + news + "function gfHitTime" + inbox
def _render_inbox(hits: list) -> list[dict]:
harness = r"""
const fs = require('fs');
const src = fs.readFileSync(process.argv[2], 'utf8');
const hits = JSON.parse(fs.readFileSync(process.argv[3], 'utf8'));
var gfNameById = {};
function makeBox() {
const kids = [];
const box = {
children: kids,
prepend(el) { kids.unshift(el); },
removeChild(el) {
const i = kids.indexOf(el);
if (i >= 0) kids.splice(i, 1);
},
};
global.document = {
getElementById(id) { return id === 'gf-inbox' ? box : null; },
createElement() {
return { type: '', className: '', dataset: {}, innerHTML: '', onclick: null };
},
};
return box;
}
eval(src);
const out = [];
for (const hit of hits) {
const box = makeBox();
pushGfInbox(hit);
const el = box.children[0];
out.push({
html: el ? el.innerHTML : '',
hasOnclick: !!(el && typeof el.onclick === 'function'),
});
}
process.stdout.write(JSON.stringify(out));
"""
with tempfile.TemporaryDirectory() as td:
root = Path(td)
src_path = root / "inbox.js"
hits_path = root / "hits.json"
harness_path = root / "harness.js"
src_path.write_text(_inbox_src())
hits_path.write_text(json.dumps(hits))
harness_path.write_text(harness)
proc = subprocess.run(
["node", str(harness_path), str(src_path), str(hits_path)],
check=False,
capture_output=True,
text=True,
)
assert proc.returncode == 0, proc.stderr
return json.loads(proc.stdout)
def test_push_gf_inbox_evidence_pack():
"""Second line from payload.evidence; missing evidence stays the one-liner."""
linked = {
"geofence_name": "Yard",
"source_kind": "news",
"entity_id": "n-1",
"created_at": "2026-11-14T05:00:00Z",
"payload": {
"evidence": {
"cameras": [
{"id": "c1", "name": "North Gate", "snapshot_url": "rtsp://camera/1"},
{"id": "c2", "name": "South Gate", "snapshot_url": "/api/cameras/c2/snapshot"},
],
"news": [{"headline": "Fence brief", "url": "https://ex.com/1", "importance": "high"}],
"snapshot": "/api/geofences/g1/at?ts=2026-11-14T05:00:00Z",
}
},
}
text_news = {
"geofence_name": "Yard",
"source_kind": "earthquake",
"entity_id": "eq-9",
"payload": {
"evidence": {
"cameras": [],
"news": [{"headline": "Silent quake", "url": "", "importance": ""}],
}
},
}
bare = {
"geofence_name": "Old Fence",
"source_kind": "adsb",
"entity_id": "abc123",
"payload": {"icao": "abc123"},
}
top_level = {
"geofence_name": "Top",
"source_kind": "fire_incident",
"entity_id": "fi-1",
"evidence": {
"cameras": [{"id": "c9", "name": "Lot Cam", "snapshot_url": "rtsp://camera/1"}],
"news": [{"headline": "Lot fire", "url": "https://ex.com/1", "importance": ""}],
},
}
as_string = {
"geofence_name": "String Fence",
"source_kind": "news",
"entity_id": "s1",
"payload": json.dumps({
"evidence": {
"cameras": [{"id": "c3", "name": "Cam A", "snapshot_url": "rtsp://camera/1"}],
"news": [{"headline": "From string", "url": "https://ex.com/1", "importance": ""}],
}
}),
}
rendered = _render_inbox([linked, text_news, bare, top_level, as_string])
html, quiet, plain, fallback, parsed = [row["html"] for row in rendered]
assert "2 cams" in html
assert "North Gate" in html
assert 'href="https://ex.com/1"' in html
assert 'target="_blank"' in html
assert 'rel="noopener"' in html
assert "stopPropagation" in html
assert "rtsp://camera/1" not in html
assert rendered[0]["hasOnclick"]
assert "Silent quake" in quiet
assert "<a" not in quiet
assert "Yard" in quiet
assert "Old Fence" in plain
assert "adsb" in plain
assert "abc123" in plain
assert "cams" not in plain
assert "<br>" not in plain
assert rendered[2]["hasOnclick"]
assert "1 cams" in fallback
assert 'href="https://ex.com/1"' in fallback
assert "rtsp://camera/1" not in fallback
assert "1 cams" in parsed
assert "From string" in parsed
assert "rtsp://camera/1" not in parsed

View file

@ -3,21 +3,12 @@
from __future__ import annotations
import asyncio
import os
from datetime import datetime, timedelta, timezone
import asyncpg
import httpx
import pytest
from conftest import requires_db
from main import app
BASE = "http://test"
_FIXTURE_URLS = (
"https://test.invalid/t_ceb74e64/future",
"https://test.invalid/t_ceb74e64/fresh",
)
async def _get(path: str) -> httpx.Response:
@ -40,67 +31,3 @@ def test_ready_endpoint_exists():
body = resp.json()
assert "checks" in body
assert "status" in body
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"],
}
async def _prepare_article_age_fixture() -> None:
"""Insert one row at now+6d and one at now-120s. Deletes only those URLs."""
conn = await asyncpg.connect(**_conn_kwargs())
try:
await conn.execute(
"DELETE FROM articles WHERE url = ANY($1::text[])",
list(_FIXTURE_URLS),
)
now = datetime.now(timezone.utc)
await conn.executemany(
"INSERT INTO articles (title, url, content, domain, timestamp) "
"VALUES ($1, $2, $3, $4, $5)",
[
("future", _FIXTURE_URLS[0], "x", "test.invalid", now + timedelta(days=6)),
("fresh", _FIXTURE_URLS[1], "x", "test.invalid", now - timedelta(seconds=120)),
],
)
finally:
await conn.close()
async def _delete_article_age_fixture() -> None:
conn = await asyncpg.connect(**_conn_kwargs())
try:
await conn.execute(
"DELETE FROM articles WHERE url = ANY($1::text[])",
list(_FIXTURE_URLS),
)
finally:
await conn.close()
@pytest.fixture()
def article_age_rows():
asyncio.run(_prepare_article_age_fixture())
yield
asyncio.run(_delete_article_age_fixture())
@requires_db
def test_health_article_age_ignores_future_rows(article_age_rows):
"""Future-dated rows must not pin articles.age_s negative.
Fixture: one row at now+6d, one at now-120s. age_s is the age of the
newest timestamp that is not in the future (NULL timestamps do not count).
"""
body = asyncio.run(_get("/api/health")).json()
articles = body["checks"]["articles"]
age = articles["age_s"]
assert age is not None
assert 0 <= age <= 600, articles
assert articles["ok"] is True

View file

@ -10,8 +10,6 @@ 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"
@ -20,7 +18,6 @@ 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)

View file

@ -2,12 +2,9 @@
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:
@ -43,141 +40,3 @@ 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
# ── CDATA title unwrap (ingest) ───────────────────────────────────────────
# Excelsior stores the wrapper as text, including the leading newline the
# feed leaves around <![CDATA[...]]>. A plain title, and real HTML that is
# not that wrapper, must pass through unchanged.
@pytest.mark.parametrize(
"raw,expected",
[
("<![CDATA[Hello]]>", "Hello"),
("\n <![CDATA[Hello]]>", "Hello"),
(
"\n <![CDATA[Hello]]> ",
"Hello",
),
("Hello", "Hello"),
(" Hello ", " Hello "),
("<b>Hello</b>", "<b>Hello</b>"),
("See <![CDATA[Hello]]>", "See <![CDATA[Hello]]>"),
(None, None),
],
)
def test_unwrap_cdata_title(raw, expected):
from newsScraper.feed_util import unwrap_cdata_title
assert unwrap_cdata_title(raw) == expected
@pytest.mark.parametrize(
"raw,expected",
[
("<![CDATA[Hello]]>", "Hello"),
("\n <![CDATA[Hello]]>", "Hello"),
("Hello", "Hello"),
("<b>Hello</b>", "<b>Hello</b>"),
],
)
def test_pipeline_stores_cdata_title_unwrapped(raw, expected):
pipe = _pipeline()
spider = _FakeSpider()
recent = _dt.datetime.now(_dt.timezone.utc) - _dt.timedelta(hours=1)
item = _item(recent)
item["title"] = raw
returned = pipe.process_item(item, spider)
assert returned["title"] == expected
stored = pipe.cur.executed[0][1][0]
assert stored == expected

View file

@ -8,15 +8,12 @@ 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)
@ -67,43 +64,7 @@ def test_geofence_alerts_passes_filters(monkeypatch):
assert seen["until"] is not None
def test_geofence_at_accepts_ts_alias(monkeypatch):
seen = {}
async def snap(gid: str, ts):
seen["gid"] = gid
seen["ts"] = ts
return {
"geofence_id": gid,
"timestamp": ts.isoformat(),
"aircraft": [],
"vessels": [],
"fires": [],
}
monkeypatch.setattr("geofence.snapshot_at", snap)
resp = asyncio.run(_req(
"GET", f"/api/geofences/{FENCE_ID}/at",
params={"ts": "2026-08-28T12:04:00Z"},
))
assert resp.status_code == 200
assert seen["gid"] == FENCE_ID
assert seen["ts"].year == 2026
def test_geofence_alerts_accepts_new_kinds(monkeypatch):
seen = {}
async def fake_list(**kwargs):
seen.update(kwargs)
return []
monkeypatch.setattr("geofence.list_alerts", fake_list)
resp = asyncio.run(_req(
"GET", "/api/geofence-alerts", params={"source_kind": "earthquake"},
))
assert resp.status_code == 200
assert seen["source_kind"] == "earthquake"
def test_geofence_alerts_rejects_bad_source_kind():
resp = asyncio.run(_req(
"GET", "/api/geofence-alerts", params={"source_kind": "camera"},
))