Compare commits
126 changed files with 1838 additions and 58523 deletions
96
.env.example
96
.env.example
|
|
@ -31,6 +31,20 @@ NOMINATIM_URL=https://nominatim.openstreetmap.org
|
||||||
NOMINATIM_MIN_INTERVAL=1.1
|
NOMINATIM_MIN_INTERVAL=1.1
|
||||||
SNAPSHOT_TTL_SECONDS=300
|
SNAPSHOT_TTL_SECONDS=300
|
||||||
|
|
||||||
|
# ── masscan active camera discovery (host-level systemd service, NOT compose) ─
|
||||||
|
# Continuous rolling sweep for open RTSP port 554 across a range. Runs on the
|
||||||
|
# Pi host via deploy/osint-masscan.service (needs root + raw sockets). Results
|
||||||
|
# land in the same `cameras` table as the scraper (discovery_source=masscan).
|
||||||
|
# NOTE: 200 pps is the residential-safe default. 1k/10k pps saturated a home
|
||||||
|
# uplink. A full 0.0.0.0/0 sweep at 200 pps takes ~8 months (rolling).
|
||||||
|
MASSCAN_RANGE=0.0.0.0/0
|
||||||
|
MASSCAN_PORTS=554
|
||||||
|
MASSCAN_RATE=200
|
||||||
|
MASSCAN_RETRIES=1
|
||||||
|
MASSCAN_WAIT=0
|
||||||
|
MASSCAN_EXCLUDEFILE=/etc/osint-dashboard/masscan-excludes.txt
|
||||||
|
MASSCAN_FLUSH_EVERY=250
|
||||||
|
|
||||||
# ── NASA FIRMS (active fire / hotspot ingest) ──────────────────────────────
|
# ── NASA FIRMS (active fire / hotspot ingest) ──────────────────────────────
|
||||||
# MAP_KEY is FREE — get one at https://firms.modaps.eosdis.nasa.gov/api/map_key_info/
|
# MAP_KEY is FREE — get one at https://firms.modaps.eosdis.nasa.gov/api/map_key_info/
|
||||||
# (1-minute signup, no payment). Leave blank to keep fire ingest idle.
|
# (1-minute signup, no payment). Leave blank to keep fire ingest idle.
|
||||||
|
|
@ -45,88 +59,34 @@ FIRMS_INTERVAL=900
|
||||||
# Set to 0 to disable the fire loop entirely.
|
# Set to 0 to disable the fire loop entirely.
|
||||||
INGEST_FIRES=1
|
INGEST_FIRES=1
|
||||||
|
|
||||||
# ── VesselAPI (commercial REST AIS — Hormuz, 5×/day, 150 calls/mo cap) ─────
|
|
||||||
# Independent of AISStream (open/shared live US-coast WebSocket). Both stay
|
|
||||||
# on when their keys are set; missing one never disables the other.
|
|
||||||
# Prefer pasting VESSELAPI_API_KEY on the dashboard Keys page.
|
|
||||||
# The poller idles when the key is unset. Never called from map pans
|
|
||||||
# (GET /api/vessels serves the shared last-known cache only).
|
|
||||||
VESSELAPI_API_KEY=
|
|
||||||
# Bounding box(es) as minlat,minlon,maxlat,maxlon (lat/lon order). Semicolon-
|
|
||||||
# separated for multiple boxes. Default = Strait of Hormuz (span 3.6 ≤ 4° cap).
|
|
||||||
VESSELAPI_BBOX=25.5,55.4,27.3,57.2
|
|
||||||
# Poll cadence in seconds (17280 = 4.8h → 5 polls/day = 150/mo).
|
|
||||||
VESSELAPI_INTERVAL=17280
|
|
||||||
# Local hard cap on successful 2xx calls per UTC day (persisted in Postgres).
|
|
||||||
VESSELAPI_MAX_CALLS_PER_DAY=5
|
|
||||||
# 1 = run the poller inside the dashboard process (default); ingester off.
|
|
||||||
VESSELAPI_IN_APP=1
|
|
||||||
VESSELAPI_IN_INGEST=0
|
|
||||||
|
|
||||||
# ── API keys (managed from the dashboard UI) ──────────────────────────────
|
# ── API keys (managed from the dashboard UI) ──────────────────────────────
|
||||||
# Keys such as NOUS_API_KEY and TELEGRAM_TOKEN are stored in the Postgres
|
# Keys such as GEMINI_API_KEY and TELEGRAM_TOKEN are stored in the Postgres
|
||||||
# `api_keys` table and managed from the dashboard's "Keys" tab
|
# `api_keys` table and managed from the dashboard's "Keys" tab
|
||||||
# (GET/POST/DELETE /api/keys/{name}) — see app/keystore.py. The FIRMS ingestor
|
# (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
|
# currently reads FIRMS_MAP_KEY from .env (above); wiring the Keys-UI store as
|
||||||
# its lookup/fallback is a planned follow-up.
|
# 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`) ────────────────
|
# ── News pipeline (scraper + summarizer, profile `ingest`) ────────────────
|
||||||
# Scraper crawls urls.txt continuously (default 10s between crawls).
|
# Hourly: the scraper crawls 257 RSS sources at minute :00 and the summarizer
|
||||||
# Summarizer runs Nous map-reduce every 15 min (NEWS_SUMMARIZE_INTERVAL_S=900).
|
# runs the Gemini map-reduce at minute :05, both writing to the shared osint-db
|
||||||
# NOUS_API_KEY is also (preferably) set in the Keys UI; env is an override.
|
# (tables `articles` + `article_summaries`, created by alembic 003_news).
|
||||||
# Unset in both env and api_keys = summarizer logs and idles (never crashes).
|
# Consume via GET /api/news and GET /api/news/summaries.
|
||||||
NOUS_API_KEY=
|
# GEMINI_API_KEY is REQUIRED for summarization; unset = summarizer idles.
|
||||||
NOUS_BASE_URL=https://inference-api.nousresearch.com/v1
|
GEMINI_API_KEY=
|
||||||
# Optional LLM knobs
|
# Optional LLM knobs
|
||||||
# SUMMARY_MODEL is an optional override. Leave unset so Settings
|
SUMMARY_MODEL=gemini-2.0-flash
|
||||||
# (app_settings.SUMMARY_MODEL) can reach the summarizer. Code default
|
|
||||||
# Hermes-4.3-36B remains after a Postgres miss. Env wins when set.
|
|
||||||
# SUMMARY_MODEL=
|
|
||||||
NEWS_BATCH_SIZE=50
|
NEWS_BATCH_SIZE=50
|
||||||
# Map-phase grading: the map model scores each article 0-100, and only blocks
|
SUMMARY_WINDOW_HOURS=1
|
||||||
# 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
|
# Futures/markets coupling from the upstream pipeline is OFF by default
|
||||||
# (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable.
|
# (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable.
|
||||||
INCLUDE_FUTURES=0
|
INCLUDE_FUTURES=0
|
||||||
NEWS_SCRAPE_INTERVAL_S=10
|
# Wall-clock scheduling (k8s CronJob replacement): scrape minute, summarize minute
|
||||||
NEWS_SUMMARIZE_INTERVAL_S=900
|
NEWS_SCRAPE_MINUTE=0
|
||||||
|
NEWS_SUMMARIZE_MINUTE=5
|
||||||
|
# Run once immediately on container start (seeds data fast), then align to the
|
||||||
|
# scheduled minute.
|
||||||
NEWS_SCRAPE_RUN_ON_START=1
|
NEWS_SCRAPE_RUN_ON_START=1
|
||||||
NEWS_SUMMARIZE_RUN_ON_START=1
|
NEWS_SUMMARIZE_RUN_ON_START=1
|
||||||
# "1" ignores the interval idempotency skip (double-pins on recreate).
|
|
||||||
NEWS_SUMMARIZE_FORCE=0
|
|
||||||
NEWS_LOG_LEVEL=INFO
|
NEWS_LOG_LEVEL=INFO
|
||||||
# Reserved for the (out-of-scope) Telegram delivery bot.
|
# Reserved for the (out-of-scope) Telegram delivery bot.
|
||||||
TELEGRAM_TOKEN=
|
TELEGRAM_TOKEN=
|
||||||
|
|
|
||||||
|
|
@ -1,28 +1,17 @@
|
||||||
# Build changed OSINT images and publish them to the Forgejo container
|
# Build all OSINT images, publish to the Forgejo container registry, then
|
||||||
# registry. Deployment is NOT done here: the cluster (homek8s, namespace
|
# redeploy on the Pi runner (docker.sock mounted).
|
||||||
# `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.
|
|
||||||
#
|
|
||||||
# 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.
|
|
||||||
#
|
#
|
||||||
|
# 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):
|
# Images (public names):
|
||||||
# forgejo.siriusdevops.com/sirius/osint-dashboard:amd64-<sha12>
|
# forgejo.siriusdevops.com/sirius/osint-dashboard
|
||||||
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg:amd64-<sha12>
|
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg
|
||||||
# forgejo.siriusdevops.com/sirius/osint-news-scraper:amd64-<sha12>
|
# forgejo.siriusdevops.com/sirius/osint-news-scraper
|
||||||
# forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64-<sha12>
|
# forgejo.siriusdevops.com/sirius/osint-news-summarizer
|
||||||
#
|
#
|
||||||
# Optional repo variable FORGEJO_REGISTRY overrides the *public* pull host.
|
# 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
|
name: build-and-deploy
|
||||||
|
|
||||||
|
|
@ -30,92 +19,23 @@ on:
|
||||||
push:
|
push:
|
||||||
branches: [main, master]
|
branches: [main, master]
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
|
||||||
rebuild_pg:
|
|
||||||
description: Rebuild Timescale+PostGIS (Dockerfile.pg)
|
|
||||||
type: boolean
|
|
||||||
default: false
|
|
||||||
rebuild_all:
|
|
||||||
description: Rebuild every app image (ignore path filter)
|
|
||||||
type: boolean
|
|
||||||
default: false
|
|
||||||
|
|
||||||
env:
|
env:
|
||||||
PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }}
|
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
|
OWNER: sirius
|
||||||
|
# Keep compose project/volumes stable on the Pi
|
||||||
|
COMPOSE_PROJECT_NAME: osint-dashboard
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build-push:
|
build-push-deploy:
|
||||||
# `amd64` only exists on siriussec-amd64, which is also the node the
|
runs-on: docker
|
||||||
# workloads run on — so the images are built on the architecture they are
|
permissions:
|
||||||
# pulled to. `runs-on: docker` matched the Pi's arm64 runner, which
|
contents: read
|
||||||
# produced images the amd64 cluster could never run.
|
packages: write
|
||||||
# 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
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: https://code.forgejo.org/actions/checkout@v4
|
uses: https://code.forgejo.org/actions/checkout@v4
|
||||||
with:
|
|
||||||
fetch-depth: 50
|
|
||||||
|
|
||||||
- name: Plan image builds
|
|
||||||
id: plan
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
APP=0
|
|
||||||
SCRAPER=0
|
|
||||||
SUM=0
|
|
||||||
PG=0
|
|
||||||
|
|
||||||
mark() {
|
|
||||||
case "$1" in
|
|
||||||
Dockerfile.pg)
|
|
||||||
PG=1 ;;
|
|
||||||
Dockerfile|app/*|alembic/*|alembic.ini)
|
|
||||||
APP=1 ;;
|
|
||||||
news/scraper/*)
|
|
||||||
SCRAPER=1 ;;
|
|
||||||
news/summerizer/*)
|
|
||||||
SUM=1 ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|
||||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
|
||||||
APP=1; SCRAPER=1; SUM=1
|
|
||||||
if [ "${{ github.event.inputs.rebuild_all }}" = "true" ]; then
|
|
||||||
APP=1; SCRAPER=1; SUM=1; PG=1
|
|
||||||
fi
|
|
||||||
if [ "${{ github.event.inputs.rebuild_pg }}" = "true" ]; then
|
|
||||||
PG=1
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
BEFORE="${{ github.event.before }}"
|
|
||||||
SHA="${GITHUB_SHA}"
|
|
||||||
ZEROS="0000000000000000000000000000000000000000"
|
|
||||||
if [ -z "$BEFORE" ] || [ "$BEFORE" = "$ZEROS" ]; then
|
|
||||||
echo "No previous SHA — build app images, skip pg"
|
|
||||||
APP=1; SCRAPER=1; SUM=1
|
|
||||||
elif ! git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then
|
|
||||||
echo "Previous SHA $BEFORE not in history — build app images, skip pg"
|
|
||||||
APP=1; SCRAPER=1; SUM=1
|
|
||||||
else
|
|
||||||
while IFS= read -r f; do
|
|
||||||
[ -z "$f" ] && continue
|
|
||||||
mark "$f"
|
|
||||||
done < <(git diff --name-only "$BEFORE" "$SHA")
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
{
|
|
||||||
echo "app=$APP"
|
|
||||||
echo "scraper=$SCRAPER"
|
|
||||||
echo "summarizer=$SUM"
|
|
||||||
echo "pg=$PG"
|
|
||||||
} >> "$GITHUB_OUTPUT"
|
|
||||||
echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG"
|
|
||||||
|
|
||||||
- name: Image refs
|
- name: Image refs
|
||||||
id: img
|
id: img
|
||||||
|
|
@ -125,11 +45,10 @@ jobs:
|
||||||
PUB="${PUBLIC_REGISTRY}"
|
PUB="${PUBLIC_REGISTRY}"
|
||||||
OWN="${OWNER}"
|
OWN="${OWNER}"
|
||||||
SHA="${GITHUB_SHA::12}"
|
SHA="${GITHUB_SHA::12}"
|
||||||
TAG="amd64-${SHA}"
|
|
||||||
{
|
{
|
||||||
echo "reg=$PUSH"
|
echo "reg=$PUSH"
|
||||||
echo "pub=$PUB"
|
echo "pub=$PUB"
|
||||||
echo "tag=$TAG"
|
echo "sha=$SHA"
|
||||||
echo "app=$PUSH/$OWN/osint-dashboard"
|
echo "app=$PUSH/$OWN/osint-dashboard"
|
||||||
echo "pg=$PUSH/$OWN/osint-dashboard-pg"
|
echo "pg=$PUSH/$OWN/osint-dashboard-pg"
|
||||||
echo "scraper=$PUSH/$OWN/osint-news-scraper"
|
echo "scraper=$PUSH/$OWN/osint-news-scraper"
|
||||||
|
|
@ -137,93 +56,103 @@ jobs:
|
||||||
} >> "$GITHUB_OUTPUT"
|
} >> "$GITHUB_OUTPUT"
|
||||||
echo "Push registry: $PUSH"
|
echo "Push registry: $PUSH"
|
||||||
echo "Public pull: $PUB"
|
echo "Public pull: $PUB"
|
||||||
echo "Image tag: $TAG"
|
echo "SHA tag: $SHA"
|
||||||
|
|
||||||
- name: Login to Forgejo registry
|
- 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: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
# GITHUB_TOKEN login "succeeds" but blob uploads 401 (Forgejo packages
|
# GITHUB_TOKEN login "succeeds" but blob uploads 401 (Forgejo packages
|
||||||
# reject the Actions token). Use a user PAT.
|
# reject the Actions token). Use a user PAT with write:package.
|
||||||
# The PAT must carry the `write:package` scope: Forgejo mints a push
|
if [ -z "${{ secrets.FORGEJO_TOKEN }}" ]; then
|
||||||
# token even without it and then rejects every blob upload with
|
echo "Missing repo secret FORGEJO_TOKEN (user PAT, not GITHUB_TOKEN)"
|
||||||
# `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)"
|
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
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
|
-u sirius --password-stdin
|
||||||
|
|
||||||
- name: Build application image (api / ingester / cameras)
|
- name: Build application image (api / ingester / cameras)
|
||||||
if: steps.plan.outputs.app == '1'
|
|
||||||
run: |
|
run: |
|
||||||
set -ex
|
set -ex
|
||||||
IMG="${{ steps.img.outputs.app }}"
|
APP="${{ steps.img.outputs.app }}"
|
||||||
TAG="${{ steps.img.outputs.tag }}"
|
SHA="${{ steps.img.outputs.sha }}"
|
||||||
docker build -f Dockerfile -t "${IMG}:${TAG}" .
|
docker build -f Dockerfile -t "${APP}:latest" -t "${APP}:${SHA}" \
|
||||||
docker push "${IMG}:${TAG}"
|
-t "localhost/osint-dashboard:latest" .
|
||||||
|
docker push "${APP}:latest"
|
||||||
|
docker push "${APP}:${SHA}"
|
||||||
|
|
||||||
- name: Build news-scraper image
|
- name: Build news-scraper image
|
||||||
if: steps.plan.outputs.scraper == '1'
|
|
||||||
run: |
|
run: |
|
||||||
set -ex
|
set -ex
|
||||||
IMG="${{ steps.img.outputs.scraper }}"
|
IMG="${{ steps.img.outputs.scraper }}"
|
||||||
TAG="${{ steps.img.outputs.tag }}"
|
SHA="${{ steps.img.outputs.sha }}"
|
||||||
docker build -f news/scraper/Dockerfile -t "${IMG}:${TAG}" news/scraper
|
docker build -f news/scraper/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \
|
||||||
docker push "${IMG}:${TAG}"
|
-t "localhost/osint-news-scraper:latest" news/scraper
|
||||||
|
docker push "${IMG}:latest"
|
||||||
|
docker push "${IMG}:${SHA}"
|
||||||
|
|
||||||
- name: Build news-summarizer image
|
- name: Build news-summarizer image
|
||||||
if: steps.plan.outputs.summarizer == '1'
|
|
||||||
run: |
|
run: |
|
||||||
set -ex
|
set -ex
|
||||||
IMG="${{ steps.img.outputs.summarizer }}"
|
IMG="${{ steps.img.outputs.summarizer }}"
|
||||||
TAG="${{ steps.img.outputs.tag }}"
|
SHA="${{ steps.img.outputs.sha }}"
|
||||||
docker build -f news/summerizer/Dockerfile -t "${IMG}:${TAG}" news/summerizer
|
docker build -f news/summerizer/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \
|
||||||
docker push "${IMG}:${TAG}"
|
-t "localhost/osint-news-summarizer:latest" news/summerizer
|
||||||
|
docker push "${IMG}:latest"
|
||||||
|
docker push "${IMG}:${SHA}"
|
||||||
|
|
||||||
- name: Build / refresh Timescale+PostGIS image
|
- name: Build / refresh Timescale+PostGIS image
|
||||||
if: steps.plan.outputs.pg == '1'
|
|
||||||
run: |
|
run: |
|
||||||
set -ex
|
set -ex
|
||||||
IMG="${{ steps.img.outputs.pg }}"
|
PG="${{ steps.img.outputs.pg }}"
|
||||||
TAG="${{ steps.img.outputs.tag }}"
|
SHA="${{ steps.img.outputs.sha }}"
|
||||||
docker build -f Dockerfile.pg -t "${IMG}:${TAG}" .
|
# Prefer rebuild so registry always has a current pg image. If packagecloud
|
||||||
docker push "${IMG}:${TAG}"
|
# is unreachable, fall back to whatever local image already exists.
|
||||||
|
if docker build -f Dockerfile.pg -t "${PG}:latest" -t "${PG}:${SHA}" \
|
||||||
|
-t "localhost/osint-dashboard-pg:latest" .; then
|
||||||
|
docker push "${PG}:latest"
|
||||||
|
docker push "${PG}:${SHA}"
|
||||||
|
elif docker image inspect "localhost/osint-dashboard-pg:latest" >/dev/null 2>&1; then
|
||||||
|
echo "WARN: Dockerfile.pg build failed; retagging existing local pg image into registry"
|
||||||
|
docker tag "localhost/osint-dashboard-pg:latest" "${PG}:latest"
|
||||||
|
docker tag "localhost/osint-dashboard-pg:latest" "${PG}:${SHA}"
|
||||||
|
docker push "${PG}:latest"
|
||||||
|
docker push "${PG}:${SHA}"
|
||||||
|
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}"
|
||||||
|
# Pull from Forgejo registry into local tags compose expects, then up.
|
||||||
|
# Compose file still uses localhost/* for stable local names; we mirror
|
||||||
|
# registry tags so a cold host can recover via docker pull.
|
||||||
|
REG="${{ steps.img.outputs.reg }}"
|
||||||
|
PUB="${{ steps.img.outputs.pub }}"
|
||||||
|
OWN="${{ env.OWNER }}"
|
||||||
|
for name in osint-dashboard osint-dashboard-pg osint-news-scraper osint-news-summarizer; do
|
||||||
|
docker pull "${REG}/${OWN}/${name}:latest" || true
|
||||||
|
docker tag "${REG}/${OWN}/${name}:latest" "localhost/${name}:latest" || true
|
||||||
|
docker tag "${REG}/${OWN}/${name}:latest" "${PUB}/${OWN}/${name}:latest" || true
|
||||||
|
done
|
||||||
|
# Do NOT set COMPOSE_PROJECT_NAME differently — volumes must stay
|
||||||
|
# osint-dashboard_osint-pgdata (pinned by `name:` in compose).
|
||||||
|
docker compose build --no-cache app ingester camera-service news-scraper news-summarizer || \
|
||||||
|
docker compose build app ingester camera-service news-scraper news-summarizer
|
||||||
|
docker compose up -d --force-recreate
|
||||||
|
docker image prune -f
|
||||||
|
echo "osint-dashboard deployed; images also on ${PUB}/${OWN}/"
|
||||||
|
|
||||||
- name: Summary
|
- name: Summary
|
||||||
if: always()
|
if: always()
|
||||||
run: |
|
run: |
|
||||||
TAG="${{ steps.img.outputs.tag }}"
|
|
||||||
PUB="${{ steps.img.outputs.pub }}"
|
|
||||||
{
|
{
|
||||||
echo "## Image plan"
|
echo "## Forgejo registry images"
|
||||||
echo "- app: \`${{ steps.plan.outputs.app }}\`"
|
echo "Pushed via ${{ steps.img.outputs.reg }} (loopback). Pull publicly:"
|
||||||
echo "- news-scraper: \`${{ steps.plan.outputs.scraper }}\`"
|
echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-dashboard:latest\`"
|
||||||
echo "- news-summarizer: \`${{ steps.plan.outputs.summarizer }}\`"
|
echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-dashboard-pg:latest\`"
|
||||||
echo "- pg (Timescale): \`${{ steps.plan.outputs.pg }}\`"
|
echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-news-scraper:latest\`"
|
||||||
echo
|
echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-news-summarizer:latest\`"
|
||||||
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)."
|
|
||||||
} >> "$GITHUB_STEP_SUMMARY"
|
} >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
|
||||||
|
|
@ -1,64 +0,0 @@
|
||||||
"""news_items table + article_summaries.model
|
|
||||||
|
|
||||||
Revision ID: 005_news_items
|
|
||||||
Revises: 004_camera_enum
|
|
||||||
Create Date: 2026-08-28
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
# revision identifiers, used by Alembic.
|
|
||||||
revision = "005_news_items"
|
|
||||||
down_revision = "004_camera_enum"
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
# Idempotent DDL: ingest (summarizer ensure_tables) may create the same
|
|
||||||
# shapes first depending on container startup order. IF NOT EXISTS makes
|
|
||||||
# both orders safe — whichever runs first wins, the other no-ops.
|
|
||||||
# One statement per op.execute: asyncpg rejects multi-command prepared
|
|
||||||
# statements (same style as 003_news).
|
|
||||||
op.execute(
|
|
||||||
"""
|
|
||||||
ALTER TABLE article_summaries
|
|
||||||
ADD COLUMN IF NOT EXISTS model TEXT
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
op.execute(
|
|
||||||
"""
|
|
||||||
CREATE TABLE IF NOT EXISTS news_items (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
summary_id INTEGER REFERENCES article_summaries(id) ON DELETE CASCADE,
|
|
||||||
kind TEXT NOT NULL,
|
|
||||||
headline TEXT NOT NULL,
|
|
||||||
importance TEXT NOT NULL,
|
|
||||||
location_name TEXT,
|
|
||||||
lat DOUBLE PRECISION,
|
|
||||||
lon DOUBLE PRECISION,
|
|
||||||
location_confidence TEXT,
|
|
||||||
category TEXT,
|
|
||||||
url TEXT,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
||||||
)
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
op.execute(
|
|
||||||
"""
|
|
||||||
CREATE INDEX IF NOT EXISTS ix_news_items_kind_created
|
|
||||||
ON news_items (kind, created_at DESC)
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
op.execute(
|
|
||||||
"""
|
|
||||||
CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox
|
|
||||||
ON news_items (lon, lat)
|
|
||||||
WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.execute("DROP TABLE IF EXISTS news_items")
|
|
||||||
op.execute("ALTER TABLE article_summaries DROP COLUMN IF EXISTS model")
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
"""merge 005_phase2 and 005_news_items
|
|
||||||
|
|
||||||
Revision ID: 006_merge_heads
|
|
||||||
Revises: 005_phase2, 005_news_items
|
|
||||||
Create Date: 2026-08-28
|
|
||||||
|
|
||||||
Two PRs both parented 004_camera_enum (phase2 geofences + news_items).
|
|
||||||
`alembic upgrade head` then fails and crash-loops the dashboard.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op # noqa: F401
|
|
||||||
|
|
||||||
revision = "006_merge_heads"
|
|
||||||
down_revision = ("005_phase2", "005_news_items")
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
pass
|
|
||||||
|
|
@ -1,115 +0,0 @@
|
||||||
"""event_dedup + Timescale compression/retention
|
|
||||||
|
|
||||||
Revision ID: 007_event_dedup
|
|
||||||
Revises: 006_merge_heads
|
|
||||||
Create Date: 2026-08-28
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
revision = "007_event_dedup"
|
|
||||||
down_revision = "006_merge_heads"
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
op.execute("""
|
|
||||||
CREATE TABLE IF NOT EXISTS event_dedup (
|
|
||||||
url TEXT PRIMARY KEY,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
)
|
|
||||||
""")
|
|
||||||
|
|
||||||
# Keep the earliest row per URL, drop the 10× USGS/camera dupes.
|
|
||||||
op.execute("""
|
|
||||||
DELETE FROM events a
|
|
||||||
USING events b
|
|
||||||
WHERE a.url IS NOT NULL AND a.url <> ''
|
|
||||||
AND a.url = b.url
|
|
||||||
AND (a.ingested_at, a.id) > (b.ingested_at, b.id)
|
|
||||||
""")
|
|
||||||
op.execute("""
|
|
||||||
INSERT INTO event_dedup (url)
|
|
||||||
SELECT DISTINCT url FROM events
|
|
||||||
WHERE url IS NOT NULL AND url <> ''
|
|
||||||
ON CONFLICT (url) DO NOTHING
|
|
||||||
""")
|
|
||||||
|
|
||||||
# Compression + retention. Policies no-op if Timescale rejects (fresh PG).
|
|
||||||
op.execute("""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
PERFORM add_compression_policy('events', INTERVAL '7 days', if_not_exists => TRUE);
|
|
||||||
EXCEPTION WHEN OTHERS THEN
|
|
||||||
BEGIN
|
|
||||||
ALTER TABLE events SET (
|
|
||||||
timescaledb.compress,
|
|
||||||
timescaledb.compress_segmentby = 'source_type',
|
|
||||||
timescaledb.compress_orderby = 'ingested_at DESC'
|
|
||||||
);
|
|
||||||
PERFORM add_compression_policy('events', INTERVAL '7 days', if_not_exists => TRUE);
|
|
||||||
EXCEPTION WHEN OTHERS THEN
|
|
||||||
NULL;
|
|
||||||
END;
|
|
||||||
END
|
|
||||||
$$;
|
|
||||||
""")
|
|
||||||
op.execute("""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
PERFORM add_retention_policy('events', INTERVAL '180 days', if_not_exists => TRUE);
|
|
||||||
EXCEPTION WHEN OTHERS THEN
|
|
||||||
NULL;
|
|
||||||
END
|
|
||||||
$$;
|
|
||||||
""")
|
|
||||||
op.execute("""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
ALTER TABLE fires SET (
|
|
||||||
timescaledb.compress,
|
|
||||||
timescaledb.compress_segmentby = 'satellite',
|
|
||||||
timescaledb.compress_orderby = 'acq_time DESC'
|
|
||||||
);
|
|
||||||
PERFORM add_compression_policy('fires', INTERVAL '7 days', if_not_exists => TRUE);
|
|
||||||
PERFORM add_retention_policy('fires', INTERVAL '90 days', if_not_exists => TRUE);
|
|
||||||
EXCEPTION WHEN OTHERS THEN
|
|
||||||
NULL;
|
|
||||||
END
|
|
||||||
$$;
|
|
||||||
""")
|
|
||||||
op.execute("""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
ALTER TABLE aircraft_positions SET (
|
|
||||||
timescaledb.compress,
|
|
||||||
timescaledb.compress_segmentby = 'hex',
|
|
||||||
timescaledb.compress_orderby = 'ts DESC'
|
|
||||||
);
|
|
||||||
PERFORM add_compression_policy('aircraft_positions', INTERVAL '1 day', if_not_exists => TRUE);
|
|
||||||
PERFORM add_retention_policy('aircraft_positions', INTERVAL '14 days', if_not_exists => TRUE);
|
|
||||||
EXCEPTION WHEN OTHERS THEN
|
|
||||||
NULL;
|
|
||||||
END
|
|
||||||
$$;
|
|
||||||
""")
|
|
||||||
op.execute("""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
ALTER TABLE vessel_positions SET (
|
|
||||||
timescaledb.compress,
|
|
||||||
timescaledb.compress_segmentby = 'mmsi',
|
|
||||||
timescaledb.compress_orderby = 'ts DESC'
|
|
||||||
);
|
|
||||||
PERFORM add_compression_policy('vessel_positions', INTERVAL '1 day', if_not_exists => TRUE);
|
|
||||||
PERFORM add_retention_policy('vessel_positions', INTERVAL '14 days', if_not_exists => TRUE);
|
|
||||||
EXCEPTION WHEN OTHERS THEN
|
|
||||||
NULL;
|
|
||||||
END
|
|
||||||
$$;
|
|
||||||
""")
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.execute("DROP TABLE IF EXISTS event_dedup")
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
"""article_summaries.kind — interval vs daily_recap
|
|
||||||
|
|
||||||
Revision ID: 008_summary_kind
|
|
||||||
Revises: 007_event_dedup
|
|
||||||
Create Date: 2026-08-28
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
revision = "008_summary_kind"
|
|
||||||
down_revision = "007_event_dedup"
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
op.execute(
|
|
||||||
"""
|
|
||||||
ALTER TABLE article_summaries
|
|
||||||
ADD COLUMN IF NOT EXISTS kind TEXT
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.execute("ALTER TABLE article_summaries DROP COLUMN IF EXISTS kind")
|
|
||||||
|
|
@ -1,41 +0,0 @@
|
||||||
"""vessels — daily VesselAPI snapshots for DVR as-of
|
|
||||||
|
|
||||||
Revision ID: 009_vessels
|
|
||||||
Revises: 008_summary_kind
|
|
||||||
Create Date: 2026-08-29
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
revision = "009_vessels"
|
|
||||||
down_revision = "008_summary_kind"
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
op.execute(
|
|
||||||
"""
|
|
||||||
CREATE TABLE IF NOT EXISTS vessels (
|
|
||||||
mmsi TEXT NOT NULL,
|
|
||||||
poll_at TIMESTAMPTZ NOT NULL,
|
|
||||||
lat DOUBLE PRECISION NOT NULL,
|
|
||||||
lon DOUBLE PRECISION NOT NULL,
|
|
||||||
heading DOUBLE PRECISION,
|
|
||||||
speed DOUBLE PRECISION,
|
|
||||||
label TEXT,
|
|
||||||
extra JSONB,
|
|
||||||
PRIMARY KEY (mmsi, poll_at)
|
|
||||||
)
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
op.execute(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_vessels_poll_at ON vessels (poll_at DESC)"
|
|
||||||
)
|
|
||||||
op.execute(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_vessels_bbox ON vessels (lon, lat)"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.execute("DROP TABLE IF EXISTS vessels")
|
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
"""GIST bbox indexes for events/fires map-pan queries.
|
|
||||||
|
|
||||||
Revision ID: 010_bbox_gist
|
|
||||||
Revises: 009_vessels
|
|
||||||
Create Date: 2026-09-01
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
revision = "010_bbox_gist"
|
|
||||||
down_revision = "009_vessels"
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
op.execute(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_events_geom_gist ON events "
|
|
||||||
"USING gist (ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326))"
|
|
||||||
)
|
|
||||||
op.execute(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_fires_geom_gist ON fires "
|
|
||||||
"USING gist (ST_SetSRID(ST_MakePoint(longitude, latitude), 4326))"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.execute("DROP INDEX IF EXISTS ix_fires_geom_gist")
|
|
||||||
op.execute("DROP INDEX IF EXISTS ix_events_geom_gist")
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
"""geofence_alerts (geofence_id, created_at DESC) for fence-scoped hit log
|
|
||||||
|
|
||||||
Revision ID: 011_geofence_alerts_fence
|
|
||||||
Revises: 010_bbox_gist
|
|
||||||
Create Date: 2026-09-01
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
revision = "011_geofence_alerts_fence"
|
|
||||||
down_revision = "010_bbox_gist"
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
op.execute(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_geofence_alerts_fence_created "
|
|
||||||
"ON geofence_alerts (geofence_id, created_at DESC)"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.execute("DROP INDEX IF EXISTS ix_geofence_alerts_fence_created")
|
|
||||||
|
|
@ -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")
|
|
||||||
|
|
@ -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")
|
|
||||||
|
|
@ -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")
|
|
||||||
589
app/auth.py
589
app/auth.py
|
|
@ -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:]))
|
|
||||||
|
|
@ -1,19 +1,50 @@
|
||||||
"""Background ffmpeg — never block a FastAPI request on a frame grab.
|
"""Background masscan / ffmpeg — never block a FastAPI request on a scan.
|
||||||
|
|
||||||
ffmpeg frame grabs are scheduled with asyncio.create_task and shared per URL.
|
masscan is capped at 200 pps (home uplink saturates at 1k+). ffmpeg frame
|
||||||
|
grabs are scheduled with asyncio.create_task and shared per URL.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import logging
|
||||||
import shutil
|
import shutil
|
||||||
from cachetools import TTLCache
|
from cachetools import TTLCache
|
||||||
|
|
||||||
|
logger = logging.getLogger("osint.bg_jobs")
|
||||||
|
|
||||||
|
MASSCAN_PPS_CAP = 200
|
||||||
|
|
||||||
|
_masscan_task: asyncio.Task | None = None
|
||||||
_ffmpeg_cache: TTLCache = TTLCache(maxsize=100, ttl=300)
|
_ffmpeg_cache: TTLCache = TTLCache(maxsize=100, ttl=300)
|
||||||
_ffmpeg_tasks: dict[str, asyncio.Task] = {}
|
_ffmpeg_tasks: dict[str, asyncio.Task] = {}
|
||||||
_FFMPEG = shutil.which("ffmpeg")
|
_FFMPEG = shutil.which("ffmpeg")
|
||||||
|
|
||||||
|
|
||||||
|
def schedule_masscan_pass() -> bool:
|
||||||
|
"""Kick one capped masscan pass. Returns False if a pass is already running."""
|
||||||
|
global _masscan_task
|
||||||
|
if _masscan_task is not None and not _masscan_task.done():
|
||||||
|
return False
|
||||||
|
_masscan_task = asyncio.create_task(_run_masscan_capped())
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def _run_masscan_capped() -> None:
|
||||||
|
import masscan_config as cfg
|
||||||
|
from run_masscan_service import _verify_excludefile, run_pass
|
||||||
|
|
||||||
|
orig = cfg.MASSCAN_RATE
|
||||||
|
if orig > MASSCAN_PPS_CAP:
|
||||||
|
logger.warning("capping masscan rate %s pps -> %s", orig, MASSCAN_PPS_CAP)
|
||||||
|
cfg.MASSCAN_RATE = MASSCAN_PPS_CAP
|
||||||
|
try:
|
||||||
|
_verify_excludefile()
|
||||||
|
await run_pass()
|
||||||
|
finally:
|
||||||
|
cfg.MASSCAN_RATE = orig
|
||||||
|
|
||||||
|
|
||||||
def cached_ffmpeg_jpeg(url: str) -> bytes | None:
|
def cached_ffmpeg_jpeg(url: str) -> bytes | None:
|
||||||
return _ffmpeg_cache.get(url)
|
return _ffmpeg_cache.get(url)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,8 +16,6 @@ CALTRANS_CCTV_URLS = tuple(
|
||||||
f"https://cwwp2.dot.ca.gov/data/d{n}/cctv/cctvStatusD{n:02d}.json"
|
f"https://cwwp2.dot.ca.gov/data/d{n}/cctv/cctvStatusD{n:02d}.json"
|
||||||
for n in range(1, 13)
|
for n in range(1, 13)
|
||||||
)
|
)
|
||||||
# MDOT MiDrive official DOT CCTV list (fields carry rendered HTML).
|
|
||||||
MDOT_CAMERA_URL = "https://mdotjboss.state.mi.us/MiDrive/camera/list"
|
|
||||||
_DEFAULT_SOURCE_URL = ",".join((
|
_DEFAULT_SOURCE_URL = ",".join((
|
||||||
# Publicly published open-camera list (markdown bullets of stream URLs).
|
# Publicly published open-camera list (markdown bullets of stream URLs).
|
||||||
"https://raw.githubusercontent.com/fury999io/public-ip-cams/main/README.md",
|
"https://raw.githubusercontent.com/fury999io/public-ip-cams/main/README.md",
|
||||||
|
|
@ -27,10 +25,6 @@ _DEFAULT_SOURCE_URL = ",".join((
|
||||||
"https://raw.githubusercontent.com/willytop8/Live-Environment-Streams/main/streams.geojson",
|
"https://raw.githubusercontent.com/willytop8/Live-Environment-Streams/main/streams.geojson",
|
||||||
# Official Caltrans CWWP2 JPEG + HLS CCTV (districts 1–12).
|
# Official Caltrans CWWP2 JPEG + HLS CCTV (districts 1–12).
|
||||||
*CALTRANS_CCTV_URLS,
|
*CALTRANS_CCTV_URLS,
|
||||||
# Oregon DOT TripCheck public CCTV JPEG inventory (Esri JSON).
|
|
||||||
"https://www.tripcheck.com/Scripts/map/data/cctvinventory.js",
|
|
||||||
# Official MDOT MiDrive CCTV (JPEG stills, Michigan).
|
|
||||||
MDOT_CAMERA_URL,
|
|
||||||
))
|
))
|
||||||
CAMERA_SOURCE_URLS = [
|
CAMERA_SOURCE_URLS = [
|
||||||
u.strip()
|
u.strip()
|
||||||
|
|
@ -59,18 +53,5 @@ SNAPSHOT_CACHE_DIR = os.getenv("SNAPSHOT_CACHE_DIR", "/data/snapshots")
|
||||||
SNAPSHOT_TTL_SECONDS = int(os.getenv("SNAPSHOT_TTL_SECONDS", "300"))
|
SNAPSHOT_TTL_SECONDS = int(os.getenv("SNAPSHOT_TTL_SECONDS", "300"))
|
||||||
SNAPSHOT_TIMEOUT = float(os.getenv("SNAPSHOT_TIMEOUT", "8.0"))
|
SNAPSHOT_TIMEOUT = float(os.getenv("SNAPSHOT_TIMEOUT", "8.0"))
|
||||||
|
|
||||||
# Retained so an old CAMERA_NATS_SUBJECT env does not surprise operators.
|
# NATS subject cameras are published on (consumed by the shared ingester).
|
||||||
# This service does not publish on it; cameras live in the cameras table.
|
|
||||||
CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera")
|
CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera")
|
||||||
|
|
||||||
|
|
||||||
# ── UDOT IBI 511 traffic cameras ──────────────────────────────────────────
|
|
||||||
# DataTables endpoint (POST form-encoded; server caps at 100 rows/page no
|
|
||||||
# matter what `length` is sent). No API key. Snapshot stills live at a stable
|
|
||||||
# /map/Cctv/{id} URL — same URL always serves the latest frame, so we store
|
|
||||||
# the URL and never scrape every frame ourselves.
|
|
||||||
UDOT_IBI_URL = "https://prod-ut.ibi511.com/List/GetData/Cameras"
|
|
||||||
UDOT_IBI_BASE = "https://prod-ut.ibi511.com"
|
|
||||||
UDOT_IBI_PAGE_SIZE = 100
|
|
||||||
# Safety cap on pages per cycle so a runaway recordsTotal cannot fan out.
|
|
||||||
UDOT_IBI_MAX_PAGES = int(os.getenv("UDOT_IBI_MAX_PAGES", "40"))
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
"""Resolve a browser-renderable preview for a camera.
|
"""Resolve a browser-renderable preview for a camera.
|
||||||
|
|
||||||
HTTP/MJPEG cameras already expose a snapshot_url the existing proxy can
|
HTTP/MJPEG cameras already expose a snapshot_url the existing proxy can
|
||||||
stream. Some scraper sources store `rtsp://` URLs with no snapshot_url, so
|
stream. masscan finds are stored as `rtsp://IP/` with no snapshot_url, so
|
||||||
the map popup used to skip the <img> entirely and the leftover source link
|
the map popup used to skip the <img> entirely and the leftover source link
|
||||||
handed the browser an rtsp:// URL (which opens VLC).
|
handed the browser an rtsp:// URL (which opens VLC).
|
||||||
|
|
||||||
|
|
@ -42,6 +42,16 @@ _HTTP_PATHS = (
|
||||||
"/tmpfs/auto.jpg",
|
"/tmpfs/auto.jpg",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Browser-playable MJPEG paths the /stream proxy can pass through.
|
||||||
|
_MJPEG_PATHS = (
|
||||||
|
"/mjpg/video.mjpg",
|
||||||
|
"/video.mjpg",
|
||||||
|
"/cgi-bin/mjpg/video.cgi",
|
||||||
|
"/axis-cgi/mjpg/video.cgi",
|
||||||
|
"/nphMotionJpeg",
|
||||||
|
"/mjpeg.cgi",
|
||||||
|
)
|
||||||
|
|
||||||
_FFMPEG = shutil.which("ffmpeg")
|
_FFMPEG = shutil.which("ffmpeg")
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -77,6 +87,55 @@ async def _http_get_image(url: str, timeout: float = 2.5) -> bytes | None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def _http_feed_url(url: str, timeout: float = 2.5) -> str | None:
|
||||||
|
"""Return url if it looks like an unauthenticated image/MJPEG feed."""
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(
|
||||||
|
timeout=timeout, follow_redirects=True,
|
||||||
|
headers={"User-Agent": USER_AGENT},
|
||||||
|
) as c:
|
||||||
|
async with c.stream("GET", url) as r:
|
||||||
|
if r.status_code != 200:
|
||||||
|
return None
|
||||||
|
ctype = (r.headers.get("content-type") or "").lower()
|
||||||
|
if "html" in ctype or ctype.startswith("text/"):
|
||||||
|
return None
|
||||||
|
if any(x in ctype for x in ("image/", "multipart", "mjpeg", "octet-stream")):
|
||||||
|
# Read a little to reject empty/error bodies.
|
||||||
|
chunk = b""
|
||||||
|
async for b in r.aiter_bytes():
|
||||||
|
chunk += b
|
||||||
|
if len(chunk) >= 64:
|
||||||
|
break
|
||||||
|
if len(chunk) < 64:
|
||||||
|
return None
|
||||||
|
if b"html" in chunk[:64].lower():
|
||||||
|
return None
|
||||||
|
return url
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def probe_public_feed(host: str) -> str | None:
|
||||||
|
"""Unauthenticated HTTP still or MJPEG URL for this host, or None.
|
||||||
|
|
||||||
|
Used at masscan ingest time so dead RTSP-only hosts never hit the map.
|
||||||
|
No credentials, no RTSP path-walking (too slow / rarely public).
|
||||||
|
"""
|
||||||
|
urls = [f"http://{host}{p}" for p in _HTTP_PATHS]
|
||||||
|
urls.append(f"http://{host}:8080/shot.jpg")
|
||||||
|
urls.extend(f"http://{host}{p}" for p in _MJPEG_PATHS)
|
||||||
|
results = await asyncio.gather(
|
||||||
|
*(_http_feed_url(u) for u in urls),
|
||||||
|
return_exceptions=True,
|
||||||
|
)
|
||||||
|
for url, hit in zip(urls, results):
|
||||||
|
if isinstance(hit, str) and hit:
|
||||||
|
return hit
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
async def ffmpeg_snapshot(url: str, timeout: float = 8.0) -> bytes | None:
|
async def ffmpeg_snapshot(url: str, timeout: float = 8.0) -> bytes | None:
|
||||||
"""Grab a single JPEG frame from an RTSP URL. None if ffmpeg missing/fails.
|
"""Grab a single JPEG frame from an RTSP URL. None if ffmpeg missing/fails.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,8 @@ Pipeline per cycle:
|
||||||
2. Parse cameras (Insecam-style HTML with embedded lat/lon, or plain-text
|
2. Parse cameras (Insecam-style HTML with embedded lat/lon, or plain-text
|
||||||
`url[|lat,lon|vendor|location]` lines).
|
`url[|lat,lon|vendor|location]` lines).
|
||||||
3. Geocode missing coords via Nominatim at <=1 req/s.
|
3. Geocode missing coords via Nominatim at <=1 req/s.
|
||||||
4. Upsert into the `cameras` table keyed by sha256(url_hash).
|
4. Publish each camera to NATS (`events.camera`) for the shared ingester,
|
||||||
Discovery is not published as an event.
|
and upsert into the `cameras` table keyed by sha256(url_hash).
|
||||||
|
|
||||||
Snapshots are cached locally with a TTL; nothing is fetched more often than
|
Snapshots are cached locally with a TTL; nothing is fetched more often than
|
||||||
the cache allows.
|
the cache allows.
|
||||||
|
|
@ -25,7 +25,6 @@ import hashlib
|
||||||
import ipaddress
|
import ipaddress
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import math
|
|
||||||
import re
|
import re
|
||||||
import time
|
import time
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
@ -38,7 +37,6 @@ from camera_config import (
|
||||||
CAMERA_SOURCE_URLS, CAMERA_REQUEST_DELAY, CAMERA_MAX_PER_SOURCE,
|
CAMERA_SOURCE_URLS, CAMERA_REQUEST_DELAY, CAMERA_MAX_PER_SOURCE,
|
||||||
NOMINATIM_URL, NOMINATIM_MIN_INTERVAL, USER_AGENT,
|
NOMINATIM_URL, NOMINATIM_MIN_INTERVAL, USER_AGENT,
|
||||||
SNAPSHOT_CACHE_DIR, SNAPSHOT_TTL_SECONDS, SNAPSHOT_TIMEOUT,
|
SNAPSHOT_CACHE_DIR, SNAPSHOT_TTL_SECONDS, SNAPSHOT_TIMEOUT,
|
||||||
UDOT_IBI_URL, UDOT_IBI_BASE, UDOT_IBI_PAGE_SIZE, UDOT_IBI_MAX_PAGES,
|
|
||||||
)
|
)
|
||||||
from camera_models import cameras
|
from camera_models import cameras
|
||||||
from database import async_session
|
from database import async_session
|
||||||
|
|
@ -116,15 +114,6 @@ class RateLimitedClient:
|
||||||
self._last[host] = time.monotonic()
|
self._last[host] = time.monotonic()
|
||||||
return await self.client.get(url, **kw)
|
return await self.client.get(url, **kw)
|
||||||
|
|
||||||
async def post(self, url: str, **kw) -> httpx.Response:
|
|
||||||
host = urlparse(url).netloc
|
|
||||||
now = time.monotonic()
|
|
||||||
wait = self._last.get(host, 0.0) + self._delay - now
|
|
||||||
if wait > 0:
|
|
||||||
await asyncio.sleep(wait)
|
|
||||||
self._last[host] = time.monotonic()
|
|
||||||
return await self.client.post(url, **kw)
|
|
||||||
|
|
||||||
async def aclose(self):
|
async def aclose(self):
|
||||||
await self.client.aclose()
|
await self.client.aclose()
|
||||||
|
|
||||||
|
|
@ -390,201 +379,6 @@ def parse_caltrans_json(text: str, source_name: str) -> list[dict]:
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
# ── UDOT IBI 511 ──────────────────────────────────────────────────────────
|
|
||||||
# Utah bbox (lat 36.9–42.1, lon -114.2–-108.9). WKT is `POINT (lng lat)`.
|
|
||||||
_UDOT_IBI_MIN_LAT, _UDOT_IBI_MAX_LAT = 36.9, 42.1
|
|
||||||
_UDOT_IBI_MIN_LON, _UDOT_IBI_MAX_LON = -114.2, -108.9
|
|
||||||
_UDOT_WKT_POINT_RE = re.compile(
|
|
||||||
r"POINT\s*\(\s*(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s*\)", re.I,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_udot_ibi_page(text: str, source_name: str = "udot") -> list[dict]:
|
|
||||||
"""Parse one UDOT IBI 511 DataTables camera page (`{"data": [...]}`).
|
|
||||||
|
|
||||||
Skips rows whose first image is `blocked` or `disabled`, and drops any
|
|
||||||
point outside the Utah bbox. The `/map/Cctv/{id}` URL is a stable identity
|
|
||||||
(always serves the latest frame), so it is stored as both source_url and
|
|
||||||
snapshot_url — we never scrape frames ourselves.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
payload = json.loads(text)
|
|
||||||
except (json.JSONDecodeError, ValueError):
|
|
||||||
return []
|
|
||||||
rows = payload.get("data") if isinstance(payload, dict) else None
|
|
||||||
if not isinstance(rows, list):
|
|
||||||
return []
|
|
||||||
out: list[dict] = []
|
|
||||||
for row in rows:
|
|
||||||
if not isinstance(row, dict):
|
|
||||||
continue
|
|
||||||
cam_id = row.get("id")
|
|
||||||
images = row.get("images") or []
|
|
||||||
if cam_id is None or not images:
|
|
||||||
continue
|
|
||||||
img = images[0] or {}
|
|
||||||
if img.get("blocked") or img.get("disabled"):
|
|
||||||
continue
|
|
||||||
lon = lat = None
|
|
||||||
try:
|
|
||||||
wkt = (row.get("latLng") or {}).get("geography") or {}
|
|
||||||
wkt = wkt.get("wellKnownText") or ""
|
|
||||||
m = _UDOT_WKT_POINT_RE.match(str(wkt).strip())
|
|
||||||
if m:
|
|
||||||
lon, lat = float(m.group(1)), float(m.group(2))
|
|
||||||
except (AttributeError, TypeError, ValueError):
|
|
||||||
lon = lat = None
|
|
||||||
if lat is None or lon is None:
|
|
||||||
continue
|
|
||||||
if not (_UDOT_IBI_MIN_LAT <= lat <= _UDOT_IBI_MAX_LAT
|
|
||||||
and _UDOT_IBI_MIN_LON <= lon <= _UDOT_IBI_MAX_LON):
|
|
||||||
continue
|
|
||||||
snap = f"{UDOT_IBI_BASE}/map/Cctv/{cam_id}"
|
|
||||||
roadway, direction, location = (
|
|
||||||
row.get("roadway"), row.get("direction"), row.get("location"),
|
|
||||||
)
|
|
||||||
name = ", ".join(
|
|
||||||
str(b) for b in (roadway, direction, location)
|
|
||||||
if b and str(b).strip() and str(b).strip().lower() != "unknown"
|
|
||||||
) or None
|
|
||||||
out.append({
|
|
||||||
"source_url": snap,
|
|
||||||
"snapshot_url": snap,
|
|
||||||
"discovery_source": source_name,
|
|
||||||
"location_lat": lat,
|
|
||||||
"location_lon": lon,
|
|
||||||
"location_name": name,
|
|
||||||
"vendor": "UDOT",
|
|
||||||
"device_type": "http",
|
|
||||||
"raw": {
|
|
||||||
"udot_id": cam_id,
|
|
||||||
"agency": row.get("source"),
|
|
||||||
"source_id": row.get("sourceId"),
|
|
||||||
"roadway": roadway,
|
|
||||||
"direction": direction,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
# Oregon DOT TripCheck inventory bounding box (approx state extent).
|
|
||||||
ODOT_BBOX = (41.9, 46.3, -124.6, -116.4) # lat_min, lat_max, lon_min, lon_max
|
|
||||||
|
|
||||||
|
|
||||||
def parse_odot_json(text: str, source_name: str) -> list[dict]:
|
|
||||||
"""Parse Oregon DOT TripCheck cctvinventory Esri-style JSON.
|
|
||||||
|
|
||||||
Store the JPEG still as snapshot_url (map thumbs); never RTSP. Keep only
|
|
||||||
rows with finite coordinates inside Oregon and a usable filename.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
payload = json.loads(text)
|
|
||||||
except (json.JSONDecodeError, ValueError):
|
|
||||||
return []
|
|
||||||
lat_min, lat_max, lon_min, lon_max = ODOT_BBOX
|
|
||||||
out: list[dict] = []
|
|
||||||
for feat in payload.get("features") or []:
|
|
||||||
attrs = (feat or {}).get("attributes") or {}
|
|
||||||
filename = (attrs.get("filename") or "").strip()
|
|
||||||
if not filename:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
lat = float(attrs.get("latitude"))
|
|
||||||
lon = float(attrs.get("longitude"))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
continue
|
|
||||||
if not (math.isfinite(lat) and math.isfinite(lon)):
|
|
||||||
continue
|
|
||||||
if not (lat_min <= lat <= lat_max and lon_min <= lon <= lon_max):
|
|
||||||
continue
|
|
||||||
jpeg = f"https://tripcheck.com/RoadCams/cams/{filename}"
|
|
||||||
title = (attrs.get("title") or "").strip()
|
|
||||||
out.append({
|
|
||||||
"source_url": jpeg,
|
|
||||||
"snapshot_url": jpeg,
|
|
||||||
"discovery_source": "odot",
|
|
||||||
"location_lat": lat,
|
|
||||||
"location_lon": lon,
|
|
||||||
"location_name": title or None,
|
|
||||||
"vendor": "ODOT",
|
|
||||||
"device_type": "http",
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
# MDOT MiDrive field extractors (fields carry rendered HTML).
|
|
||||||
_MDOT_LAT_RE = re.compile(r"lat=(-?\d+(?:\.\d+)?)", re.I)
|
|
||||||
_MDOT_LON_RE = re.compile(r"lon=(-?\d+(?:\.\d+)?)", re.I)
|
|
||||||
_MDOT_ID_RE = re.compile(r"[?&]id=(\d+)", re.I)
|
|
||||||
_MDOT_IMG_RE = re.compile(r'<img[^>]+src=["\']([^"\']+)["\']', re.I)
|
|
||||||
|
|
||||||
# Michigan bbox (docs/osiris-ideas.md §3.2): lat 41.6–48.3, lon -90.5–-82.1.
|
|
||||||
MDOT_LAT_RANGE = (41.6, 48.3)
|
|
||||||
MDOT_LON_RANGE = (-90.5, -82.1)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_mdot_json(text: str, source_name: str) -> list[dict]:
|
|
||||||
"""Parse MDOT MiDrive `camera/list` JSON (fields carry rendered HTML).
|
|
||||||
|
|
||||||
Coordinates and the stable id live in the `county` field's map link
|
|
||||||
(`/MiDrive/map?...lat=&lon=&id=`); the `image` field carries an `<img>`
|
|
||||||
whose src is the JPEG still. Out-of-bbox and coord-less rows are dropped.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
payload = json.loads(text)
|
|
||||||
except (json.JSONDecodeError, ValueError):
|
|
||||||
return []
|
|
||||||
if not isinstance(payload, list):
|
|
||||||
return []
|
|
||||||
out: list[dict] = []
|
|
||||||
for row in payload:
|
|
||||||
if not isinstance(row, dict):
|
|
||||||
continue
|
|
||||||
county_html = row.get("county") or ""
|
|
||||||
m_lat = _MDOT_LAT_RE.search(county_html)
|
|
||||||
m_lon = _MDOT_LON_RE.search(county_html)
|
|
||||||
m_id = _MDOT_ID_RE.search(county_html)
|
|
||||||
if not (m_lat and m_lon and m_id):
|
|
||||||
continue # missing coordinates / stable id → drop
|
|
||||||
try:
|
|
||||||
lat = float(m_lat.group(1))
|
|
||||||
lon = float(m_lon.group(1))
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
if not (MDOT_LAT_RANGE[0] <= lat <= MDOT_LAT_RANGE[1]
|
|
||||||
and MDOT_LON_RANGE[0] <= lon <= MDOT_LON_RANGE[1]):
|
|
||||||
continue # out of Michigan bbox → drop
|
|
||||||
img_m = _MDOT_IMG_RE.search(row.get("image") or "")
|
|
||||||
if not img_m:
|
|
||||||
continue
|
|
||||||
snap = img_m.group(1).strip()
|
|
||||||
low = snap.lower()
|
|
||||||
if not (low.startswith("http://") or low.startswith("https://")):
|
|
||||||
continue
|
|
||||||
if low.startswith("rtsp"):
|
|
||||||
continue
|
|
||||||
cam_id = m_id.group(1)
|
|
||||||
route = (row.get("route") or "").strip()
|
|
||||||
loc = (row.get("location") or "").strip().lstrip("@").strip()
|
|
||||||
county_name = county_html.split("<a", 1)[0].strip()
|
|
||||||
bits = [
|
|
||||||
f"{route} @ {loc}" if (route and loc) else (route or loc or None),
|
|
||||||
county_name or None,
|
|
||||||
]
|
|
||||||
name = ", ".join(b for b in bits if b) or None
|
|
||||||
out.append({
|
|
||||||
"source_url": f"https://mdotjboss.state.mi.us/MiDrive/camera/{cam_id}",
|
|
||||||
"snapshot_url": snap,
|
|
||||||
"discovery_source": "mdot",
|
|
||||||
"location_lat": lat,
|
|
||||||
"location_lon": lon,
|
|
||||||
"location_name": name,
|
|
||||||
"vendor": "MDOT",
|
|
||||||
"device_type": "http",
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def parse_live_streams_geojson(text: str, source_name: str) -> list[dict]:
|
def parse_live_streams_geojson(text: str, source_name: str) -> list[dict]:
|
||||||
"""Parse willytop8/Live-Environment-Streams GeoJSON.
|
"""Parse willytop8/Live-Environment-Streams GeoJSON.
|
||||||
|
|
||||||
|
|
@ -696,10 +490,6 @@ async def scrape_source(client: RateLimitedClient, geo: Geocoder,
|
||||||
body = resp.text
|
body = resp.text
|
||||||
if "cwwp2.dot.ca.gov" in src_url or "cctvStatus" in src_url:
|
if "cwwp2.dot.ca.gov" in src_url or "cctvStatus" in src_url:
|
||||||
cams = parse_caltrans_json(body, name)
|
cams = parse_caltrans_json(body, name)
|
||||||
elif "cctvinventory" in src_url or "tripcheck.com" in src_url:
|
|
||||||
cams = parse_odot_json(body, name)
|
|
||||||
elif "mdotjboss.state.mi.us" in src_url or "/MiDrive/camera/list" in src_url:
|
|
||||||
cams = parse_mdot_json(body, name)
|
|
||||||
elif ("getCameraDataByLoc" in src_url
|
elif ("getCameraDataByLoc" in src_url
|
||||||
or ("json" in ctype and '"locs"' in body[:4000] and '"cams"' in body[:8000])):
|
or ("json" in ctype and '"locs"' in body[:4000] and '"cams"' in body[:8000])):
|
||||||
cams = parse_alertwest_json(body, name)
|
cams = parse_alertwest_json(body, name)
|
||||||
|
|
@ -759,54 +549,6 @@ async def scrape_source(client: RateLimitedClient, geo: Geocoder,
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
# ── UDOT IBI 511 paginated fetcher ────────────────────────────────────────
|
|
||||||
|
|
||||||
async def scrape_udot_ibi(client: RateLimitedClient) -> list[dict]:
|
|
||||||
"""Page through the UDOT IBI 511 DataTables endpoint and normalize.
|
|
||||||
|
|
||||||
POSTs `start`/`length` form fields (server caps at 100 rows/page), walking
|
|
||||||
pages until `recordsTotal` is exhausted or UDOT_IBI_MAX_PAGES is hit.
|
|
||||||
"""
|
|
||||||
out: list[dict] = []
|
|
||||||
seen: set[str] = set()
|
|
||||||
start = 0
|
|
||||||
for _ in range(UDOT_IBI_MAX_PAGES):
|
|
||||||
try:
|
|
||||||
resp = await client.post(
|
|
||||||
UDOT_IBI_URL,
|
|
||||||
data={
|
|
||||||
"start": str(start),
|
|
||||||
"length": str(UDOT_IBI_PAGE_SIZE),
|
|
||||||
"lang": "en-US",
|
|
||||||
},
|
|
||||||
headers={"X-Requested-With": "XMLHttpRequest"},
|
|
||||||
)
|
|
||||||
resp.raise_for_status()
|
|
||||||
body = resp.text
|
|
||||||
except Exception: # noqa: BLE001
|
|
||||||
logger.exception("failed to fetch UDOT IBI page start=%d", start)
|
|
||||||
break
|
|
||||||
try:
|
|
||||||
payload = json.loads(body)
|
|
||||||
except ValueError:
|
|
||||||
logger.warning("UDOT IBI non-JSON response at start=%d", start)
|
|
||||||
break
|
|
||||||
total = int(payload.get("recordsTotal") or 0)
|
|
||||||
rows = payload.get("data") or []
|
|
||||||
if not isinstance(rows, list) or not rows:
|
|
||||||
break
|
|
||||||
for cam in parse_udot_ibi_page(body, "udot"):
|
|
||||||
if cam["source_url"] in seen:
|
|
||||||
continue
|
|
||||||
seen.add(cam["source_url"])
|
|
||||||
out.append(cam)
|
|
||||||
if start + len(rows) >= total:
|
|
||||||
break
|
|
||||||
start += len(rows)
|
|
||||||
logger.info("UDOT IBI yielded %d cameras", len(out))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
# ── Persistence ────────────────────────────────────────────────────────────
|
# ── Persistence ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
async def upsert_cameras(cams: list[dict]) -> int:
|
async def upsert_cameras(cams: list[dict]) -> int:
|
||||||
|
|
@ -858,7 +600,6 @@ async def run_cycle() -> int:
|
||||||
try:
|
try:
|
||||||
results = await asyncio.gather(
|
results = await asyncio.gather(
|
||||||
*(scrape_source(client, geo, s) for s in CAMERA_SOURCE_URLS),
|
*(scrape_source(client, geo, s) for s in CAMERA_SOURCE_URLS),
|
||||||
scrape_udot_ibi(client),
|
|
||||||
return_exceptions=True,
|
return_exceptions=True,
|
||||||
)
|
)
|
||||||
all_cams: list[dict] = []
|
all_cams: list[dict] = []
|
||||||
|
|
|
||||||
|
|
@ -1,62 +0,0 @@
|
||||||
"""Static chokepoint preset catalog — one-tap fly-to targets for the map.
|
|
||||||
|
|
||||||
Pure data, no upstream calls and no VesselAPI quota spend. ``vesselapi`` is
|
|
||||||
``True`` only for Hormuz (the single box the VesselAPI poller already covers);
|
|
||||||
every other strait is AISStream-only until a human later spends quota. Never
|
|
||||||
call VesselAPI from here.
|
|
||||||
|
|
||||||
Bounding boxes are ``minlat,minlon,maxlat,maxlon`` (VesselAPI order) and each
|
|
||||||
stays within the ``|dLat|+|dLon| <= 4`` span rule enforced by
|
|
||||||
``vesselapi.validate_bbox_span``.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
# id → preset. ``center`` is ``[lat, lon]`` for Leaflet ``setView``.
|
|
||||||
_CHOKEPOINTS: tuple[dict, ...] = (
|
|
||||||
{
|
|
||||||
"id": "hormuz",
|
|
||||||
"title": "Strait of Hormuz",
|
|
||||||
"bbox": "25.5,55.4,27.3,57.2",
|
|
||||||
"center": [26.4, 56.5],
|
|
||||||
"zoom": 9,
|
|
||||||
"vesselapi": True,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "bab_el_mandeb",
|
|
||||||
"title": "Bab el-Mandeb",
|
|
||||||
"bbox": "12.0,42.8,13.5,44.3",
|
|
||||||
"center": [12.7, 43.4],
|
|
||||||
"zoom": 9,
|
|
||||||
"vesselapi": False,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "suez",
|
|
||||||
"title": "Suez / N. Red Sea",
|
|
||||||
"bbox": "29.5,32.0,31.0,33.5",
|
|
||||||
"center": [30.0,32.5],
|
|
||||||
"zoom": 9,
|
|
||||||
"vesselapi": False,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "malacca",
|
|
||||||
"title": "Malacca / Singapore",
|
|
||||||
"bbox": "1.0,103.0,2.5,104.5",
|
|
||||||
"center": [1.3, 103.8],
|
|
||||||
"zoom": 9,
|
|
||||||
"vesselapi": False,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "taiwan",
|
|
||||||
"title": "Taiwan Strait",
|
|
||||||
"bbox": "23.5,119.0,25.0,120.5",
|
|
||||||
"center": [24.2, 119.8],
|
|
||||||
"zoom": 9,
|
|
||||||
"vesselapi": False,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def chokepoints() -> list[dict]:
|
|
||||||
"""Return a fresh copy of the catalog (callers must not mutate the source)."""
|
|
||||||
return [dict(p) for p in _CHOKEPOINTS]
|
|
||||||
|
|
@ -71,16 +71,6 @@ FIRMS_DATASETS = [d.strip() for d in _FIRMS_DATASETS_RAW.split(",") if d.strip()
|
||||||
OSINT_USER_AGENT = os.getenv(
|
OSINT_USER_AGENT = os.getenv(
|
||||||
"OSINT_USER_AGENT", "osint-dashboard/1.0 (self-hosted; [email protected])"
|
"OSINT_USER_AGENT", "osint-dashboard/1.0 (self-hosted; [email protected])"
|
||||||
)
|
)
|
||||||
# Nominatim reverse (GET /api/place). Camera scraper has its own copy in camera_config.
|
|
||||||
NOMINATIM_URL = os.getenv("NOMINATIM_URL", "https://nominatim.openstreetmap.org")
|
|
||||||
NOMINATIM_MIN_INTERVAL = float(os.getenv("NOMINATIM_MIN_INTERVAL", "1.0"))
|
|
||||||
|
|
||||||
# Self-hosted TiTiler (warps Sentinel-1 signed COGs into XYZ tiles on the Pi).
|
|
||||||
# TITILER_PUBLIC_BASE is the same-origin path prefix the browser hits through
|
|
||||||
# the osint.rpi.local nginx vhost (`location /titiler/` → 127.0.0.1:8001).
|
|
||||||
# TITILER_INTERNAL_URL is the compose-DNS address, used only for health checks.
|
|
||||||
TITILER_PUBLIC_BASE = os.getenv("TITILER_PUBLIC_BASE", "/titiler").rstrip("/")
|
|
||||||
TITILER_INTERNAL_URL = os.getenv("TITILER_INTERNAL_URL", "http://titiler:8000")
|
|
||||||
|
|
||||||
# AISStream (server-side WebSocket only). Idle when unset.
|
# AISStream (server-side WebSocket only). Idle when unset.
|
||||||
AISSTREAM_API_KEY = os.getenv("AISSTREAM_API_KEY", "")
|
AISSTREAM_API_KEY = os.getenv("AISSTREAM_API_KEY", "")
|
||||||
|
|
@ -91,28 +81,3 @@ AISSTREAM_BBOX = os.getenv("AISSTREAM_BBOX", "24,-125,50,-66")
|
||||||
# without the ingest profile). Set 0 if the ingester owns the only connection.
|
# without the ingest profile). Set 0 if the ingester owns the only connection.
|
||||||
AISSTREAM_IN_APP = os.getenv("AISSTREAM_IN_APP", "1").lower() in ("1", "true", "yes")
|
AISSTREAM_IN_APP = os.getenv("AISSTREAM_IN_APP", "1").lower() in ("1", "true", "yes")
|
||||||
AISSTREAM_IN_INGEST = os.getenv("AISSTREAM_IN_INGEST", "0").lower() in ("1", "true", "yes")
|
AISSTREAM_IN_INGEST = os.getenv("AISSTREAM_IN_INGEST", "0").lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
# VesselAPI (quota-capped REST AIS poller — free tier 150 calls/mo).
|
|
||||||
# AISStream keeps US coasts; VesselAPI fills the Middle East blind spot. The
|
|
||||||
# poller idles when VESSELAPI_API_KEY is unset (never from GET /api/vessels).
|
|
||||||
VESSELAPI_API_KEY = os.getenv("VESSELAPI_API_KEY", "")
|
|
||||||
# Bounding box(es) as minlat,minlon,maxlat,maxlon — note lat/lon order (same as
|
|
||||||
# AISSTREAM_BBOX). Semicolon-separated for multiple boxes. Default: Strait of
|
|
||||||
# Hormuz (|dLat|+|dLon| = 3.6 ≤ 4° span cap). VesselAPI 400s any box over 4°.
|
|
||||||
VESSELAPI_BBOX = os.getenv("VESSELAPI_BBOX", "25.5,55.4,27.3,57.2")
|
|
||||||
# Poll cadence in seconds. 17280 = 4.8h → 5 polls/day (150/mo free tier).
|
|
||||||
VESSELAPI_INTERVAL = int(os.getenv("VESSELAPI_INTERVAL", "17280"))
|
|
||||||
# Local hard cap on successful 2xx calls per UTC day (persisted in Postgres).
|
|
||||||
VESSELAPI_MAX_CALLS_PER_DAY = int(os.getenv("VESSELAPI_MAX_CALLS_PER_DAY", "5"))
|
|
||||||
# Run the VesselAPI poller inside the dashboard process (default on, like AIS).
|
|
||||||
VESSELAPI_IN_APP = os.getenv("VESSELAPI_IN_APP", "1").lower() in ("1", "true", "yes")
|
|
||||||
VESSELAPI_IN_INGEST = os.getenv("VESSELAPI_IN_INGEST", "0").lower() in ("1", "true", "yes")
|
|
||||||
|
|
||||||
# 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"))
|
|
||||||
|
|
|
||||||
168
app/conflicts.py
168
app/conflicts.py
|
|
@ -1,168 +0,0 @@
|
||||||
"""Curated OSINT conflict-zone catalog + point-in-bbox event counting.
|
|
||||||
|
|
||||||
A static, human-curated list of active conflict theatres (war / high /
|
|
||||||
elevated). Purely descriptive — this is a catalog, not a live feed and not a
|
|
||||||
scrape of LiveUAMap or any other source. Severity and descriptions are
|
|
||||||
editorial judgement kept short and factual.
|
|
||||||
|
|
||||||
Each zone carries an internal ``bbox`` (``min_lat, min_lon, max_lat, max_lon``)
|
|
||||||
used only to count pre-existing geocoded news/GDELT/``/api/news/map`` rows that
|
|
||||||
fall inside it. The bbox is not part of the API response; callers get the
|
|
||||||
``eventCount`` roll-up instead.
|
|
||||||
|
|
||||||
Never call an upstream API from here — event counts come from rows already in
|
|
||||||
the local database (``events`` with geocoords + ``news_items`` map pins).
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
# id → zone. ``lat``/``lon`` is the fly-to anchor; ``bbox`` is the internal
|
|
||||||
# count window in ``min_lat, min_lon, max_lat, max_lon`` order.
|
|
||||||
_ZONES: tuple[dict, ...] = (
|
|
||||||
{
|
|
||||||
"id": "ukraine",
|
|
||||||
"label": "Ukraine",
|
|
||||||
"severity": "war",
|
|
||||||
"lat": 48.5,
|
|
||||||
"lon": 31.0,
|
|
||||||
"description": "Full-scale Russian invasion since 2022; active front lines in the east and south.",
|
|
||||||
"bbox": (44.3, 22.1, 52.4, 40.2),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "gaza",
|
|
||||||
"label": "Gaza",
|
|
||||||
"severity": "war",
|
|
||||||
"lat": 31.4,
|
|
||||||
"lon": 34.4,
|
|
||||||
"description": "Israel–Hamas war; sustained fighting and a severe humanitarian crisis in the Gaza Strip.",
|
|
||||||
"bbox": (31.0, 34.1, 31.8, 34.7),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "sudan",
|
|
||||||
"label": "Sudan",
|
|
||||||
"severity": "war",
|
|
||||||
"lat": 15.5,
|
|
||||||
"lon": 30.0,
|
|
||||||
"description": "Civil war between the SAF and RSF since 2023, with mass displacement across the country.",
|
|
||||||
"bbox": (8.7, 21.8, 22.0, 38.6),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "myanmar",
|
|
||||||
"label": "Myanmar",
|
|
||||||
"severity": "war",
|
|
||||||
"lat": 21.5,
|
|
||||||
"lon": 96.0,
|
|
||||||
"description": "Post-2021 coup conflict pitting the junta against resistance and ethnic armed groups.",
|
|
||||||
"bbox": (9.5, 92.2, 28.5, 101.2),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "drc",
|
|
||||||
"label": "DR Congo",
|
|
||||||
"severity": "war",
|
|
||||||
"lat": -1.5,
|
|
||||||
"lon": 28.0,
|
|
||||||
"description": "Eastern DRC conflict involving M23 and other armed groups; heavy displacement around Goma.",
|
|
||||||
"bbox": (-5.0, 26.0, 3.0, 31.0),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "yemen",
|
|
||||||
"label": "Yemen",
|
|
||||||
"severity": "war",
|
|
||||||
"lat": 15.5,
|
|
||||||
"lon": 47.5,
|
|
||||||
"description": "Protracted Houthi–government/coalition war with one of the world's worst humanitarian emergencies.",
|
|
||||||
"bbox": (12.6, 42.5, 19.0, 54.0),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "syria",
|
|
||||||
"label": "Syria",
|
|
||||||
"severity": "war",
|
|
||||||
"lat": 34.5,
|
|
||||||
"lon": 38.5,
|
|
||||||
"description": "Multi-sided civil war; government, opposition, and external actors continue to engage.",
|
|
||||||
"bbox": (32.3, 35.7, 37.3, 42.4),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "lebanon",
|
|
||||||
"label": "Lebanon",
|
|
||||||
"severity": "high",
|
|
||||||
"lat": 33.9,
|
|
||||||
"lon": 35.9,
|
|
||||||
"description": "Israel–Hezbollah hostilities with periodic escalation along the southern border.",
|
|
||||||
"bbox": (33.0, 35.0, 34.7, 36.6),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "sahel",
|
|
||||||
"label": "Sahel",
|
|
||||||
"severity": "high",
|
|
||||||
"lat": 14.5,
|
|
||||||
"lon": 0.0,
|
|
||||||
"description": "Jihadist insurgencies across Mali, Burkina Faso, and Niger destabilising the central Sahel.",
|
|
||||||
"bbox": (10.0, -10.0, 20.0, 12.0),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "somalia",
|
|
||||||
"label": "Somalia",
|
|
||||||
"severity": "high",
|
|
||||||
"lat": 6.0,
|
|
||||||
"lon": 45.0,
|
|
||||||
"description": "Al-Shabaab insurgency against the federal government and security forces.",
|
|
||||||
"bbox": (-2.0, 41.0, 12.0, 51.5),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "red_sea",
|
|
||||||
"label": "Red Sea",
|
|
||||||
"severity": "high",
|
|
||||||
"lat": 18.0,
|
|
||||||
"lon": 40.0,
|
|
||||||
"description": "Houthi attacks on commercial shipping transiting the Red Sea corridor.",
|
|
||||||
"bbox": (12.0, 34.0, 22.0, 44.0),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "taiwan_strait",
|
|
||||||
"label": "Taiwan Strait",
|
|
||||||
"severity": "elevated",
|
|
||||||
"lat": 24.5,
|
|
||||||
"lon": 119.5,
|
|
||||||
"description": "Heightened military standoff between China and Taiwan, including deterrence patrols.",
|
|
||||||
"bbox": (21.9, 117.0, 26.5, 122.0),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"id": "korean_dmz",
|
|
||||||
"label": "Korean DMZ",
|
|
||||||
"severity": "elevated",
|
|
||||||
"lat": 38.3,
|
|
||||||
"lon": 127.0,
|
|
||||||
"description": "Heavily fortified inter-Korean border with periodic tensions and military drills.",
|
|
||||||
"bbox": (37.5, 126.0, 39.0, 128.5),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
SEVERITIES: frozenset[str] = frozenset({"war", "high", "elevated"})
|
|
||||||
|
|
||||||
|
|
||||||
def conflict_zones() -> list[dict]:
|
|
||||||
"""Return a fresh shallow copy of the catalog (callers must not mutate)."""
|
|
||||||
return [dict(z) for z in _ZONES]
|
|
||||||
|
|
||||||
|
|
||||||
def zone_event_stats(
|
|
||||||
points: list[tuple[float, float, datetime | None]],
|
|
||||||
bbox: tuple[float, float, float, float],
|
|
||||||
) -> tuple[int, datetime | None]:
|
|
||||||
"""Count points inside ``bbox`` and return (count, latest timestamp).
|
|
||||||
|
|
||||||
``points`` is an iterable of ``(lat, lon, ts)``; ``ts`` may be ``None``.
|
|
||||||
``bbox`` is ``(min_lat, min_lon, max_lat, max_lon)``.
|
|
||||||
"""
|
|
||||||
min_lat, min_lon, max_lat, max_lon = bbox
|
|
||||||
count = 0
|
|
||||||
latest: datetime | None = None
|
|
||||||
for lat, lon, ts in points:
|
|
||||||
if min_lat <= lat <= max_lat and min_lon <= lon <= max_lon:
|
|
||||||
count += 1
|
|
||||||
if ts is not None and (latest is None or ts > latest):
|
|
||||||
latest = ts
|
|
||||||
return count, latest
|
|
||||||
|
|
@ -4,9 +4,7 @@ set -e
|
||||||
|
|
||||||
cd /app
|
cd /app
|
||||||
echo "[entrypoint] running migrations..."
|
echo "[entrypoint] running migrations..."
|
||||||
# `heads` (plural): parallel PRs can fork the chain (005_phase2 + 005_news_items).
|
alembic upgrade head
|
||||||
# `upgrade head` then exits 255 and crash-loops the container.
|
|
||||||
alembic upgrade heads
|
|
||||||
|
|
||||||
echo "[entrypoint] starting uvicorn..."
|
echo "[entrypoint] starting uvicorn..."
|
||||||
exec uvicorn app.main:app --host 0.0.0.0 --port 8000
|
exec uvicorn app.main:app --host 0.0.0.0 --port 8000
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,6 @@ UTC date (YYYY-MM-DD).
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import csv
|
import csv
|
||||||
import hashlib
|
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
|
@ -45,11 +44,6 @@ from upstream_cache import firms_cache
|
||||||
|
|
||||||
logger = logging.getLogger("osint.firms")
|
logger = logging.getLogger("osint.firms")
|
||||||
|
|
||||||
# In-process poll state: skip byte-identical CSVs, persist only new hotspots.
|
|
||||||
# Survives the 15-minute loop; one full ON CONFLICT after process start.
|
|
||||||
_csv_digest: dict[tuple, bytes] = {}
|
|
||||||
_seen_ids: dict[tuple, set[int]] = {}
|
|
||||||
|
|
||||||
# ── FIRMS API ─────────────────────────────────────────────────────────────
|
# ── FIRMS API ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
FIRMS_AREA_CSV = (
|
FIRMS_AREA_CSV = (
|
||||||
|
|
@ -92,34 +86,33 @@ def normalize_acq_time(acq_date: object, acq_time: object) -> datetime | None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _hotspot_id(lat: float, lon: float, acq_iso: str, satellite: str) -> int:
|
def parse_firms_csv(text: str) -> list[dict]:
|
||||||
return hash((round(lat, 5), round(lon, 5), acq_iso, satellite))
|
"""Parse a FIRMS area CSV payload into normalized fire messages.
|
||||||
|
|
||||||
|
Returns one dict per hotspot with the fields stored in the ``fires`` table
|
||||||
def parse_firms_csv_delta(
|
(acq_time already combined into a UTC ISO timestamp). Rows that don't look
|
||||||
text: str, skip_ids: set[int] | None = None,
|
like valid VIIRS detections are skipped rather than failing the whole poll.
|
||||||
) -> tuple[list[dict], set[int]]:
|
|
||||||
"""Parse FIRMS CSV; optionally drop hotspots already seen this process.
|
|
||||||
|
|
||||||
Returns (new_or_all_points, ids_for_every_valid_row). Streaming — does not
|
|
||||||
materialize the raw CSV as a list of lists.
|
|
||||||
"""
|
"""
|
||||||
reader = csv.reader(io.StringIO(text))
|
rows = list(csv.reader(io.StringIO(text)))
|
||||||
header = None
|
if not rows:
|
||||||
for row in reader:
|
return []
|
||||||
|
|
||||||
|
# Locate the real header row. FIRMS normally returns the CSV header first,
|
||||||
|
# but occasionally prepends a legend/info line, so scan until we see the
|
||||||
|
# canonical header.
|
||||||
|
header_idx = 0
|
||||||
|
for i, row in enumerate(rows):
|
||||||
if row and row[0].strip().lower() == "latitude" and len(row) >= 4:
|
if row and row[0].strip().lower() == "latitude" and len(row) >= 4:
|
||||||
header = [c.strip().lower() for c in row]
|
header_idx = i
|
||||||
break
|
break
|
||||||
if not header or "latitude" not in header or "longitude" not in header:
|
header = [c.strip().lower() for c in rows[header_idx]]
|
||||||
logger.warning(
|
# Guard against a header that isn't actually the FIRMS one.
|
||||||
"FIRMS payload does not look like a hotspot CSV (first row: %r)",
|
if "latitude" not in header or "longitude" not in header:
|
||||||
(header or [])[:6],
|
logger.warning("FIRMS payload does not look like a hotspot CSV (first row: %r)", header[:6])
|
||||||
)
|
return []
|
||||||
return [], set()
|
|
||||||
|
|
||||||
points: list[dict] = []
|
points: list[dict] = []
|
||||||
ids: set[int] = set()
|
for row in rows[header_idx + 1:]:
|
||||||
for row in reader:
|
|
||||||
if len(row) < len(header):
|
if len(row) < len(header):
|
||||||
continue
|
continue
|
||||||
rec = dict(zip(header, row))
|
rec = dict(zip(header, row))
|
||||||
|
|
@ -130,19 +123,13 @@ def parse_firms_csv_delta(
|
||||||
acq_time = normalize_acq_time(rec.get("acq_date"), rec.get("acq_time"))
|
acq_time = normalize_acq_time(rec.get("acq_date"), rec.get("acq_time"))
|
||||||
if acq_time is None:
|
if acq_time is None:
|
||||||
continue
|
continue
|
||||||
sat = str(rec.get("satellite") or "").strip()
|
|
||||||
acq_iso = acq_time.isoformat()
|
|
||||||
hid = _hotspot_id(lat, lon, acq_iso, sat)
|
|
||||||
ids.add(hid)
|
|
||||||
if skip_ids is not None and hid in skip_ids:
|
|
||||||
continue
|
|
||||||
points.append({
|
points.append({
|
||||||
"latitude": lat,
|
"latitude": lat,
|
||||||
"longitude": lon,
|
"longitude": lon,
|
||||||
"brightness": _to_float(rec.get("bright_ti4")),
|
"brightness": _to_float(rec.get("bright_ti4")),
|
||||||
"confidence": str(rec.get("confidence") or "").strip(),
|
"confidence": str(rec.get("confidence") or "").strip(),
|
||||||
"acq_time": acq_iso,
|
"acq_time": acq_time.isoformat(),
|
||||||
"satellite": sat,
|
"satellite": str(rec.get("satellite") or "").strip(),
|
||||||
"instrument": str(rec.get("instrument") or "").strip(),
|
"instrument": str(rec.get("instrument") or "").strip(),
|
||||||
"bright_ti5": _to_float(rec.get("bright_ti5")),
|
"bright_ti5": _to_float(rec.get("bright_ti5")),
|
||||||
"frp": _to_float(rec.get("frp")),
|
"frp": _to_float(rec.get("frp")),
|
||||||
|
|
@ -151,17 +138,6 @@ def parse_firms_csv_delta(
|
||||||
"track": _to_float(rec.get("track")),
|
"track": _to_float(rec.get("track")),
|
||||||
"version": str(rec.get("version") or "").strip(),
|
"version": str(rec.get("version") or "").strip(),
|
||||||
})
|
})
|
||||||
return points, ids
|
|
||||||
|
|
||||||
|
|
||||||
def parse_firms_csv(text: str) -> list[dict]:
|
|
||||||
"""Parse a FIRMS area CSV payload into normalized fire messages.
|
|
||||||
|
|
||||||
Returns one dict per hotspot with the fields stored in the ``fires`` table
|
|
||||||
(acq_time already combined into a UTC ISO timestamp). Rows that don't look
|
|
||||||
like valid VIIRS detections are skipped rather than failing the whole poll.
|
|
||||||
"""
|
|
||||||
points, _ids = parse_firms_csv_delta(text)
|
|
||||||
return points
|
return points
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -186,16 +162,6 @@ async def publish_fire_batch(points: list[dict]) -> int:
|
||||||
return len(points)
|
return len(points)
|
||||||
|
|
||||||
|
|
||||||
async def persist_hotspots(points: list[dict]) -> int:
|
|
||||||
"""Write a FIRMS poll to Postgres in one ON CONFLICT batch.
|
|
||||||
|
|
||||||
NATS-per-row was 93k commits + geofence/correlation per hotspot.
|
|
||||||
"""
|
|
||||||
from ingestor import ingest_fire_rows
|
|
||||||
|
|
||||||
return await ingest_fire_rows(points)
|
|
||||||
|
|
||||||
|
|
||||||
async def ingest_fires(bbox: str | None = None) -> int:
|
async def ingest_fires(bbox: str | None = None) -> int:
|
||||||
"""Fetch the FIRMS hotspot CSV for an area and publish it to NATS.
|
"""Fetch the FIRMS hotspot CSV for an area and publish it to NATS.
|
||||||
|
|
||||||
|
|
@ -239,18 +205,11 @@ async def ingest_fires(bbox: str | None = None) -> int:
|
||||||
dataset, first_line,
|
dataset, first_line,
|
||||||
)
|
)
|
||||||
continue
|
continue
|
||||||
poll_key = (dataset, area, FIRMS_DAYS)
|
points = parse_firms_csv(text)
|
||||||
digest = hashlib.sha256(text.encode("utf-8", "surrogatepass")).digest()
|
published = await publish_fire_batch(points)
|
||||||
if _csv_digest.get(poll_key) == digest:
|
|
||||||
logger.info("FIRMS %s CSV unchanged, skip parse/insert", dataset)
|
|
||||||
continue
|
|
||||||
points, ids = parse_firms_csv_delta(text, skip_ids=_seen_ids.get(poll_key))
|
|
||||||
published = await persist_hotspots(points) if points else 0
|
|
||||||
_csv_digest[poll_key] = digest
|
|
||||||
_seen_ids[poll_key] = ids
|
|
||||||
total_published += published
|
total_published += published
|
||||||
logger.info(
|
logger.info(
|
||||||
"FIRMS: fetched %d hotspot(s) for bbox=%s (%s), published %d",
|
"FIRMS: fetched %d hotspot(s) for bbox=%s (%s), published %d",
|
||||||
len(ids), area, dataset, published,
|
len(points), area, dataset, published,
|
||||||
)
|
)
|
||||||
return total_published
|
return total_published
|
||||||
|
|
|
||||||
527
app/geofence.py
527
app/geofence.py
|
|
@ -7,7 +7,6 @@ in ``geofence_alerts`` and fan out as WS type ``geofence_alert``.
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
@ -16,19 +15,6 @@ from sqlalchemy import text
|
||||||
|
|
||||||
from database import async_session
|
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]]]:
|
def _rings_from_geojson(geojson: dict) -> list[list[list[float]]]:
|
||||||
if not isinstance(geojson, dict):
|
if not isinstance(geojson, dict):
|
||||||
|
|
@ -113,160 +99,6 @@ _recent_hits: dict[tuple[str, str], datetime] = {}
|
||||||
_HIT_COOLDOWN = timedelta(minutes=5)
|
_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]:
|
async def refresh_cache() -> list[dict]:
|
||||||
global _cache
|
global _cache
|
||||||
async with async_session() as session:
|
async with async_session() as session:
|
||||||
|
|
@ -417,24 +249,12 @@ async def record_and_notify(
|
||||||
lat: float,
|
lat: float,
|
||||||
lon: float,
|
lon: float,
|
||||||
payload: dict[str, Any] | None = None,
|
payload: dict[str, Any] | None = None,
|
||||||
skip_existing: bool = False,
|
|
||||||
) -> int:
|
) -> int:
|
||||||
"""Insert a geofence_alerts row per hit and WS-push to viewport clients.
|
"""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
|
PostGIS ST_Intersects is the source of truth. The in-process GeoJSON
|
||||||
cache is not a reject filter — the FIRMS ingester never fills it.
|
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)
|
hits = await st_intersects(lon, lat)
|
||||||
if not hits:
|
if not hits:
|
||||||
return 0
|
return 0
|
||||||
|
|
@ -455,33 +275,6 @@ async def record_and_notify(
|
||||||
hits = fresh
|
hits = fresh
|
||||||
async with async_session() as session:
|
async with async_session() as session:
|
||||||
for fence in hits:
|
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())
|
aid = str(uuid4())
|
||||||
body = {
|
body = {
|
||||||
"id": aid,
|
"id": aid,
|
||||||
|
|
@ -491,7 +284,7 @@ async def record_and_notify(
|
||||||
"entity_id": str(entity_id),
|
"entity_id": str(entity_id),
|
||||||
"lat": lat,
|
"lat": lat,
|
||||||
"lon": lon,
|
"lon": lon,
|
||||||
"payload": body_payload,
|
"payload": payload or {},
|
||||||
"created_at": now.isoformat(),
|
"created_at": now.isoformat(),
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
|
|
@ -513,7 +306,7 @@ async def record_and_notify(
|
||||||
"entity_id": str(entity_id),
|
"entity_id": str(entity_id),
|
||||||
"lat": lat,
|
"lat": lat,
|
||||||
"lon": lon,
|
"lon": lon,
|
||||||
"payload": json.dumps(body_payload),
|
"payload": json.dumps(payload or {}),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|
@ -521,324 +314,8 @@ async def record_and_notify(
|
||||||
sent += await manager.publish_point(
|
sent += await manager.publish_point(
|
||||||
"geofence_alert", body, lat=lat, lon=lon,
|
"geofence_alert", body, lat=lat, lon=lon,
|
||||||
)
|
)
|
||||||
if skip_existing:
|
|
||||||
_notified_once.add(once_key)
|
|
||||||
try:
|
try:
|
||||||
await session.commit()
|
await session.commit()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return sent
|
return sent
|
||||||
|
|
||||||
|
|
||||||
async def list_alerts(
|
|
||||||
*,
|
|
||||||
geofence_id: str | None = None,
|
|
||||||
since: datetime | None = None,
|
|
||||||
until: datetime | None = None,
|
|
||||||
source_kind: str | None = None,
|
|
||||||
limit: int = 100,
|
|
||||||
) -> list[dict]:
|
|
||||||
"""Filterable hit log. Empty list if the DB is down — never raises."""
|
|
||||||
where = ["TRUE"]
|
|
||||||
params: dict[str, Any] = {"limit": int(limit)}
|
|
||||||
if geofence_id:
|
|
||||||
where.append("geofence_id = CAST(:geofence_id AS uuid)")
|
|
||||||
params["geofence_id"] = geofence_id
|
|
||||||
if since is not None:
|
|
||||||
where.append("created_at >= :since")
|
|
||||||
params["since"] = since
|
|
||||||
if until is not None:
|
|
||||||
where.append("created_at <= :until")
|
|
||||||
params["until"] = until
|
|
||||||
if source_kind:
|
|
||||||
where.append("source_kind = :source_kind")
|
|
||||||
params["source_kind"] = source_kind
|
|
||||||
sql = f"""
|
|
||||||
SELECT id::text, geofence_id::text, source_kind, entity_id,
|
|
||||||
lat, lon, payload, created_at
|
|
||||||
FROM geofence_alerts
|
|
||||||
WHERE {' AND '.join(where)}
|
|
||||||
ORDER BY created_at DESC
|
|
||||||
LIMIT :limit
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
async with async_session() as session:
|
|
||||||
rows = (await session.execute(text(sql), params)).mappings().all()
|
|
||||||
out = []
|
|
||||||
for r in rows:
|
|
||||||
item = dict(r)
|
|
||||||
if item.get("created_at") is not None:
|
|
||||||
item["created_at"] = item["created_at"].isoformat()
|
|
||||||
out.append(item)
|
|
||||||
return out
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
async def get_geofence(gid: str) -> dict | None:
|
|
||||||
current = next((f for f in _cache if f["id"] == gid), None)
|
|
||||||
if current is not None:
|
|
||||||
return current
|
|
||||||
try:
|
|
||||||
await refresh_cache()
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
return next((f for f in _cache if f["id"] == gid), None)
|
|
||||||
|
|
||||||
|
|
||||||
def _marker_from_track(row) -> dict:
|
|
||||||
from live_layers import to_marker
|
|
||||||
|
|
||||||
extra = {"bucket": row["bucket"].isoformat() if row.get("bucket") else None, "dvr": True}
|
|
||||||
return to_marker(
|
|
||||||
row["id"], row["lat"], row["lon"],
|
|
||||||
heading=row.get("heading"), speed=row.get("speed"),
|
|
||||||
label=row.get("label") or row["id"],
|
|
||||||
extra=extra,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def _cagg_inside(gid: str, kind: str, bucket: datetime, limit: int = 2000) -> list[dict]:
|
|
||||||
table = "aircraft_tracks_1min" if kind == "aircraft" else "vessel_tracks_1min"
|
|
||||||
id_col = "hex" if kind == "aircraft" else "mmsi"
|
|
||||||
sql = f"""
|
|
||||||
SELECT {id_col} AS id, lat, lon, heading, speed, label, bucket
|
|
||||||
FROM {table}
|
|
||||||
WHERE bucket = :bucket
|
|
||||||
AND ST_Intersects(
|
|
||||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
|
||||||
ST_SetSRID(ST_MakePoint(lon, lat), 4326)
|
|
||||||
)
|
|
||||||
LIMIT :limit
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
async with async_session() as session:
|
|
||||||
rows = (await session.execute(
|
|
||||||
text(sql), {"bucket": bucket, "gid": gid, "limit": limit},
|
|
||||||
)).mappings().all()
|
|
||||||
return [
|
|
||||||
_marker_from_track(r)
|
|
||||||
for r in rows
|
|
||||||
if r["lat"] is not None and r["lon"] is not None
|
|
||||||
]
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
async def _fires_inside(gid: str, ts: datetime, limit: int = 2000) -> list[dict]:
|
|
||||||
from tracks import minute_bucket
|
|
||||||
|
|
||||||
bucket = minute_bucket(ts)
|
|
||||||
t1 = bucket + timedelta(minutes=1)
|
|
||||||
sql = """
|
|
||||||
SELECT latitude, longitude, brightness, confidence, acq_time, satellite,
|
|
||||||
instrument, bright_ti5, frp, daynight
|
|
||||||
FROM fires
|
|
||||||
WHERE acq_time >= :t0 AND acq_time < :t1
|
|
||||||
AND ST_Intersects(
|
|
||||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
|
||||||
ST_SetSRID(ST_MakePoint(longitude, latitude), 4326)
|
|
||||||
)
|
|
||||||
LIMIT :limit
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
async with async_session() as session:
|
|
||||||
rows = (await session.execute(
|
|
||||||
text(sql),
|
|
||||||
{"t0": bucket, "t1": t1, "gid": gid, "limit": limit},
|
|
||||||
)).mappings().all()
|
|
||||||
out = []
|
|
||||||
for r in rows:
|
|
||||||
item = dict(r)
|
|
||||||
if item.get("acq_time") is not None:
|
|
||||||
item["acq_time"] = item["acq_time"].isoformat()
|
|
||||||
out.append(item)
|
|
||||||
return out
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
async def snapshot_at(gid: str, ts: datetime) -> dict | None:
|
|
||||||
"""Positions inside the fence at time T. None if the fence is missing.
|
|
||||||
|
|
||||||
Does not persist or notify. Empty lists if track/fire queries fail.
|
|
||||||
"""
|
|
||||||
fence = await get_geofence(gid)
|
|
||||||
if fence is None:
|
|
||||||
return None
|
|
||||||
from tracks import minute_bucket
|
|
||||||
|
|
||||||
bucket = minute_bucket(ts)
|
|
||||||
aircraft = await _cagg_inside(gid, "aircraft", bucket)
|
|
||||||
vessels = await _cagg_inside(gid, "vessel", bucket)
|
|
||||||
fires = await _fires_inside(gid, ts)
|
|
||||||
return {
|
|
||||||
"geofence_id": gid,
|
|
||||||
"timestamp": ts.isoformat(),
|
|
||||||
"aircraft": aircraft,
|
|
||||||
"vessels": vessels,
|
|
||||||
"fires": fires,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
_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
|
|
||||||
|
|
|
||||||
|
|
@ -14,17 +14,10 @@ from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||||
from database import async_session
|
from database import async_session
|
||||||
from models import events as events_table
|
from models import events as events_table
|
||||||
from models import fires as fires_table
|
from models import fires as fires_table
|
||||||
from models import event_dedup as event_dedup_table
|
|
||||||
from config import NATS_URL
|
from config import NATS_URL
|
||||||
from sources import event_dedup_key
|
|
||||||
|
|
||||||
logger = logging.getLogger("osint.ingestor")
|
logger = logging.getLogger("osint.ingestor")
|
||||||
|
|
||||||
# asyncpg rejects statements with >32767 bind params. A FIRMS poll is ~90k
|
|
||||||
# rows × 14 columns. Chunk inserts; still one transaction / one commit.
|
|
||||||
FIRE_ROW_BIND_PARAMS = 14
|
|
||||||
FIRE_INSERT_CHUNK = 2000
|
|
||||||
|
|
||||||
# NATS connection settings
|
# NATS connection settings
|
||||||
NATS_URLS = NATS_URL
|
NATS_URLS = NATS_URL
|
||||||
NATS_STREAM = "events"
|
NATS_STREAM = "events"
|
||||||
|
|
@ -122,45 +115,6 @@ async def ingest_fire_row(msg: dict) -> bool:
|
||||||
return inserted
|
return inserted
|
||||||
|
|
||||||
|
|
||||||
async def ingest_fire_rows(msgs: list[dict]) -> int:
|
|
||||||
"""Bulk-insert FIRMS hotspots: one INSERT, one ON CONFLICT, one commit."""
|
|
||||||
rows = []
|
|
||||||
for msg in msgs:
|
|
||||||
row = _fire_row_from_msg(msg)
|
|
||||||
if row is not None:
|
|
||||||
rows.append(row)
|
|
||||||
if not rows:
|
|
||||||
return 0
|
|
||||||
inserted = 0
|
|
||||||
async with async_session() as session:
|
|
||||||
for i in range(0, len(rows), FIRE_INSERT_CHUNK):
|
|
||||||
chunk = rows[i:i + FIRE_INSERT_CHUNK]
|
|
||||||
stmt = (
|
|
||||||
pg_insert(fires_table)
|
|
||||||
.values(chunk)
|
|
||||||
.on_conflict_do_nothing(constraint="pk_fires_natural_key")
|
|
||||||
)
|
|
||||||
result = await session.execute(stmt)
|
|
||||||
inserted += int(result.rowcount or 0)
|
|
||||||
await session.commit()
|
|
||||||
if inserted:
|
|
||||||
logger.info("bulk ingested %d/%d FIRMS hotspots", inserted, len(rows))
|
|
||||||
from live_layers import aircraft_last_known
|
|
||||||
from fire_aircraft import correlate_and_notify
|
|
||||||
from tracks import recent_markers
|
|
||||||
acs = list(aircraft_last_known.values()) or await recent_markers("aircraft")
|
|
||||||
if acs:
|
|
||||||
fires = [
|
|
||||||
{
|
|
||||||
"id": f"firms:{r['latitude']:.4f},{r['longitude']:.4f}",
|
|
||||||
"lat": r["latitude"], "lon": r["longitude"], "label": "FIRMS",
|
|
||||||
}
|
|
||||||
for r in rows[:500]
|
|
||||||
]
|
|
||||||
await correlate_and_notify(fires, acs)
|
|
||||||
return inserted
|
|
||||||
|
|
||||||
|
|
||||||
async def ingest_event(msg: dict):
|
async def ingest_event(msg: dict):
|
||||||
"""Ingest a single event from NATS into PostgreSQL."""
|
"""Ingest a single event from NATS into PostgreSQL."""
|
||||||
# Active fire/hotspot messages carry a dedicated schema and land in the
|
# Active fire/hotspot messages carry a dedicated schema and land in the
|
||||||
|
|
@ -195,56 +149,17 @@ async def ingest_event(msg: dict):
|
||||||
}
|
}
|
||||||
|
|
||||||
# Parse timestamp if string
|
# Parse timestamp if string
|
||||||
ts = event_row["source_timestamp"]
|
if isinstance(event_row["source_timestamp"], str):
|
||||||
if isinstance(ts, str):
|
event_row["source_timestamp"] = datetime.fromisoformat(event_row["source_timestamp"])
|
||||||
ts = datetime.fromisoformat(ts.replace("Z", "+00:00"))
|
|
||||||
if isinstance(ts, datetime) and ts.tzinfo is None:
|
|
||||||
ts = ts.replace(tzinfo=timezone.utc)
|
|
||||||
event_row["source_timestamp"] = ts
|
|
||||||
|
|
||||||
key = event_dedup_key(event_row)
|
|
||||||
async with async_session() as session:
|
async with async_session() as session:
|
||||||
if key:
|
|
||||||
dedup = (
|
|
||||||
pg_insert(event_dedup_table)
|
|
||||||
.values(url=key)
|
|
||||||
.on_conflict_do_nothing(index_elements=["url"])
|
|
||||||
)
|
|
||||||
claimed = await session.execute(dedup)
|
|
||||||
if not claimed.rowcount:
|
|
||||||
await session.commit()
|
|
||||||
logger.debug("skip duplicate event url=%s", key)
|
|
||||||
return None
|
|
||||||
result = await session.execute(events_table.insert().values(**event_row))
|
result = await session.execute(events_table.insert().values(**event_row))
|
||||||
await session.commit()
|
await session.commit()
|
||||||
event_id = result.inserted_primary_key[0] # type: ignore[union-attr]
|
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"))
|
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
|
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():
|
async def start_nats_consumer():
|
||||||
"""Start NATS JetStream consumer for OSINT events."""
|
"""Start NATS JetStream consumer for OSINT events."""
|
||||||
nc = await nats.connect(NATS_URLS)
|
nc = await nats.connect(NATS_URLS)
|
||||||
|
|
|
||||||
|
|
@ -57,10 +57,10 @@ KEY_REGISTRY: dict[str, dict] = {
|
||||||
"pattern": r"^[0-9a-fA-F]{32}$",
|
"pattern": r"^[0-9a-fA-F]{32}$",
|
||||||
"example": "32-char hex string (e.g. 5f3c…9a02)",
|
"example": "32-char hex string (e.g. 5f3c…9a02)",
|
||||||
},
|
},
|
||||||
"NOUS_API_KEY": {
|
"GEMINI_API_KEY": {
|
||||||
"description": "Nous Portal API key — 15-min news summarizer (inference-api.nousresearch.com).",
|
"description": "Google Gemini API key — LLM event analysis / summarization.",
|
||||||
"pattern": r"^.{16,}$",
|
"pattern": r"^AIza[0-9A-Za-z_-]{35}$",
|
||||||
"example": "key from https://portal.nousresearch.com (API keys page)",
|
"example": "AIza… (Google API key, 39 chars)",
|
||||||
},
|
},
|
||||||
"TELEGRAM_TOKEN": {
|
"TELEGRAM_TOKEN": {
|
||||||
"description": "Telegram bot token — push alert notifications to a channel.",
|
"description": "Telegram bot token — push alert notifications to a channel.",
|
||||||
|
|
@ -68,15 +68,10 @@ KEY_REGISTRY: dict[str, dict] = {
|
||||||
"example": "123456789:AA… (bot token from @BotFather)",
|
"example": "123456789:AA… (bot token from @BotFather)",
|
||||||
},
|
},
|
||||||
"AISSTREAM_API_KEY": {
|
"AISSTREAM_API_KEY": {
|
||||||
"description": "AISStream (open/shared) — live US-coast AIS. Server-side WebSocket only.",
|
"description": "AISStream WebSocket key — live vessel positions (server-side only).",
|
||||||
"pattern": r"^.{8,}$",
|
"pattern": r"^.{8,}$",
|
||||||
"example": "key from https://aisstream.io/account (GitHub login)",
|
"example": "key from https://aisstream.io/account (GitHub login)",
|
||||||
},
|
},
|
||||||
"VESSELAPI_API_KEY": {
|
|
||||||
"description": "VesselAPI (commercial) — Strait of Hormuz AIS, 5×/day cache. Paste the Bearer token from dashboard.vesselapi.com. Not a US-coast feed.",
|
|
||||||
"pattern": r"^.{8,}$",
|
|
||||||
"example": "Bearer token from https://dashboard.vesselapi.com/",
|
|
||||||
},
|
|
||||||
"OPENSKY_CLIENT_ID": {
|
"OPENSKY_CLIENT_ID": {
|
||||||
"description": "OpenSky OAuth client id — optional ADS-B fallback (unused until enabled).",
|
"description": "OpenSky OAuth client id — optional ADS-B fallback (unused until enabled).",
|
||||||
"example": "client id from opensky-network.org account",
|
"example": "client id from opensky-network.org account",
|
||||||
|
|
@ -219,7 +214,7 @@ async def get_api_key(name: str) -> str | None:
|
||||||
"""Read a stored key value — used by ingest services, never by the API.
|
"""Read a stored key value — used by ingest services, never by the API.
|
||||||
|
|
||||||
Returns the raw value (or None when unset) so producers can pass it to
|
Returns the raw value (or None when unset) so producers can pass it to
|
||||||
external APIs (FIRMS, Nous, Telegram, …). Reads live from Postgres, so a
|
external APIs (FIRMS, Gemini, Telegram, …). Reads live from Postgres, so a
|
||||||
key set via the dashboard is picked up on the next poll — no restart.
|
key set via the dashboard is picked up on the next poll — no restart.
|
||||||
"""
|
"""
|
||||||
await ensure_api_keys_table()
|
await ensure_api_keys_table()
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
944
app/main.py
944
app/main.py
File diff suppressed because it is too large
Load diff
65
app/masscan_config.py
Normal file
65
app/masscan_config.py
Normal file
|
|
@ -0,0 +1,65 @@
|
||||||
|
"""Active camera-discovery configuration (masscan-based, env-driven).
|
||||||
|
|
||||||
|
All knobs read from the environment with safe defaults. The scanner targets
|
||||||
|
open TCP port 554 (RTSP — the typical IP-camera port) across a configured
|
||||||
|
range and feeds results into the same `cameras` table as the passive scraper
|
||||||
|
(discovery_source='masscan'), deduped by URL hash.
|
||||||
|
|
||||||
|
ETHICS / SCOPE (mirrors camera_scraper.py):
|
||||||
|
* Detection only — a SYN port scan for OPEN hosts. No credential guessing,
|
||||||
|
no login attempts, no banner grabbing, and no access to camera feeds.
|
||||||
|
* Private / reserved ranges are excluded via MASSCAN_EXCLUDEFILE so the
|
||||||
|
scanner never probes RFC1918, loopback, link-local, multicast, or the
|
||||||
|
bogons. Fail closed if the excludefile is missing.
|
||||||
|
|
||||||
|
TIMING REALITY: at the residential-safe default of 200 pps a full IPv4
|
||||||
|
sweep (0.0.0.0/0, ~4.29B addresses) takes ~8 months. This is therefore a
|
||||||
|
CONTINUOUS ROLLING SWEEP, not a "finish in a day" job: masscan streams
|
||||||
|
open hosts to stdout and the runner ingests them incrementally, then
|
||||||
|
restarts the sweep when a pass completes. New cameras are detected as they
|
||||||
|
appear on each pass. 1k/10k pps saturated a home uplink — do not raise the
|
||||||
|
rate unless you are on a VPS / unmetered link.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
# Path to the masscan binary (installed on the Pi host).
|
||||||
|
MASSCAN_BIN = os.getenv("MASSCAN_BIN", "masscan")
|
||||||
|
|
||||||
|
# CIDR(s) to sweep. Default = the whole public IPv4 space.
|
||||||
|
MASSCAN_RANGE = os.getenv("MASSCAN_RANGE", "0.0.0.0/0")
|
||||||
|
|
||||||
|
# Port(s) to probe. Default 554 = RTSP, the typical IP-camera port.
|
||||||
|
MASSCAN_PORTS = os.getenv("MASSCAN_PORTS", "554")
|
||||||
|
|
||||||
|
# Packets/sec. 200 is the residential-safe default — 1k/10k pps saturated
|
||||||
|
# a home uplink. Raise only on a VPS / unmetered link.
|
||||||
|
MASSCAN_RATE = int(os.getenv("MASSCAN_RATE", "200"))
|
||||||
|
|
||||||
|
# Retransmission count. 1 maximizes unique-host coverage at low rate; the
|
||||||
|
# default (10) spends most of the budget re-probing the same hosts.
|
||||||
|
MASSCAN_RETRIES = int(os.getenv("MASSCAN_RETRIES", "1"))
|
||||||
|
|
||||||
|
# Seconds to keep listening for straggler responses after the last probe.
|
||||||
|
# 0 avoids a 10s tail per pass; tiny loss of the very last hosts is fine
|
||||||
|
# since the sweep repeats.
|
||||||
|
MASSCAN_WAIT = int(os.getenv("MASSCAN_WAIT", "0"))
|
||||||
|
|
||||||
|
# Excludefile path on the Pi host. Must contain RFC1918/loopback/link-local/
|
||||||
|
# multicast/bogons so the scanner never probes private ranges. Fail closed if
|
||||||
|
# the file is absent (the runner refuses to start rather than scan wide).
|
||||||
|
MASSCAN_EXCLUDEFILE = os.getenv(
|
||||||
|
"MASSCAN_EXCLUDEFILE", "/etc/osint-dashboard/masscan-excludes.txt"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Ingest batch size — flush this many newly-seen hosts to the DB per round.
|
||||||
|
MASSCAN_FLUSH_EVERY = int(os.getenv("MASSCAN_FLUSH_EVERY", "250"))
|
||||||
|
|
||||||
|
# NATS subject newly-found cameras are published on (same feed as the
|
||||||
|
# passive scraper so the shared ingester persists them).
|
||||||
|
MASSCAN_NATS_SUBJECT = os.getenv("MASSCAN_NATS_SUBJECT", "events.camera")
|
||||||
|
|
||||||
|
# discovery_source tag written into the cameras table.
|
||||||
|
MASSCAN_DISCOVERY_SOURCE = os.getenv("MASSCAN_DISCOVERY_SOURCE", "masscan")
|
||||||
226
app/masscan_scanner.py
Normal file
226
app/masscan_scanner.py
Normal file
|
|
@ -0,0 +1,226 @@
|
||||||
|
"""masscan result parsing + ingestion for the OSINT dashboard.
|
||||||
|
|
||||||
|
Turns a stream of masscan JSON-lines (open port 554 hosts) into rows in the
|
||||||
|
`cameras` table with discovery_source='masscan', deduped by URL hash against
|
||||||
|
whatever the passive scraper already found. Newly discovered hosts are also
|
||||||
|
published to NATS (`events.camera`) so the shared ingester pipeline persists
|
||||||
|
them exactly like scraper finds.
|
||||||
|
|
||||||
|
Scope: detection of OPEN hosts only. No credentials, no banners, no feed
|
||||||
|
access. Private/reserved ranges never enter masscan (see excludefile).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from camera_models import cameras
|
||||||
|
from camera_scraper import url_hash, geolocate_ips
|
||||||
|
from database import async_session
|
||||||
|
|
||||||
|
from masscan_config import (
|
||||||
|
MASSCAN_NATS_SUBJECT, MASSCAN_DISCOVERY_SOURCE,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("osint.masscan_scanner")
|
||||||
|
|
||||||
|
|
||||||
|
# ── URL building ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def build_rtsp_url(ip: str) -> str:
|
||||||
|
"""Canonical URL for an open-RTSP host. Used as the dedupe key."""
|
||||||
|
return f"rtsp://{ip}/"
|
||||||
|
|
||||||
|
|
||||||
|
# ── masscan JSON parsing ──────────────────────────────────────────────────
|
||||||
|
# masscan --output-format=json --output-file=- emits line-delimited JSON on a
|
||||||
|
# pipe (a bare object per open host), not the array form used for seekable
|
||||||
|
# files. We parse per-line and tolerate an accidental leading '['.
|
||||||
|
|
||||||
|
def parse_masscan_line(line: str) -> list[dict]:
|
||||||
|
"""Parse one masscan stdout line into a list of host records.
|
||||||
|
|
||||||
|
A line may contain one JSON object or, defensively, be wrapped in an
|
||||||
|
array. Returns [] on anything unparseable (harmless — the sweep repeats).
|
||||||
|
"""
|
||||||
|
s = line.strip()
|
||||||
|
if not s:
|
||||||
|
return []
|
||||||
|
s = s.lstrip("[").rstrip("]").strip()
|
||||||
|
if not s:
|
||||||
|
return []
|
||||||
|
# Multiple records may share a line separated by '},{'.
|
||||||
|
if s.endswith(","):
|
||||||
|
s = s[:-1].rstrip()
|
||||||
|
out: list[dict] = []
|
||||||
|
for cand in _split_records(s):
|
||||||
|
try:
|
||||||
|
obj = json.loads(cand)
|
||||||
|
except (json.JSONDecodeError, ValueError):
|
||||||
|
continue
|
||||||
|
if isinstance(obj, dict) and obj.get("ip"):
|
||||||
|
out.append(obj)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _split_records(s: str) -> list[str]:
|
||||||
|
"""Split a buffer into individual JSON object strings, honoring nesting."""
|
||||||
|
records, depth, start = [], 0, 0
|
||||||
|
for i, ch in enumerate(s):
|
||||||
|
if ch == "{":
|
||||||
|
if depth == 0:
|
||||||
|
start = i
|
||||||
|
depth += 1
|
||||||
|
elif ch == "}":
|
||||||
|
depth -= 1
|
||||||
|
if depth == 0:
|
||||||
|
records.append(s[start:i + 1])
|
||||||
|
return records
|
||||||
|
|
||||||
|
|
||||||
|
def extract_open_ips(records: list[dict], port: int) -> list[str]:
|
||||||
|
"""Return the list of IPs from records that have `port` open."""
|
||||||
|
ips: list[str] = []
|
||||||
|
for rec in records:
|
||||||
|
for p in rec.get("ports", []):
|
||||||
|
if p.get("port") == port and p.get("status") == "open":
|
||||||
|
ips.append(rec["ip"])
|
||||||
|
break
|
||||||
|
return ips
|
||||||
|
|
||||||
|
|
||||||
|
# ── Persistence ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def ingest_open_hosts(ips: list[str]) -> tuple[int, list[str]]:
|
||||||
|
"""Insert-or-refresh camera rows for open RTSP hosts that have a public feed.
|
||||||
|
|
||||||
|
A host only lands in the table (and therefore on the map) if an
|
||||||
|
unauthenticated HTTP still or MJPEG URL responds. Port-554-only hosts
|
||||||
|
are skipped. Returns (newly_inserted, hosts_with_working_feed).
|
||||||
|
"""
|
||||||
|
if not ips:
|
||||||
|
return 0, []
|
||||||
|
from camera_preview import probe_public_feed
|
||||||
|
|
||||||
|
unique = list(dict.fromkeys(ips))
|
||||||
|
sem = asyncio.Semaphore(20)
|
||||||
|
|
||||||
|
async def _probe(ip: str) -> tuple[str, str | None]:
|
||||||
|
async with sem:
|
||||||
|
return ip, await probe_public_feed(ip)
|
||||||
|
|
||||||
|
probed = await asyncio.gather(*(_probe(ip) for ip in unique))
|
||||||
|
live = [(ip, feed) for ip, feed in probed if feed]
|
||||||
|
if not live:
|
||||||
|
logger.info("masscan ingest: 0 working feeds of %d open-554 hosts",
|
||||||
|
len(unique))
|
||||||
|
return 0, []
|
||||||
|
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
coords = await geolocate_ips([ip for ip, _ in live])
|
||||||
|
new = 0
|
||||||
|
async with async_session() as session:
|
||||||
|
for ip, feed in live:
|
||||||
|
url = build_rtsp_url(ip)
|
||||||
|
h = url_hash(url)
|
||||||
|
lat, lon = coords.get(ip, (None, None))
|
||||||
|
existing = (await session.execute(
|
||||||
|
cameras.select().where(cameras.c.url_hash == h)
|
||||||
|
)).one_or_none()
|
||||||
|
if existing is None:
|
||||||
|
await session.execute(cameras.insert().values(
|
||||||
|
url_hash=h,
|
||||||
|
source_url=url,
|
||||||
|
snapshot_url=feed,
|
||||||
|
discovery_source=MASSCAN_DISCOVERY_SOURCE,
|
||||||
|
location_lat=lat,
|
||||||
|
location_lon=lon,
|
||||||
|
location_name=f"{ip} (IP-geo)" if lat is not None else None,
|
||||||
|
vendor=None,
|
||||||
|
device_type="rtsp",
|
||||||
|
first_seen=now,
|
||||||
|
last_seen=now,
|
||||||
|
raw={"discovered_via": "masscan", "port": 554,
|
||||||
|
"public_feed": feed},
|
||||||
|
))
|
||||||
|
new += 1
|
||||||
|
else:
|
||||||
|
await session.execute(cameras.update().where(
|
||||||
|
cameras.c.url_hash == h
|
||||||
|
).values(
|
||||||
|
last_seen=now,
|
||||||
|
snapshot_url=feed,
|
||||||
|
location_lat=lat,
|
||||||
|
location_lon=lon,
|
||||||
|
location_name=f"{ip} (IP-geo)" if lat is not None else None,
|
||||||
|
))
|
||||||
|
await session.commit()
|
||||||
|
logger.info("masscan ingest: %d new working feeds (%d probed, %d open-554)",
|
||||||
|
new, len(live), len(unique))
|
||||||
|
return new, [ip for ip, _ in live]
|
||||||
|
|
||||||
|
|
||||||
|
# ── NATS publish ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def publish_new_hosts(ips: list[str]) -> int:
|
||||||
|
"""Publish newly-found open hosts to NATS for the shared ingester.
|
||||||
|
|
||||||
|
Returns the number of messages published (0 if NATS is down).
|
||||||
|
"""
|
||||||
|
import json as _json
|
||||||
|
import nats
|
||||||
|
from config import NATS_URL
|
||||||
|
|
||||||
|
if not ips:
|
||||||
|
return 0
|
||||||
|
try:
|
||||||
|
nc = await nats.connect(NATS_URL)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.warning("NATS unavailable — skipping publish pass")
|
||||||
|
return 0
|
||||||
|
published = 0
|
||||||
|
try:
|
||||||
|
js = nc.jetstream()
|
||||||
|
for ip in dict.fromkeys(ips):
|
||||||
|
url = build_rtsp_url(ip)
|
||||||
|
msg = {
|
||||||
|
"source_type": "camera",
|
||||||
|
"title": f"Open RTSP camera ({ip})",
|
||||||
|
"url": url,
|
||||||
|
"location_lat": None,
|
||||||
|
"location_lon": None,
|
||||||
|
"location_name": None,
|
||||||
|
"tags": ["osint", "camera", MASSCAN_DISCOVERY_SOURCE],
|
||||||
|
"raw": {
|
||||||
|
"url_hash": url_hash(url),
|
||||||
|
"source_url": url,
|
||||||
|
"snapshot_url": None,
|
||||||
|
"vendor": None,
|
||||||
|
"device_type": "rtsp",
|
||||||
|
"discovered_via": "masscan",
|
||||||
|
"port": 554,
|
||||||
|
},
|
||||||
|
"source_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||||
|
}
|
||||||
|
await js.publish(MASSCAN_NATS_SUBJECT, _json.dumps(msg).encode())
|
||||||
|
published += 1
|
||||||
|
finally:
|
||||||
|
await nc.close()
|
||||||
|
logger.info("published %d masscan finds to %s", published, MASSCAN_NATS_SUBJECT)
|
||||||
|
return published
|
||||||
|
|
||||||
|
|
||||||
|
# ── Batch drain helper used by the runner ─────────────────────────────────
|
||||||
|
|
||||||
|
async def flush(seen: set[str], new_accum: int) -> tuple[int, int]:
|
||||||
|
"""Ingest + publish the accumulated host set; return (new, published)."""
|
||||||
|
if not seen:
|
||||||
|
return 0, 0
|
||||||
|
ips = list(seen)
|
||||||
|
new, live = await ingest_open_hosts(ips)
|
||||||
|
published = await publish_new_hosts(live)
|
||||||
|
seen.clear()
|
||||||
|
return new, published
|
||||||
|
|
@ -4,7 +4,7 @@ from datetime import datetime, timezone
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from sqlalchemy import (
|
from sqlalchemy import (
|
||||||
Boolean, Column, Enum, Float, Index, Integer, String, Text,
|
Column, Enum, Float, Index, Integer, String, Text,
|
||||||
DateTime, JSON, func, Table, PrimaryKeyConstraint,
|
DateTime, JSON, func, Table, PrimaryKeyConstraint,
|
||||||
)
|
)
|
||||||
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
|
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
|
||||||
|
|
@ -68,15 +68,6 @@ Index("ix_events_search_vector", events.c.search_vector, postgresql_using="gin")
|
||||||
# Spatial index on location
|
# Spatial index on location
|
||||||
Index("ix_events_location", events.c.location_lat, events.c.location_lon)
|
Index("ix_events_location", events.c.location_lat, events.c.location_lon)
|
||||||
|
|
||||||
# Timescale unique indexes must include the partition column, so URL
|
|
||||||
# idempotency lives on a regular table — not the events hypertable.
|
|
||||||
event_dedup = Table(
|
|
||||||
"event_dedup",
|
|
||||||
metadata,
|
|
||||||
Column("url", Text, primary_key=True),
|
|
||||||
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ── Entities (people, organizations, locations of interest) ──────────────
|
# ── Entities (people, organizations, locations of interest) ──────────────
|
||||||
|
|
||||||
|
|
@ -194,8 +185,8 @@ Index("ix_fires_bbox", fires.c.longitude, fires.c.latitude)
|
||||||
|
|
||||||
|
|
||||||
# ── News pipeline (scraper + summarizer) ──────────────────────────────────
|
# ── News pipeline (scraper + summarizer) ──────────────────────────────────
|
||||||
# Written by the vendored news-scraper (Scrapy) / news-summarizer services;
|
# Written by the vendored news-scraper (Scrapy) / news-summarizer (Gemini)
|
||||||
# schema must match the idempotent alembic migrations 003_news + 005_news_items.
|
# services; schema must match the idempotent alembic migration 003_news.
|
||||||
|
|
||||||
articles = Table(
|
articles = Table(
|
||||||
"articles",
|
"articles",
|
||||||
|
|
@ -218,58 +209,6 @@ article_summaries = Table(
|
||||||
Column("summary_text", Text, nullable=False),
|
Column("summary_text", Text, nullable=False),
|
||||||
Column("batch_timestamp", DateTime(timezone=True),
|
Column("batch_timestamp", DateTime(timezone=True),
|
||||||
server_default=func.now(), nullable=False),
|
server_default=func.now(), nullable=False),
|
||||||
Column("model", Text), # LLM id used for this batch; nullable for old rows
|
|
||||||
Column("kind", Text), # interval | daily_recap; nullable for old rows
|
|
||||||
)
|
)
|
||||||
|
|
||||||
Index("ix_article_summaries_batch_timestamp", article_summaries.c.batch_timestamp)
|
Index("ix_article_summaries_batch_timestamp", article_summaries.c.batch_timestamp)
|
||||||
|
|
||||||
|
|
||||||
news_items = Table(
|
|
||||||
"news_items",
|
|
||||||
metadata,
|
|
||||||
Column("id", Integer, primary_key=True, autoincrement=True),
|
|
||||||
Column("summary_id", Integer),
|
|
||||||
Column("kind", Text, nullable=False),
|
|
||||||
Column("headline", Text, nullable=False),
|
|
||||||
Column("importance", Text, nullable=False),
|
|
||||||
Column("location_name", Text),
|
|
||||||
Column("lat", Float),
|
|
||||||
Column("lon", Float),
|
|
||||||
Column("location_confidence", Text),
|
|
||||||
Column("category", Text),
|
|
||||||
Column("url", Text),
|
|
||||||
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
|
|
||||||
)
|
|
||||||
Index("ix_news_items_kind_created", news_items.c.kind, news_items.c.created_at)
|
|
||||||
|
|
||||||
|
|
||||||
# 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),
|
|
||||||
)
|
|
||||||
|
|
|
||||||
|
|
@ -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()
|
|
||||||
99
app/place.py
99
app/place.py
|
|
@ -1,99 +0,0 @@
|
||||||
"""Nominatim reverse-geocode proxy for the map place dossier.
|
|
||||||
|
|
||||||
Browser clients cannot set an identifying User-Agent, and Nominatim typically
|
|
||||||
blocks CORS — so the HUD calls GET /api/place instead of talking to OSM
|
|
||||||
directly. Cache 60s / 500 keys; never exceed 1 req/s upstream.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import time
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
from cachetools import TTLCache
|
|
||||||
|
|
||||||
from config import NOMINATIM_MIN_INTERVAL, NOMINATIM_URL, OSINT_USER_AGENT
|
|
||||||
|
|
||||||
_NOMINATIM = NOMINATIM_URL.rstrip("/")
|
|
||||||
|
|
||||||
place_cache: TTLCache = TTLCache(maxsize=500, ttl=60)
|
|
||||||
|
|
||||||
_lock = asyncio.Lock()
|
|
||||||
_last_req = 0.0
|
|
||||||
|
|
||||||
_ADDR_KEEP = (
|
|
||||||
"house_number", "road", "neighbourhood", "suburb", "city", "town",
|
|
||||||
"village", "hamlet", "county", "state", "postcode", "country", "country_code",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def cache_key(lat: float, lon: float) -> str:
|
|
||||||
return f"{lat:.4f},{lon:.4f}"
|
|
||||||
|
|
||||||
|
|
||||||
def slim_place(lat: float, lon: float, data: dict | None) -> dict:
|
|
||||||
data = data or {}
|
|
||||||
raw_addr = data.get("address")
|
|
||||||
addr_in: dict = raw_addr if isinstance(raw_addr, dict) else {}
|
|
||||||
address = {k: addr_in[k] for k in _ADDR_KEEP if addr_in.get(k)}
|
|
||||||
err = data.get("error")
|
|
||||||
display = None if err else (data.get("display_name") or None)
|
|
||||||
name = None if err else (data.get("name") or address.get("city")
|
|
||||||
or address.get("town") or address.get("village") or None)
|
|
||||||
return {
|
|
||||||
"lat": lat,
|
|
||||||
"lon": lon,
|
|
||||||
"display_name": display,
|
|
||||||
"name": name,
|
|
||||||
"address": address,
|
|
||||||
"osm_type": None if err else data.get("osm_type"),
|
|
||||||
"osm_id": None if err else data.get("osm_id"),
|
|
||||||
"attribution": "© OpenStreetMap contributors",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def reverse_geocode(lat: float, lon: float) -> dict:
|
|
||||||
"""Reverse-geocode a point. Cache hits skip Nominatim entirely."""
|
|
||||||
if not (-90.0 <= lat <= 90.0 and -180.0 <= lon <= 180.0):
|
|
||||||
raise ValueError("lat/lon out of range")
|
|
||||||
key = cache_key(lat, lon)
|
|
||||||
qlat, qlon = (float(p) for p in key.split(","))
|
|
||||||
async with _lock:
|
|
||||||
hit = place_cache.get(key)
|
|
||||||
if hit is not None:
|
|
||||||
return hit
|
|
||||||
global _last_req
|
|
||||||
wait = _last_req + NOMINATIM_MIN_INTERVAL - time.monotonic()
|
|
||||||
if wait > 0:
|
|
||||||
await asyncio.sleep(wait)
|
|
||||||
body = await _fetch_nominatim(qlat, qlon)
|
|
||||||
_last_req = time.monotonic()
|
|
||||||
place_cache[key] = body
|
|
||||||
return body
|
|
||||||
|
|
||||||
|
|
||||||
async def _fetch_nominatim(lat: float, lon: float) -> dict:
|
|
||||||
headers = {
|
|
||||||
"User-Agent": OSINT_USER_AGENT,
|
|
||||||
"Accept": "application/json",
|
|
||||||
}
|
|
||||||
url = f"{_NOMINATIM}/reverse"
|
|
||||||
params = {
|
|
||||||
"lat": f"{lat:.6f}",
|
|
||||||
"lon": f"{lon:.6f}",
|
|
||||||
"format": "jsonv2",
|
|
||||||
"addressdetails": "1",
|
|
||||||
"zoom": "18",
|
|
||||||
}
|
|
||||||
async with _http_client(timeout=10.0, follow_redirects=True) as client:
|
|
||||||
r = await client.get(url, params=params, headers=headers)
|
|
||||||
r.raise_for_status()
|
|
||||||
data = r.json()
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
data = {}
|
|
||||||
return slim_place(lat, lon, data)
|
|
||||||
|
|
||||||
|
|
||||||
def _http_client(**kwargs):
|
|
||||||
return httpx.AsyncClient(**kwargs)
|
|
||||||
|
|
@ -12,5 +12,3 @@ python-dateutil>=2.9
|
||||||
structlog>=24.4
|
structlog>=24.4
|
||||||
websockets>=14
|
websockets>=14
|
||||||
cachetools>=5.5
|
cachetools>=5.5
|
||||||
h3>=4.0
|
|
||||||
sgp4>=2.23
|
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,9 @@
|
||||||
"""Long-running camera discovery service.
|
"""Long-running camera discovery service.
|
||||||
|
|
||||||
Discovers cameras on an interval and upserts them into the `cameras` table
|
Follows the existing ingest pattern: discovers cameras on an interval and
|
||||||
(dedupe by url_hash) for the /api/cameras bbox query. Discovery is not an
|
publishes each one as a NATS message (`events.camera`) so the shared NATS ->
|
||||||
event: this process does not publish `events.camera` messages. Those were
|
ingester pipeline persists them; also upserts directly into the `cameras`
|
||||||
inserted as events rows and flooded the HUD feed. The cameras table is the
|
table (dedupe by url_hash) for the /api/cameras bbox query.
|
||||||
index.
|
|
||||||
|
|
||||||
Env:
|
Env:
|
||||||
CAMERA_SOURCE_URLS comma-separated public directory/list URLs
|
CAMERA_SOURCE_URLS comma-separated public directory/list URLs
|
||||||
|
|
@ -15,6 +14,7 @@ Env:
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
@ -22,12 +22,16 @@ from pathlib import Path
|
||||||
sys_path = str(Path(__file__).parent)
|
sys_path = str(Path(__file__).parent)
|
||||||
sys.path.insert(0, sys_path)
|
sys.path.insert(0, sys_path)
|
||||||
|
|
||||||
|
import nats # noqa: E402
|
||||||
|
|
||||||
from camera_config import ( # 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,
|
SNAPSHOT_CACHE_DIR,
|
||||||
)
|
)
|
||||||
from camera_scraper import run_cycle # noqa: E402
|
from camera_models import cameras # noqa: E402
|
||||||
from database import init_extensions # 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,
|
logging.basicConfig(level=logging.INFO,
|
||||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||||
|
|
@ -36,16 +40,48 @@ logger = logging.getLogger("osint.camera_service")
|
||||||
ENABLED = sys.argv[1:] != ["--once"]
|
ENABLED = sys.argv[1:] != ["--once"]
|
||||||
|
|
||||||
|
|
||||||
async def publish_new_cameras(rows: list | None = None) -> int:
|
async def publish_new_cameras() -> int:
|
||||||
"""Do not publish camera discoveries as events.
|
"""Publish cameras seen in the latest cycle to NATS for the ingester."""
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
``run_cycle`` already upserts the cameras table, which backs
|
cutoff = datetime.now(timezone.utc) - timedelta(seconds=CAMERA_SCRAPE_INTERVAL * 2)
|
||||||
``GET /api/cameras``. ``rows`` is newly seen cameras from a cycle or a
|
published = 0
|
||||||
test; none are JetStream-published, so the ingester inserts 0 events
|
try:
|
||||||
with source_type=camera.
|
nc = await nats.connect(NATS_URL)
|
||||||
"""
|
except Exception: # noqa: BLE001
|
||||||
del rows
|
logger.warning("NATS unavailable — skipping publish pass")
|
||||||
return 0
|
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:
|
async def main() -> None:
|
||||||
|
|
@ -57,7 +93,8 @@ async def main() -> None:
|
||||||
try:
|
try:
|
||||||
n = await run_cycle()
|
n = await run_cycle()
|
||||||
p = await publish_new_cameras()
|
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
|
except Exception: # noqa: BLE001
|
||||||
logger.exception("camera cycle error")
|
logger.exception("camera cycle error")
|
||||||
if not ENABLED: # --once mode
|
if not ENABLED: # --once mode
|
||||||
|
|
|
||||||
|
|
@ -24,8 +24,8 @@ import sys
|
||||||
|
|
||||||
sys.path.insert(0, sys_path)
|
sys.path.insert(0, sys_path)
|
||||||
|
|
||||||
from config import NATS_URL, FIRMS_INTERVAL, FIRMS_DATASET, AISSTREAM_IN_INGEST, VESSELAPI_IN_INGEST # noqa: E402
|
from config import NATS_URL, FIRMS_INTERVAL, FIRMS_DATASET, AISSTREAM_IN_INGEST # noqa: E402
|
||||||
from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_eonet, ingest_cisa_kev # noqa: E402
|
from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes # noqa: E402
|
||||||
from fire_sources import ingest_fires # noqa: E402
|
from fire_sources import ingest_fires # noqa: E402
|
||||||
from ingestor import ingest_event, start_nats_consumer # noqa: E402
|
from ingestor import ingest_event, start_nats_consumer # noqa: E402
|
||||||
|
|
||||||
|
|
@ -37,8 +37,6 @@ INTERVAL = int(os.getenv("INGEST_INTERVAL", "300"))
|
||||||
GDELT_QUERY = os.getenv("GDELT_QUERY", "")
|
GDELT_QUERY = os.getenv("GDELT_QUERY", "")
|
||||||
ENABLE_QUAKES = os.getenv("INGEST_EARTHQUAKES", "1").lower() in ("1", "true", "yes")
|
ENABLE_QUAKES = os.getenv("INGEST_EARTHQUAKES", "1").lower() in ("1", "true", "yes")
|
||||||
ENABLE_FIRES = os.getenv("INGEST_FIRES", "1").lower() in ("1", "true", "yes")
|
ENABLE_FIRES = os.getenv("INGEST_FIRES", "1").lower() in ("1", "true", "yes")
|
||||||
ENABLE_EONET = os.getenv("INGEST_EONET", "1").lower() in ("1", "true", "yes")
|
|
||||||
ENABLE_KEV = os.getenv("INGEST_KEV", "1").lower() in ("1", "true", "yes")
|
|
||||||
|
|
||||||
NATS_STREAM = "events"
|
NATS_STREAM = "events"
|
||||||
|
|
||||||
|
|
@ -56,29 +54,14 @@ async def producer_loop() -> None:
|
||||||
try:
|
try:
|
||||||
g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50)
|
g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50)
|
||||||
logger.info("GDELT -> %d articles", g)
|
logger.info("GDELT -> %d articles", g)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
# Quota/backoff cases are handled inside ingest_gdelt (one clean
|
logger.exception("GDELT fetch failed")
|
||||||
# line); anything reaching here is a real failure and a stack
|
|
||||||
# trace every 5 minutes is not actionable, so keep it to one line.
|
|
||||||
logger.warning("GDELT fetch failed: %s", exc)
|
|
||||||
if ENABLE_QUAKES:
|
if ENABLE_QUAKES:
|
||||||
try:
|
try:
|
||||||
q = await ingest_earthquakes()
|
q = await ingest_earthquakes()
|
||||||
logger.info("USGS -> %d events", q)
|
logger.info("USGS -> %d events", q)
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
logger.exception("USGS fetch failed")
|
logger.exception("USGS fetch failed")
|
||||||
if ENABLE_EONET:
|
|
||||||
try:
|
|
||||||
n = await ingest_eonet()
|
|
||||||
logger.info("EONET -> %d events", n)
|
|
||||||
except Exception: # noqa: BLE001
|
|
||||||
logger.exception("EONET fetch failed")
|
|
||||||
if ENABLE_KEV:
|
|
||||||
try:
|
|
||||||
k = await ingest_cisa_kev()
|
|
||||||
logger.info("CISA KEV -> %d events", k)
|
|
||||||
except Exception: # noqa: BLE001
|
|
||||||
logger.exception("CISA KEV fetch failed")
|
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
logger.exception("producer cycle error")
|
logger.exception("producer cycle error")
|
||||||
await asyncio.sleep(INTERVAL)
|
await asyncio.sleep(INTERVAL)
|
||||||
|
|
@ -119,24 +102,6 @@ async def fire_loop() -> None:
|
||||||
await asyncio.sleep(FIRMS_INTERVAL)
|
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:
|
async def main() -> None:
|
||||||
logger.info(
|
logger.info(
|
||||||
"ingester starting (rss=%d feeds, gdelt_q=%r, quakes=%s, fires=%s, interval=%ss)",
|
"ingester starting (rss=%d feeds, gdelt_q=%r, quakes=%s, fires=%s, interval=%ss)",
|
||||||
|
|
@ -147,9 +112,7 @@ async def main() -> None:
|
||||||
await refresh_cache()
|
await refresh_cache()
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception("geofence cache refresh failed (ST_Intersects still runs on ingest)")
|
logger.exception("geofence cache refresh failed (ST_Intersects still runs on ingest)")
|
||||||
tasks: list[asyncio.Task] = [
|
tasks: list[asyncio.Task] = []
|
||||||
asyncio.create_task(geofence_feed_loop()),
|
|
||||||
]
|
|
||||||
if ENABLE_FIRES:
|
if ENABLE_FIRES:
|
||||||
# Fire ingest only starts once FIRMS_MAP_KEY is set (ingest_fires logs
|
# Fire ingest only starts once FIRMS_MAP_KEY is set (ingest_fires logs
|
||||||
# and idles otherwise).
|
# and idles otherwise).
|
||||||
|
|
@ -157,9 +120,6 @@ async def main() -> None:
|
||||||
if AISSTREAM_IN_INGEST:
|
if AISSTREAM_IN_INGEST:
|
||||||
from ais_stream import run_ais_worker # noqa: E402
|
from ais_stream import run_ais_worker # noqa: E402
|
||||||
tasks.append(asyncio.create_task(run_ais_worker()))
|
tasks.append(asyncio.create_task(run_ais_worker()))
|
||||||
if VESSELAPI_IN_INGEST:
|
|
||||||
from vesselapi import run_vesselapi_worker # noqa: E402
|
|
||||||
tasks.append(asyncio.create_task(run_vesselapi_worker()))
|
|
||||||
await asyncio.gather(producer_loop(), consumer_loop(), *tasks)
|
await asyncio.gather(producer_loop(), consumer_loop(), *tasks)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
149
app/run_masscan_service.py
Normal file
149
app/run_masscan_service.py
Normal file
|
|
@ -0,0 +1,149 @@
|
||||||
|
"""Continuous masscan rolling-sweep service for the OSINT dashboard.
|
||||||
|
|
||||||
|
Runs masscan against the configured range for open port 554 (RTSP), streams
|
||||||
|
the JSON-lines output, and ingests open hosts into the `cameras` table (new
|
||||||
|
finds only) plus publishes them to NATS — exactly like the passive scraper.
|
||||||
|
|
||||||
|
Because a full IPv4 sweep at a conservative rate takes days, this runs
|
||||||
|
masscan CONTINUOUSLY: each pass streams results in as they're found, and when
|
||||||
|
a pass completes the sweep restarts from the top. New cameras are picked up
|
||||||
|
on every pass.
|
||||||
|
|
||||||
|
Ethics: detection-only (open-port SYN scan). Private/reserved ranges are
|
||||||
|
excluded and the service REFUSES to start if the excludefile is missing, so
|
||||||
|
we never probe private space by accident.
|
||||||
|
|
||||||
|
Run once (for a manual/test pass): python app/run_masscan_service.py --once
|
||||||
|
Run forever (systemd): python app/run_masscan_service.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys_path = str(Path(__file__).parent)
|
||||||
|
sys.path.insert(0, sys_path)
|
||||||
|
|
||||||
|
import masscan_config as cfg # noqa: E402
|
||||||
|
from database import init_extensions # noqa: E402
|
||||||
|
from masscan_scanner import ( # noqa: E402
|
||||||
|
parse_masscan_line, extract_open_ips, flush,
|
||||||
|
)
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO,
|
||||||
|
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||||
|
logger = logging.getLogger("osint.masscan_service")
|
||||||
|
|
||||||
|
ONCE = "--once" in sys.argv[1:]
|
||||||
|
|
||||||
|
|
||||||
|
def _verify_excludefile() -> None:
|
||||||
|
"""Fail closed: refuse to sweep the wide range without an excludefile."""
|
||||||
|
if not cfg.MASSCAN_EXCLUDEFILE:
|
||||||
|
raise SystemExit("MASSCAN_EXCLUDEFILE is empty — refusing to run")
|
||||||
|
if not Path(cfg.MASSCAN_EXCLUDEFILE).is_file():
|
||||||
|
raise SystemExit(
|
||||||
|
f"excludefile {cfg.MASSCAN_EXCLUDEFILE!r} missing — refusing to "
|
||||||
|
f"run (would risk probing private ranges). Install the excludefile "
|
||||||
|
f"first (see deploy/masscan-excludes.txt)."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_command() -> list[str]:
|
||||||
|
cmd = [
|
||||||
|
cfg.MASSCAN_BIN,
|
||||||
|
cfg.MASSCAN_RANGE,
|
||||||
|
f"-p{cfg.MASSCAN_PORTS}",
|
||||||
|
f"--rate={cfg.MASSCAN_RATE}",
|
||||||
|
f"--retries={cfg.MASSCAN_RETRIES}",
|
||||||
|
f"--wait={cfg.MASSCAN_WAIT}",
|
||||||
|
"--output-format=json",
|
||||||
|
"--output-file=-",
|
||||||
|
]
|
||||||
|
if cfg.MASSCAN_EXCLUDEFILE:
|
||||||
|
cmd.append(f"--excludefile={cfg.MASSCAN_EXCLUDEFILE}")
|
||||||
|
return cmd
|
||||||
|
|
||||||
|
|
||||||
|
async def _drain_stderr(stream: asyncio.StreamReader) -> None:
|
||||||
|
"""Consume masscan's progress chatter so its stderr pipe never fills."""
|
||||||
|
while True:
|
||||||
|
line = await stream.readline()
|
||||||
|
if not line:
|
||||||
|
break
|
||||||
|
text = line.decode(errors="ignore").strip()
|
||||||
|
if text and not text.startswith("rate:"):
|
||||||
|
logger.debug("masscan: %s", text)
|
||||||
|
|
||||||
|
|
||||||
|
async def run_pass() -> tuple[int, int]:
|
||||||
|
"""Run one full sweep pass, ingesting incrementally.
|
||||||
|
|
||||||
|
Returns (new_hosts, total_hosts_seen) for the whole pass.
|
||||||
|
"""
|
||||||
|
cmd = build_command()
|
||||||
|
logger.info("starting masscan pass: %s", " ".join(cmd))
|
||||||
|
proc = await asyncio.create_subprocess_exec(
|
||||||
|
*cmd,
|
||||||
|
stdout=asyncio.subprocess.PIPE,
|
||||||
|
stderr=asyncio.subprocess.PIPE,
|
||||||
|
)
|
||||||
|
if proc.stderr is not None:
|
||||||
|
asyncio.ensure_future(_drain_stderr(proc.stderr))
|
||||||
|
|
||||||
|
seen: set[str] = set()
|
||||||
|
total_seen = 0
|
||||||
|
total_new = 0
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
raw = await proc.stdout.readline()
|
||||||
|
if not raw:
|
||||||
|
break
|
||||||
|
records = parse_masscan_line(raw.decode(errors="ignore"))
|
||||||
|
for ip in extract_open_ips(records, 554):
|
||||||
|
if ip in seen:
|
||||||
|
continue
|
||||||
|
seen.add(ip)
|
||||||
|
if len(seen) >= cfg.MASSCAN_FLUSH_EVERY:
|
||||||
|
new, _published = await flush(seen, total_new)
|
||||||
|
total_new += new
|
||||||
|
total_seen += new
|
||||||
|
# Drain the final partial batch.
|
||||||
|
if seen:
|
||||||
|
new, _published = await flush(seen, total_new)
|
||||||
|
total_new += new
|
||||||
|
rc = await proc.wait()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
proc.kill()
|
||||||
|
raise
|
||||||
|
logger.info("masscan pass finished (rc=%s): %d new hosts ingested",
|
||||||
|
rc, total_new)
|
||||||
|
return total_new, total_seen
|
||||||
|
|
||||||
|
|
||||||
|
async def main() -> None:
|
||||||
|
_verify_excludefile()
|
||||||
|
await init_extensions()
|
||||||
|
logger.info(
|
||||||
|
"masscan service starting: range=%s ports=%s rate=%s pps (full sweep "
|
||||||
|
"~%.0fh at this rate)",
|
||||||
|
cfg.MASSCAN_RANGE, cfg.MASSCAN_PORTS, cfg.MASSCAN_RATE,
|
||||||
|
4.29e9 / cfg.MASSCAN_RATE / 3600,
|
||||||
|
)
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await run_pass()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
logger.exception("masscan pass error")
|
||||||
|
if ONCE:
|
||||||
|
return
|
||||||
|
# Small gap between passes so the restart is visible in logs.
|
||||||
|
await asyncio.sleep(5)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
|
|
@ -1,289 +0,0 @@
|
||||||
"""CelesTrak satellites last-known overlay.
|
|
||||||
|
|
||||||
Fetches GP **JSON** (OMM mean elements — not TLE) per group at most once per
|
|
||||||
2 hours, caches the element blob, and propagates positions with a real SGP4
|
|
||||||
library on every request. Positions move every second; the *element set* is
|
|
||||||
what we cache, not the derived lat/lon.
|
|
||||||
|
|
||||||
Catalog numbers >= 100000 only fit OMM/JSON, never a 5-column TLE field, so
|
|
||||||
elements are initialized through :func:`sgp4.omm.initialize` (which consumes
|
|
||||||
the CelesTrak GP JSON fields verbatim) rather than round-tripping to TLE.
|
|
||||||
|
|
||||||
CelesTrak usage policy is non-negotiable: fetch the GP JSON blob at most once
|
|
||||||
per 2 hours per group, never fan out every GROUP, never also fetch
|
|
||||||
``GROUP=active`` plus subsets, and identify with ``OSINT_USER_AGENT``.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import math
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from urllib.parse import quote
|
|
||||||
|
|
||||||
logger = logging.getLogger("osint.satellites")
|
|
||||||
|
|
||||||
CELESTRAK_GP = "https://celestrak.org/NORAD/elements/gp.php"
|
|
||||||
SATNOGS_TLE = "https://db.satnogs.org/api/tle/"
|
|
||||||
DEFAULT_GROUPS = ("stations", "weather")
|
|
||||||
ALLOWED_GROUPS = ("stations", "weather", "gps-ops", "starlink")
|
|
||||||
# CelesTrak policy: do not hit gp.php more than once per 2 hours per group.
|
|
||||||
SATELLITE_TTL = 2 * 3600.0
|
|
||||||
SOURCE_CELESTRAK = "celestrak"
|
|
||||||
SOURCE_SATNOGS = "satnogs"
|
|
||||||
DEFAULT_LIMIT = 2000
|
|
||||||
|
|
||||||
# WGS-84 ellipsoid for TEME -> geodetic.
|
|
||||||
_WGS84_A = 6378.137
|
|
||||||
_WGS84_F = 1.0 / 298.257223563
|
|
||||||
|
|
||||||
# Last-good element blob per group, kept past TTL so a 403 / "has not updated
|
|
||||||
# since ..." still serves the previous set instead of failing the overlay.
|
|
||||||
_last_good: dict[str, list[dict]] = {}
|
|
||||||
|
|
||||||
|
|
||||||
def parse_groups(raw: str | None) -> list[str]:
|
|
||||||
"""Validate + normalize a comma-separated group list. Raises ValueError.
|
|
||||||
|
|
||||||
Starlink is allowed only when explicitly requested (never in the default);
|
|
||||||
it is a large supplemental feed, not part of the stations/weather default.
|
|
||||||
"""
|
|
||||||
groups = [g.strip().lower() for g in (raw or "").split(",") if g.strip()]
|
|
||||||
if not groups:
|
|
||||||
raise ValueError("groups must be a non-empty comma-separated list")
|
|
||||||
bad = [g for g in groups if g not in ALLOWED_GROUPS]
|
|
||||||
if bad:
|
|
||||||
raise ValueError(f"unknown group(s): {', '.join(bad)}")
|
|
||||||
# Dedup, preserve order.
|
|
||||||
seen: set[str] = set()
|
|
||||||
out: list[str] = []
|
|
||||||
for g in groups:
|
|
||||||
if g not in seen:
|
|
||||||
seen.add(g)
|
|
||||||
out.append(g)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _teme_to_geodetic(
|
|
||||||
r: tuple[float, float, float],
|
|
||||||
jd: float,
|
|
||||||
fr: float,
|
|
||||||
) -> tuple[float, float, float]:
|
|
||||||
"""SGP4 TEME position (km) -> geodetic (lat_deg, lon_deg, alt_km).
|
|
||||||
|
|
||||||
Rotate TEME into an Earth-fixed frame via GMST, then iterate the WGS-84
|
|
||||||
geodetic conversion. Good to well under a km for a ground-track overlay.
|
|
||||||
"""
|
|
||||||
# GMST (radians) from UT1 ~= UTC here (sub-second error is negligible).
|
|
||||||
d = (jd + fr) - 2451545.0
|
|
||||||
t = d / 36525.0
|
|
||||||
gmst_s = (
|
|
||||||
67310.54841
|
|
||||||
+ (876600.0 * 3600.0 + 8640184.812866) * t
|
|
||||||
+ 0.093104 * t * t
|
|
||||||
- 6.2e-6 * t * t * t
|
|
||||||
)
|
|
||||||
theta = math.radians((gmst_s % 86400.0) / 240.0)
|
|
||||||
|
|
||||||
x, y, z = r
|
|
||||||
xe = x * math.cos(theta) + y * math.sin(theta)
|
|
||||||
ye = -x * math.sin(theta) + y * math.cos(theta)
|
|
||||||
ze = z
|
|
||||||
|
|
||||||
e2 = _WGS84_F * (2.0 - _WGS84_F)
|
|
||||||
p = math.sqrt(xe * xe + ye * ye)
|
|
||||||
lon = math.atan2(ye, xe)
|
|
||||||
lat = math.atan2(ze, p * (1.0 - e2))
|
|
||||||
alt = 0.0
|
|
||||||
for _ in range(10):
|
|
||||||
n = _WGS84_A / math.sqrt(1.0 - e2 * math.sin(lat) ** 2)
|
|
||||||
alt = p / math.cos(lat) - n
|
|
||||||
lat = math.atan2(ze, p * (1.0 - e2 * n / (n + alt)))
|
|
||||||
n = _WGS84_A / math.sqrt(1.0 - e2 * math.sin(lat) ** 2)
|
|
||||||
alt = p / math.cos(lat) - n
|
|
||||||
return math.degrees(lat), math.degrees(lon), alt
|
|
||||||
|
|
||||||
|
|
||||||
def propagate_gp(
|
|
||||||
elements: list[dict],
|
|
||||||
group: str,
|
|
||||||
now: datetime,
|
|
||||||
) -> list[dict]:
|
|
||||||
"""Propagate CelesTrak GP JSON elements to geodetic positions at ``now``.
|
|
||||||
|
|
||||||
Pure and deterministic given ``now``. Returns ``[{id, name, lat, lon,
|
|
||||||
alt_km, group}]``; malformed elements and propagation errors are skipped.
|
|
||||||
"""
|
|
||||||
from sgp4.api import Satrec, jday
|
|
||||||
import sgp4.omm as omm
|
|
||||||
|
|
||||||
jd, fr = jday(
|
|
||||||
now.year, now.month, now.day,
|
|
||||||
now.hour, now.minute, now.second + now.microsecond / 1e6,
|
|
||||||
)
|
|
||||||
out: list[dict] = []
|
|
||||||
for rec in elements:
|
|
||||||
if not isinstance(rec, dict):
|
|
||||||
continue
|
|
||||||
sat = Satrec()
|
|
||||||
try:
|
|
||||||
omm.initialize(sat, rec)
|
|
||||||
except (KeyError, ValueError, TypeError):
|
|
||||||
continue
|
|
||||||
err, r, _v = sat.sgp4(jd, fr)
|
|
||||||
if err != 0:
|
|
||||||
continue
|
|
||||||
lat, lon, alt = _teme_to_geodetic(r, jd, fr)
|
|
||||||
norad = rec.get("NORAD_CAT_ID")
|
|
||||||
out.append({
|
|
||||||
"id": str(norad) if norad is not None else "",
|
|
||||||
"name": rec.get("OBJECT_NAME") or str(norad or ""),
|
|
||||||
"lat": round(lat, 5),
|
|
||||||
"lon": round(lon, 5),
|
|
||||||
"alt_km": round(alt, 2),
|
|
||||||
"group": group,
|
|
||||||
})
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _max_epoch(elements: list[dict]) -> str | None:
|
|
||||||
"""Most recent EPOCH across an element set (ISO-8601 lexical max)."""
|
|
||||||
epochs = [
|
|
||||||
str(e["EPOCH"]) for e in elements
|
|
||||||
if isinstance(e, dict) and e.get("EPOCH")
|
|
||||||
]
|
|
||||||
return max(epochs) if epochs else None
|
|
||||||
|
|
||||||
|
|
||||||
def propagate_satnogs_tle(
|
|
||||||
payload: list[dict],
|
|
||||||
group: str,
|
|
||||||
now: datetime,
|
|
||||||
) -> tuple[list[dict], str | None]:
|
|
||||||
"""Fallback parser for SatNOGS TLE JSON (``[{tle0,tle1,tle2,updated}]``).
|
|
||||||
|
|
||||||
Returns ``(satellites, epoch)`` where epoch is the max ``updated`` time.
|
|
||||||
Only used when the CelesTrak cache is completely empty.
|
|
||||||
"""
|
|
||||||
from sgp4.api import Satrec, jday
|
|
||||||
|
|
||||||
jd, fr = jday(
|
|
||||||
now.year, now.month, now.day,
|
|
||||||
now.hour, now.minute, now.second + now.microsecond / 1e6,
|
|
||||||
)
|
|
||||||
out: list[dict] = []
|
|
||||||
epochs: list[str] = []
|
|
||||||
for rec in payload or []:
|
|
||||||
if not isinstance(rec, dict):
|
|
||||||
continue
|
|
||||||
line1 = rec.get("tle1")
|
|
||||||
line2 = rec.get("tle2")
|
|
||||||
if not line1 or not line2:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
sat = Satrec.twoline2rv(line1, line2)
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
continue
|
|
||||||
e, r, _v = sat.sgp4(jd, fr)
|
|
||||||
if e != 0:
|
|
||||||
continue
|
|
||||||
lat, lon, alt = _teme_to_geodetic(r, jd, fr)
|
|
||||||
satnum = getattr(sat, "satnum_str", None) or rec.get("norad_cat_id")
|
|
||||||
name = (rec.get("tle0") or "").strip().lstrip("0").strip() or str(satnum or "")
|
|
||||||
out.append({
|
|
||||||
"id": str(satnum).strip() or "",
|
|
||||||
"name": name,
|
|
||||||
"lat": round(lat, 5),
|
|
||||||
"lon": round(lon, 5),
|
|
||||||
"alt_km": round(alt, 2),
|
|
||||||
"group": group,
|
|
||||||
})
|
|
||||||
if rec.get("updated"):
|
|
||||||
epochs.append(str(rec["updated"]))
|
|
||||||
return out, (max(epochs) if epochs else None)
|
|
||||||
|
|
||||||
|
|
||||||
async def _group_elements(group: str) -> tuple[list[dict], str | None]:
|
|
||||||
"""CelesTrak GP blob for one group, TTL-cached with a last-good fallback.
|
|
||||||
|
|
||||||
Returns ``(elements, epoch)``. On a fetch failure (403 / "has not updated
|
|
||||||
since ...") falls back to the previous successful blob for that group.
|
|
||||||
"""
|
|
||||||
from live_layers import _get_json, _ttl_get
|
|
||||||
|
|
||||||
url = f"{CELESTRAK_GP}?GROUP={quote(group)}&FORMAT=JSON"
|
|
||||||
|
|
||||||
async def _load() -> list[dict]:
|
|
||||||
data = await _get_json(url)
|
|
||||||
if not isinstance(data, list):
|
|
||||||
raise ValueError(f"unexpected CelesTrak payload for {group}")
|
|
||||||
if data:
|
|
||||||
_last_good[group] = data
|
|
||||||
return data
|
|
||||||
|
|
||||||
key = f"celestrak:gp:{group}"
|
|
||||||
try:
|
|
||||||
elements = await _ttl_get(key, SATELLITE_TTL, _load)
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
logger.warning("celestrak_fetch_failed group=%s: %s", group, exc)
|
|
||||||
elements = _last_good.get(group, [])
|
|
||||||
if not elements:
|
|
||||||
return [], None
|
|
||||||
return elements, _max_epoch(elements)
|
|
||||||
|
|
||||||
|
|
||||||
async def fetch_satellites(
|
|
||||||
groups: list[str],
|
|
||||||
bbox: str | None = None,
|
|
||||||
limit: int = DEFAULT_LIMIT,
|
|
||||||
) -> dict:
|
|
||||||
"""Assemble the ``/api/satellites`` payload for the requested groups."""
|
|
||||||
from live_layers import _get_json, _ttl_get, filter_points_bbox, parse_bbox
|
|
||||||
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
satellites: list[dict] = []
|
|
||||||
epoch: str | None = None
|
|
||||||
source = SOURCE_CELESTRAK
|
|
||||||
|
|
||||||
for group in groups:
|
|
||||||
elements, group_epoch = await _group_elements(group)
|
|
||||||
if not elements:
|
|
||||||
continue
|
|
||||||
if group_epoch and (epoch is None or group_epoch > epoch):
|
|
||||||
epoch = group_epoch
|
|
||||||
satellites.extend(propagate_gp(elements, group, now))
|
|
||||||
|
|
||||||
if not satellites:
|
|
||||||
# Fallback only when the CelesTrak cache is entirely empty — never
|
|
||||||
# poll both providers every cycle.
|
|
||||||
async def _load_satnogs() -> list[dict]:
|
|
||||||
data = await _get_json(SATNOGS_TLE, params={"format": "json"})
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
try:
|
|
||||||
satnogs = await _ttl_get("satnogs:tle", SATELLITE_TTL, _load_satnogs)
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
logger.warning("satnogs_fetch_failed: %s", exc)
|
|
||||||
satnogs = []
|
|
||||||
if satnogs:
|
|
||||||
source = SOURCE_SATNOGS
|
|
||||||
for group in groups:
|
|
||||||
rows, sn_epoch = propagate_satnogs_tle(satnogs, group, now)
|
|
||||||
if sn_epoch and (epoch is None or sn_epoch > epoch):
|
|
||||||
epoch = sn_epoch
|
|
||||||
satellites.extend(rows)
|
|
||||||
|
|
||||||
if bbox:
|
|
||||||
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
|
|
||||||
satellites = filter_points_bbox(
|
|
||||||
satellites, minlon, minlat, maxlon, maxlat, limit,
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
satellites = satellites[:limit]
|
|
||||||
|
|
||||||
return {
|
|
||||||
"satellites": satellites,
|
|
||||||
"source": source,
|
|
||||||
"tle_epoch": epoch,
|
|
||||||
"timestamp": now.isoformat(),
|
|
||||||
}
|
|
||||||
120
app/schemas.py
120
app/schemas.py
|
|
@ -4,10 +4,10 @@ from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import Literal, Optional
|
from typing import Optional
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
# ─── Enums ───────────────────────────────────────────────────────────────
|
# ─── Enums ───────────────────────────────────────────────────────────────
|
||||||
|
|
@ -63,17 +63,6 @@ class FeedSourceCreate(BaseModel):
|
||||||
config: Optional[dict] = None
|
config: Optional[dict] = None
|
||||||
|
|
||||||
|
|
||||||
class FeedSourceUpdate(BaseModel):
|
|
||||||
"""PATCH /api/sources/{id} — only these keys may be set."""
|
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid")
|
|
||||||
|
|
||||||
name: Optional[str] = None
|
|
||||||
url: Optional[str] = None
|
|
||||||
config: Optional[dict] = None
|
|
||||||
enabled: Optional[bool] = None
|
|
||||||
|
|
||||||
|
|
||||||
class FeedSourceOut(BaseModel):
|
class FeedSourceOut(BaseModel):
|
||||||
id: UUID
|
id: UUID
|
||||||
name: str
|
name: str
|
||||||
|
|
@ -284,90 +273,6 @@ class NewsSummaryOut(BaseModel):
|
||||||
id: int
|
id: int
|
||||||
summary_text: str
|
summary_text: str
|
||||||
batch_timestamp: datetime
|
batch_timestamp: datetime
|
||||||
model: Optional[str] = None
|
|
||||||
kind: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class NewsTickerItemOut(BaseModel):
|
|
||||||
"""One flagged ticker row as exposed by GET /api/news/ticker."""
|
|
||||||
|
|
||||||
id: int
|
|
||||||
headline: str
|
|
||||||
importance: str
|
|
||||||
location_name: Optional[str] = None
|
|
||||||
url: Optional[str] = None
|
|
||||||
created_at: datetime
|
|
||||||
|
|
||||||
|
|
||||||
class NewsMapItemOut(BaseModel):
|
|
||||||
"""One flagged map pin as exposed by GET /api/news/map."""
|
|
||||||
|
|
||||||
id: int
|
|
||||||
headline: str
|
|
||||||
importance: str
|
|
||||||
location_name: Optional[str] = None
|
|
||||||
lat: float
|
|
||||||
lon: float
|
|
||||||
location_confidence: Optional[str] = None
|
|
||||||
category: Optional[str] = None
|
|
||||||
url: Optional[str] = None
|
|
||||||
created_at: datetime
|
|
||||||
|
|
||||||
|
|
||||||
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."""
|
|
||||||
|
|
||||||
id: str
|
|
||||||
|
|
||||||
|
|
||||||
class NewsModelsOut(BaseModel):
|
|
||||||
"""Catalog for the summarizer model selector."""
|
|
||||||
|
|
||||||
source: str
|
|
||||||
models: list[NewsModelId]
|
|
||||||
|
|
||||||
|
|
||||||
class SettingsIn(BaseModel):
|
|
||||||
"""Body for PUT /api/settings. ``nous_base_url`` is not writable."""
|
|
||||||
|
|
||||||
summary_model: str = Field(..., min_length=1, max_length=128)
|
|
||||||
|
|
||||||
@field_validator("summary_model")
|
|
||||||
@classmethod
|
|
||||||
def summary_model_not_blank(cls, v: str) -> str:
|
|
||||||
stripped = v.strip()
|
|
||||||
if not stripped:
|
|
||||||
raise ValueError("summary_model must be 1–128 chars, not whitespace-only")
|
|
||||||
if len(stripped) > 128:
|
|
||||||
raise ValueError("summary_model must be 1–128 chars, not whitespace-only")
|
|
||||||
return stripped
|
|
||||||
|
|
||||||
|
|
||||||
class SettingsOut(BaseModel):
|
|
||||||
"""Current summarizer settings. ``nous_base_url`` is read-only."""
|
|
||||||
|
|
||||||
summary_model: str
|
|
||||||
nous_base_url: str
|
|
||||||
|
|
||||||
|
|
||||||
# ─── Aggregations ────────────────────────────────────────────────────────
|
# ─── Aggregations ────────────────────────────────────────────────────────
|
||||||
|
|
@ -417,24 +322,3 @@ class GeofenceUpdate(BaseModel):
|
||||||
geojson: Optional[dict] = None
|
geojson: Optional[dict] = None
|
||||||
active: Optional[bool] = None
|
active: Optional[bool] = None
|
||||||
|
|
||||||
|
|
||||||
class ConflictZoneOut(BaseModel):
|
|
||||||
"""One curated conflict theatre as exposed by GET /api/conflicts."""
|
|
||||||
|
|
||||||
id: str
|
|
||||||
label: str
|
|
||||||
severity: Literal["war", "high", "elevated"]
|
|
||||||
lat: float
|
|
||||||
lon: float
|
|
||||||
description: str
|
|
||||||
eventCount: int
|
|
||||||
lastUpdated: Optional[datetime] = None
|
|
||||||
|
|
||||||
|
|
||||||
class ConflictsOut(BaseModel):
|
|
||||||
"""Response envelope for GET /api/conflicts."""
|
|
||||||
|
|
||||||
zones: list[ConflictZoneOut]
|
|
||||||
timestamp: datetime
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,219 +0,0 @@
|
||||||
"""OSINT Dashboard — non-secret app settings (keyv-style Postgres table).
|
|
||||||
|
|
||||||
Model choice lives here so the summarizer container can read it from Postgres.
|
|
||||||
Only whitelisted names are stored — this is not a generic dump.
|
|
||||||
|
|
||||||
Storage: the table is created lazily with ``CREATE TABLE IF NOT EXISTS`` on
|
|
||||||
first use in each process (same bootstrap pattern as ``api_keys``).
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
from sqlalchemy import Column, DateTime, String, Table, Text, func, select, text
|
|
||||||
|
|
||||||
import keystore
|
|
||||||
from database import async_session, engine, metadata
|
|
||||||
|
|
||||||
DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1"
|
|
||||||
DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B"
|
|
||||||
SETTING_SUMMARY_MODEL = "SUMMARY_MODEL"
|
|
||||||
ALLOWED_SETTINGS = frozenset({SETTING_SUMMARY_MODEL})
|
|
||||||
MODELS_CACHE_TTL_S = 600.0
|
|
||||||
MODELS_TIMEOUT_S = 8.0
|
|
||||||
DEFAULT_MODELS_USER_AGENT = "osint-dashboard-news-summarizer"
|
|
||||||
|
|
||||||
FALLBACK_MODELS = [
|
|
||||||
"Hermes-4.3-36B",
|
|
||||||
"Hermes-4-70B",
|
|
||||||
"google/gemini-2.5-flash",
|
|
||||||
"anthropic/claude-haiku-4.5",
|
|
||||||
"openai/gpt-4.1-mini",
|
|
||||||
"x-ai/grok-4",
|
|
||||||
]
|
|
||||||
|
|
||||||
app_settings = Table(
|
|
||||||
"app_settings",
|
|
||||||
metadata,
|
|
||||||
Column("name", String(128), primary_key=True),
|
|
||||||
Column("value", Text, nullable=False),
|
|
||||||
Column("updated_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
|
|
||||||
)
|
|
||||||
|
|
||||||
_CREATE_TABLE_SQL = text(
|
|
||||||
"""
|
|
||||||
CREATE TABLE IF NOT EXISTS app_settings (
|
|
||||||
name VARCHAR(128) PRIMARY KEY,
|
|
||||||
value TEXT NOT NULL,
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
)
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
|
|
||||||
_ensure_lock = asyncio.Lock()
|
|
||||||
_ensured = False
|
|
||||||
_models_cache: tuple[float, dict] | None = None
|
|
||||||
|
|
||||||
|
|
||||||
class SettingsError(ValueError):
|
|
||||||
"""Raised when a setting name or value fails validation."""
|
|
||||||
|
|
||||||
|
|
||||||
async def ensure_app_settings_table() -> None:
|
|
||||||
"""Create the app_settings table if it doesn't exist (idempotent, per process)."""
|
|
||||||
global _ensured
|
|
||||||
if _ensured:
|
|
||||||
return
|
|
||||||
async with _ensure_lock:
|
|
||||||
if _ensured:
|
|
||||||
return
|
|
||||||
async with engine.begin() as conn:
|
|
||||||
await conn.execute(_CREATE_TABLE_SQL)
|
|
||||||
_ensured = True
|
|
||||||
|
|
||||||
|
|
||||||
def nous_base_url() -> str:
|
|
||||||
"""Read-only Nous inference base URL (env, never writable from the UI)."""
|
|
||||||
raw = (os.getenv("NOUS_BASE_URL") or "").strip().rstrip("/")
|
|
||||||
return raw or DEFAULT_NOUS_BASE_URL
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_summary_model(value: str) -> str:
|
|
||||||
stripped = (value or "").strip()
|
|
||||||
if not stripped or len(stripped) > 128:
|
|
||||||
raise SettingsError("summary_model must be 1–128 chars, not whitespace-only")
|
|
||||||
return stripped
|
|
||||||
|
|
||||||
|
|
||||||
async def get_summary_model() -> str:
|
|
||||||
"""Stored SUMMARY_MODEL, else env, else Hermes-4.3-36B."""
|
|
||||||
await ensure_app_settings_table()
|
|
||||||
async with async_session() as session:
|
|
||||||
row = (
|
|
||||||
await session.execute(
|
|
||||||
select(app_settings).where(app_settings.c.name == SETTING_SUMMARY_MODEL)
|
|
||||||
)
|
|
||||||
).mappings().one_or_none()
|
|
||||||
if row and row["value"]:
|
|
||||||
return row["value"]
|
|
||||||
return os.getenv("SUMMARY_MODEL", DEFAULT_SUMMARY_MODEL)
|
|
||||||
|
|
||||||
|
|
||||||
async def set_summary_model(value: str) -> dict:
|
|
||||||
"""Upsert SUMMARY_MODEL and return the public settings payload."""
|
|
||||||
value = _validate_summary_model(value)
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
|
|
||||||
await ensure_app_settings_table()
|
|
||||||
async with async_session() as session:
|
|
||||||
existing = (
|
|
||||||
await session.execute(
|
|
||||||
select(app_settings).where(app_settings.c.name == SETTING_SUMMARY_MODEL)
|
|
||||||
)
|
|
||||||
).mappings().one_or_none()
|
|
||||||
if existing:
|
|
||||||
await session.execute(
|
|
||||||
app_settings.update()
|
|
||||||
.where(app_settings.c.name == SETTING_SUMMARY_MODEL)
|
|
||||||
.values(value=value, updated_at=now)
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
await session.execute(
|
|
||||||
app_settings.insert().values(
|
|
||||||
name=SETTING_SUMMARY_MODEL, value=value, updated_at=now
|
|
||||||
)
|
|
||||||
)
|
|
||||||
await session.commit()
|
|
||||||
return await get_app_settings()
|
|
||||||
|
|
||||||
|
|
||||||
async def get_app_settings() -> dict:
|
|
||||||
return {
|
|
||||||
"summary_model": await get_summary_model(),
|
|
||||||
"nous_base_url": nous_base_url(),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _fallback_payload() -> dict:
|
|
||||||
return {
|
|
||||||
"source": "fallback",
|
|
||||||
"models": [{"id": mid} for mid in FALLBACK_MODELS],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def _nous_api_key() -> str | None:
|
|
||||||
"""Keystore first, then env. Any lookup failure is treated as missing."""
|
|
||||||
try:
|
|
||||||
stored = await keystore.get_api_key("NOUS_API_KEY")
|
|
||||||
except Exception:
|
|
||||||
stored = None
|
|
||||||
if stored and str(stored).strip():
|
|
||||||
return str(stored).strip()
|
|
||||||
env = (os.getenv("NOUS_API_KEY") or "").strip()
|
|
||||||
return env or None
|
|
||||||
|
|
||||||
|
|
||||||
def _models_user_agent() -> str:
|
|
||||||
return os.getenv("OSINT_USER_AGENT") or DEFAULT_MODELS_USER_AGENT
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_models_payload(body: object) -> list[dict[str, str]]:
|
|
||||||
if isinstance(body, dict):
|
|
||||||
raw = body.get("data", body.get("models", []))
|
|
||||||
elif isinstance(body, list):
|
|
||||||
raw = body
|
|
||||||
else:
|
|
||||||
raw = []
|
|
||||||
out: list[dict[str, str]] = []
|
|
||||||
for item in raw or []:
|
|
||||||
if isinstance(item, str) and item.strip():
|
|
||||||
out.append({"id": item.strip()})
|
|
||||||
elif isinstance(item, dict):
|
|
||||||
mid = item.get("id") or item.get("name")
|
|
||||||
if mid:
|
|
||||||
out.append({"id": str(mid)})
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
async def _http_get(url: str, *, headers: dict[str, str], timeout: float) -> httpx.Response:
|
|
||||||
async with httpx.AsyncClient(timeout=timeout, headers=headers) as client:
|
|
||||||
return await client.get(url)
|
|
||||||
|
|
||||||
|
|
||||||
async def list_models() -> dict:
|
|
||||||
"""Live ``GET {base}/models`` when a key is present; otherwise curated fallback.
|
|
||||||
|
|
||||||
Never raises to the caller for missing key or upstream failure.
|
|
||||||
"""
|
|
||||||
global _models_cache
|
|
||||||
key = await _nous_api_key()
|
|
||||||
if not key:
|
|
||||||
return _fallback_payload()
|
|
||||||
|
|
||||||
now = time.monotonic()
|
|
||||||
hit = _models_cache
|
|
||||||
if hit and now - hit[0] < MODELS_CACHE_TTL_S:
|
|
||||||
return hit[1]
|
|
||||||
|
|
||||||
url = f"{nous_base_url()}/models"
|
|
||||||
headers = {
|
|
||||||
"Authorization": f"Bearer {key}",
|
|
||||||
"User-Agent": _models_user_agent(),
|
|
||||||
"Accept": "application/json",
|
|
||||||
}
|
|
||||||
try:
|
|
||||||
resp = await _http_get(url, headers=headers, timeout=MODELS_TIMEOUT_S)
|
|
||||||
resp.raise_for_status()
|
|
||||||
models = _parse_models_payload(resp.json())
|
|
||||||
if not models:
|
|
||||||
return _fallback_payload()
|
|
||||||
payload = {"source": "live", "models": models}
|
|
||||||
_models_cache = (now, payload)
|
|
||||||
return payload
|
|
||||||
except Exception:
|
|
||||||
return _fallback_payload()
|
|
||||||
654
app/sources.py
654
app/sources.py
|
|
@ -2,22 +2,16 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import html
|
|
||||||
import io
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
from datetime import datetime, timezone
|
||||||
import re
|
|
||||||
import time
|
|
||||||
import zipfile
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
from email.utils import parsedate_to_datetime
|
from email.utils import parsedate_to_datetime
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import feedparser
|
import feedparser
|
||||||
import nats
|
import nats
|
||||||
|
|
||||||
from config import NATS_URL, OSINT_USER_AGENT
|
from config import NATS_URL
|
||||||
from upstream_cache import rss_cache
|
from upstream_cache import rss_cache
|
||||||
|
|
||||||
logger = logging.getLogger("osint.sources")
|
logger = logging.getLogger("osint.sources")
|
||||||
|
|
@ -32,75 +26,26 @@ def _parse_rfc822(date_str: object) -> str | None:
|
||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
# NATS connection
|
||||||
NATS_URLS = NATS_URL
|
NATS_URLS = NATS_URL
|
||||||
_nc = None
|
|
||||||
|
|
||||||
|
|
||||||
async def _jetstream():
|
|
||||||
"""Reuse one NATS connection across publishes (no connect/close per event)."""
|
|
||||||
global _nc
|
|
||||||
if _nc is None or _nc.is_closed:
|
|
||||||
_nc = await nats.connect(NATS_URLS)
|
|
||||||
return _nc.jetstream()
|
|
||||||
|
|
||||||
|
|
||||||
async def publish_event(subject: str, event: dict):
|
async def publish_event(subject: str, event: dict):
|
||||||
"""Publish an event to NATS JetStream."""
|
"""Publish an event to NATS JetStream."""
|
||||||
js = await _jetstream()
|
nc = await nats.connect(NATS_URLS)
|
||||||
|
js = nc.jetstream()
|
||||||
await js.publish(subject, json.dumps(event).encode())
|
await js.publish(subject, json.dumps(event).encode())
|
||||||
|
await nc.close()
|
||||||
logger.debug("Published event to %s", subject)
|
logger.debug("Published event to %s", subject)
|
||||||
|
|
||||||
|
|
||||||
def event_dedup_key(msg: dict) -> str | None:
|
|
||||||
"""Natural key for generic events. URL when present; else None (always insert)."""
|
|
||||||
url = msg.get("url")
|
|
||||||
if not isinstance(url, str):
|
|
||||||
return None
|
|
||||||
url = url.strip()
|
|
||||||
return url or None
|
|
||||||
|
|
||||||
|
|
||||||
async def existing_event_urls(urls: list[str]) -> set[str]:
|
|
||||||
"""URLs already claimed in event_dedup. Empty input -> empty set."""
|
|
||||||
if not urls:
|
|
||||||
return set()
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
from database import async_session
|
|
||||||
from models import event_dedup as event_dedup_table
|
|
||||||
|
|
||||||
async with async_session() as session:
|
|
||||||
result = await session.execute(
|
|
||||||
select(event_dedup_table.c.url).where(event_dedup_table.c.url.in_(urls))
|
|
||||||
)
|
|
||||||
return {row[0] for row in result}
|
|
||||||
|
|
||||||
|
|
||||||
async def _publish_unknown(subject: str, events: list[dict]) -> int:
|
|
||||||
"""Publish only events whose URL is not already in event_dedup."""
|
|
||||||
keys = [event_dedup_key(e) for e in events]
|
|
||||||
known = await existing_event_urls([k for k in keys if k])
|
|
||||||
published = 0
|
|
||||||
for event, key in zip(events, keys):
|
|
||||||
if key and key in known:
|
|
||||||
continue
|
|
||||||
await publish_event(subject, event)
|
|
||||||
published += 1
|
|
||||||
return published
|
|
||||||
|
|
||||||
|
|
||||||
def _ua_headers() -> dict[str, str]:
|
|
||||||
return {"User-Agent": OSINT_USER_AGENT}
|
|
||||||
|
|
||||||
|
|
||||||
# ─── RSS Feed Ingestor ──────────────────────────────────────────────────
|
# ─── RSS Feed Ingestor ──────────────────────────────────────────────────
|
||||||
|
|
||||||
async def ingest_rss_feed(feed_url: str, source_id: str | None = None):
|
async def ingest_rss_feed(feed_url: str, source_id: str | None = None):
|
||||||
"""Fetch and parse an RSS feed, publish items to NATS."""
|
"""Fetch and parse an RSS feed, publish items to NATS."""
|
||||||
text = rss_cache.get(feed_url)
|
text = rss_cache.get(feed_url)
|
||||||
if text is None:
|
if text is None:
|
||||||
async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client:
|
async with httpx.AsyncClient(timeout=30) as client:
|
||||||
resp = await client.get(feed_url)
|
resp = await client.get(feed_url)
|
||||||
resp.raise_for_status()
|
resp.raise_for_status()
|
||||||
text = resp.text
|
text = resp.text
|
||||||
|
|
@ -131,403 +76,51 @@ async def ingest_rss_feed(feed_url: str, source_id: str | None = None):
|
||||||
return count
|
return count
|
||||||
|
|
||||||
|
|
||||||
# ─── GDELT 2.0 DOC API ──────────────────────────────────────────────────
|
# ─── GDELT 2.0 Ingestor ─────────────────────────────────────────────────
|
||||||
|
|
||||||
GDELT_API = "https://api.gdeltproject.org/api/v2/doc/doc"
|
GDELT_API = "https://api.gdeltproject.org/gdeltv2"
|
||||||
GDELT_DEFAULT_QUERY = '(unrest OR protest OR outage OR cyber OR "power outage")'
|
|
||||||
|
|
||||||
|
|
||||||
def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]:
|
|
||||||
"""DOC 2.0 query string (not the retired gdeltv2 ``search`` param)."""
|
|
||||||
q = (query or "").strip() or GDELT_DEFAULT_QUERY
|
|
||||||
return {
|
|
||||||
"query": q,
|
|
||||||
"mode": "ArtList",
|
|
||||||
"format": "json",
|
|
||||||
"maxrecords": str(int(max_articles)),
|
|
||||||
"timespan": "1d",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# 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:
|
|
||||||
return datetime.strptime(value[:15], "%Y%m%dT%H%M%S").replace(
|
|
||||||
tzinfo=timezone.utc
|
|
||||||
).isoformat()
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
return datetime.now(timezone.utc).isoformat()
|
|
||||||
|
|
||||||
|
|
||||||
def parse_gdelt_articles(data: dict) -> list[dict]:
|
|
||||||
events = []
|
|
||||||
for article in data.get("articles") or []:
|
|
||||||
if not isinstance(article, dict):
|
|
||||||
continue
|
|
||||||
url = article.get("url")
|
|
||||||
if not url:
|
|
||||||
continue
|
|
||||||
events.append({
|
|
||||||
"source_type": "gdel-t2",
|
|
||||||
"title": article.get("title"),
|
|
||||||
"body": article.get("domain") or article.get("language"),
|
|
||||||
"url": url,
|
|
||||||
"location_name": article.get("sourcecountry"),
|
|
||||||
"source_timestamp": _parse_gdelt_seendate(article.get("seendate")),
|
|
||||||
"tags": [t for t in (article.get("language"), article.get("sourcecountry")) if t],
|
|
||||||
"raw": article,
|
|
||||||
})
|
|
||||||
return events
|
|
||||||
|
|
||||||
|
|
||||||
async def _ingest_gdelt_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
|
|
||||||
|
|
||||||
params = gdelt_params(query=query, max_articles=max_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
|
|
||||||
|
|
||||||
_gdelt_clear_backoff()
|
|
||||||
events = parse_gdelt_articles(data if isinstance(data, dict) else {})
|
|
||||||
for event in events:
|
|
||||||
await publish_event("events.gdelt", event)
|
|
||||||
logger.info("Ingested %d articles from GDELT", len(events))
|
|
||||||
return len(events)
|
|
||||||
|
|
||||||
|
|
||||||
# ─── GDELT 2.0 15-minute bulk files (throttle-free) ─────────────────────
|
|
||||||
#
|
|
||||||
# The DOC 2.0 API is per-IP quota'd (429, no Retry-After). The same coverage is
|
|
||||||
# published every 15 minutes as static files under /gdeltv2/ with no key and no
|
|
||||||
# quota, indexed by ``lastupdate.txt``:
|
|
||||||
# *.export.CSV.zip events (CAMEO codes)
|
|
||||||
# *.mentions.CSV.zip event->article mentions (URL + confidence, no title)
|
|
||||||
# *.gkg.csv.zip Global Knowledge Graph, one row per article: URL, source
|
|
||||||
# domain, themes, locations with lat/lon, tone, and the
|
|
||||||
# page title in the V2ExtrasXML column
|
|
||||||
# GKG is the one that carries title + geo, so map a filtered row into the same
|
|
||||||
# event shape ``parse_gdelt_articles`` produces and let the existing
|
|
||||||
# ``events.gdelt`` NATS consumer + ``event_dedup`` (URL) keep working.
|
|
||||||
|
|
||||||
GDELT_BULK_ENABLED = os.getenv("GDELT_BULK_ENABLED", "1").lower() in ("1", "true", "yes")
|
|
||||||
GDELT_BULK_LASTUPDATE = os.getenv(
|
|
||||||
"GDELT_BULK_LASTUPDATE", "https://data.gdeltproject.org/gdeltv2/lastupdate.txt"
|
|
||||||
)
|
|
||||||
GDELT_BULK_MAX_EVENTS = int(os.getenv("GDELT_BULK_MAX_EVENTS", "100"))
|
|
||||||
|
|
||||||
# Newest bulk file already parsed; lastupdate.txt is re-read every cycle but the
|
|
||||||
# 15-minute file behind it only changes 4x/hour.
|
|
||||||
_gdelt_bulk_last_file: str | None = None
|
|
||||||
|
|
||||||
_PAGE_TITLE_RE = re.compile(r"<PAGE_TITLE>(.*?)</PAGE_TITLE>", re.DOTALL)
|
|
||||||
_PAGE_PUB_TS_RE = re.compile(r"<PAGE_PRECISEPUBTIMESTAMP>(\d{14})<")
|
|
||||||
|
|
||||||
|
|
||||||
def gdelt_query_terms(query: str = "") -> list[str]:
|
|
||||||
"""CONFIG GDELT query (``(unrest OR protest OR ...)``) -> plain terms.
|
|
||||||
|
|
||||||
Used to filter bulk rows against their GKG theme tokens instead of
|
|
||||||
publishing every article in the 15-minute window.
|
|
||||||
"""
|
|
||||||
q = (query or "").strip() or GDELT_DEFAULT_QUERY
|
|
||||||
terms: list[str] = []
|
|
||||||
for part in re.split(r"\s+OR\s+", q.strip().strip("()"), flags=re.IGNORECASE):
|
|
||||||
term = part.strip().strip('"').strip("'").strip().lower()
|
|
||||||
if term and term not in terms:
|
|
||||||
terms.append(term)
|
|
||||||
return terms
|
|
||||||
|
|
||||||
|
|
||||||
def _term_hits_themes(term: str, themes: str) -> bool:
|
|
||||||
"""Term matches when every word of it appears in the theme token list."""
|
|
||||||
words = [w for w in re.split(r"[\s_\-]+", term) if w]
|
|
||||||
return bool(words) and all(w in themes for w in words)
|
|
||||||
|
|
||||||
|
|
||||||
def select_gdelt_bulk_url(lastupdate_text: str) -> tuple[str, str] | None:
|
|
||||||
"""``(filename, https_url)`` of the newest GKG file in lastupdate.txt.
|
|
||||||
|
|
||||||
lastupdate.txt lists plain ``http://`` URLs, which 301 to https; normalise
|
|
||||||
so the fetch never follows a redirect into a stale mirror.
|
|
||||||
"""
|
|
||||||
for line in (lastupdate_text or "").splitlines():
|
|
||||||
parts = line.split()
|
|
||||||
if len(parts) < 3 or not parts[2].endswith(".gkg.csv.zip"):
|
|
||||||
continue
|
|
||||||
url = parts[2]
|
|
||||||
if url.startswith("http://"):
|
|
||||||
url = "https://" + url[len("http://"):]
|
|
||||||
return url.rsplit("/", 1)[-1], url
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _gkg_location(field: str) -> tuple[float | None, float | None, str | None]:
|
|
||||||
"""First location in a V2Locations field -> (lat, lon, name).
|
|
||||||
|
|
||||||
V2Locations is ``type#fullname#cc#adm1[#adm2]#lat#lon#featureid``; the
|
|
||||||
adm2 slot is sometimes dropped, so read the triple from the end.
|
|
||||||
"""
|
|
||||||
segment = (field or "").split(";", 1)[0]
|
|
||||||
parts = segment.split("#")
|
|
||||||
if len(parts) < 5:
|
|
||||||
return None, None, None
|
|
||||||
name = parts[1].strip() or None
|
|
||||||
try:
|
|
||||||
lat = float(parts[-3])
|
|
||||||
lon = float(parts[-2])
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return None, None, name
|
|
||||||
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
|
||||||
return None, None, name
|
|
||||||
return lat, lon, name
|
|
||||||
|
|
||||||
|
|
||||||
def _gkg_tone(field: str) -> float | None:
|
|
||||||
try:
|
|
||||||
return _parse_gdelt_tone(field.split(",", 1)[0])
|
|
||||||
except (AttributeError, IndexError):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _gkg_timestamp(row: list[str], extras: str) -> str:
|
|
||||||
"""Article publish time: PAGE_PRECISEPUBTIMESTAMP, else the GKG window stamp."""
|
|
||||||
stamps = []
|
|
||||||
pub = _PAGE_PUB_TS_RE.search(extras)
|
|
||||||
if pub is not None:
|
|
||||||
stamps.append(pub.group(1))
|
|
||||||
if len(row) > 1 and isinstance(row[1], str):
|
|
||||||
stamps.append(row[1][:14])
|
|
||||||
for stamp in stamps:
|
|
||||||
try:
|
|
||||||
return datetime.strptime(stamp, "%Y%m%d%H%M%S").replace(
|
|
||||||
tzinfo=timezone.utc
|
|
||||||
).isoformat()
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
return datetime.now(timezone.utc).isoformat()
|
|
||||||
|
|
||||||
|
|
||||||
def parse_gkg_row(row: list[str], terms: list[str], bulk_file: str = "") -> dict | None:
|
|
||||||
"""Map one GKG CSV row into the ``events.gdelt`` event shape.
|
|
||||||
|
|
||||||
Returns None when the row has no usable URL or matches none of ``terms``.
|
|
||||||
"""
|
|
||||||
if len(row) < 8:
|
|
||||||
return None
|
|
||||||
url = (row[4] or "").strip()
|
|
||||||
if not url.startswith(("http://", "https://")):
|
|
||||||
return None
|
|
||||||
|
|
||||||
raw_themes = row[7] or ""
|
|
||||||
themes = raw_themes.lower()
|
|
||||||
matched = [t for t in terms if _term_hits_themes(t, themes)]
|
|
||||||
if not matched:
|
|
||||||
return None
|
|
||||||
|
|
||||||
extras = row[-1] if isinstance(row[-1], str) else ""
|
|
||||||
title_match = _PAGE_TITLE_RE.search(extras)
|
|
||||||
title = html.unescape(title_match.group(1)).strip() if title_match else None
|
|
||||||
|
|
||||||
lat = lon = loc_name = None
|
|
||||||
for idx in (9, 10):
|
|
||||||
if idx < len(row):
|
|
||||||
lat, lon, loc_name = _gkg_location(row[idx])
|
|
||||||
if lat is not None:
|
|
||||||
break
|
|
||||||
|
|
||||||
theme_tokens = [t for t in raw_themes.split(";") if t]
|
|
||||||
tags = matched + [
|
|
||||||
t for t in theme_tokens
|
|
||||||
if any(w in t.lower() for w in matched)
|
|
||||||
]
|
|
||||||
tags = list(dict.fromkeys(tags))[:10]
|
|
||||||
|
|
||||||
return {
|
|
||||||
"source_type": "gdel-t2",
|
|
||||||
"title": title,
|
|
||||||
"body": (row[3] or "").strip() or None,
|
|
||||||
"url": url,
|
|
||||||
"location_lat": lat,
|
|
||||||
"location_lon": lon,
|
|
||||||
"location_name": loc_name,
|
|
||||||
"source_timestamp": _gkg_timestamp(row, extras),
|
|
||||||
"tags": tags,
|
|
||||||
"raw": {
|
|
||||||
"gkg_record_id": row[0],
|
|
||||||
"source_common_name": row[3],
|
|
||||||
"source_collection": row[2],
|
|
||||||
"themes": theme_tokens[:12],
|
|
||||||
"tone": _gkg_tone(row[15]) if len(row) > 15 else None,
|
|
||||||
"bulk_file": bulk_file,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def ingest_gdelt_bulk(query: str = "", max_events: int | None = None) -> int:
|
|
||||||
"""Publish new articles from the newest 15-minute GKG bulk file.
|
|
||||||
|
|
||||||
No API key, no per-IP quota, and the existing URL dedupe means re-reading
|
|
||||||
the same file after a restart publishes nothing new.
|
|
||||||
"""
|
|
||||||
global _gdelt_bulk_last_file
|
|
||||||
cap = GDELT_BULK_MAX_EVENTS if max_events is None else max_events
|
|
||||||
|
|
||||||
async with httpx.AsyncClient(
|
|
||||||
timeout=120, headers=_ua_headers(), follow_redirects=True,
|
|
||||||
) as client:
|
|
||||||
index = await client.get(GDELT_BULK_LASTUPDATE)
|
|
||||||
index.raise_for_status()
|
|
||||||
picked = select_gdelt_bulk_url(index.text)
|
|
||||||
if picked is None:
|
|
||||||
logger.warning("GDELT bulk: no .gkg file listed in lastupdate.txt")
|
|
||||||
return 0
|
|
||||||
filename, url = picked
|
|
||||||
if filename == _gdelt_bulk_last_file:
|
|
||||||
logger.debug("GDELT bulk: %s already ingested; nothing new", filename)
|
|
||||||
return 0
|
|
||||||
archive = await client.get(url)
|
|
||||||
archive.raise_for_status()
|
|
||||||
|
|
||||||
terms = gdelt_query_terms(query)
|
|
||||||
events: list[dict] = []
|
|
||||||
scanned = 0
|
|
||||||
with zipfile.ZipFile(io.BytesIO(archive.content)) as zf:
|
|
||||||
member = zf.namelist()[0]
|
|
||||||
with zf.open(member) as fh:
|
|
||||||
for line in io.TextIOWrapper(fh, encoding="utf-8", errors="replace"):
|
|
||||||
if not line.strip():
|
|
||||||
continue
|
|
||||||
scanned += 1
|
|
||||||
event = parse_gkg_row(line.rstrip("\r\n").split("\t"), terms, filename)
|
|
||||||
if event is not None and len(events) < cap:
|
|
||||||
events.append(event)
|
|
||||||
|
|
||||||
published = await _publish_unknown("events.gdelt", events)
|
|
||||||
_gdelt_bulk_last_file = filename
|
|
||||||
logger.info(
|
|
||||||
"GDELT bulk %s: %d/%d rows matched %s, %d new articles published",
|
|
||||||
filename, len(events), scanned, "/".join(terms), published,
|
|
||||||
)
|
|
||||||
return published
|
|
||||||
|
|
||||||
|
|
||||||
async def ingest_gdelt(query: str = "", max_articles: int = 50):
|
async def ingest_gdelt(query: str = "", max_articles: int = 50):
|
||||||
"""GDELT articles: throttle-free 15-minute bulk file first, DOC API fallback.
|
"""Fetch articles from GDELT 2.0 API."""
|
||||||
|
params = {
|
||||||
|
"mode": "artlist",
|
||||||
|
"format": "json",
|
||||||
|
"maxrecords": max_articles,
|
||||||
|
"mode": "artlist",
|
||||||
|
}
|
||||||
|
if query:
|
||||||
|
params["search"] = query
|
||||||
|
|
||||||
The bulk path carries the coverage; the DOC 2.0 call (with its 429 backoff)
|
async with httpx.AsyncClient(timeout=60) as client:
|
||||||
only runs when the bulk fetch itself fails, so the per-IP quota is no longer
|
resp = await client.get(GDELT_API, params=params)
|
||||||
on the hot path.
|
resp.raise_for_status()
|
||||||
"""
|
data = resp.json()
|
||||||
if GDELT_BULK_ENABLED:
|
|
||||||
try:
|
count = 0
|
||||||
return await ingest_gdelt_bulk(query=query)
|
for article in data.get("articles", []):
|
||||||
except Exception as exc: # noqa: BLE001 — any bulk failure falls back
|
event = {
|
||||||
logger.warning(
|
"source_type": "gdel-t2",
|
||||||
"GDELT bulk fetch failed (%s: %s); falling back to DOC API",
|
"title": article.get("title"),
|
||||||
type(exc).__name__, str(exc)[:160],
|
"body": article.get("articleBody"),
|
||||||
)
|
"url": article.get("url"),
|
||||||
return await _ingest_gdelt_doc(query=query, max_articles=max_articles)
|
"sentiment_score": _parse_gdelt_tone(article.get("Tone", "0")),
|
||||||
|
"location_lat": article.get("Latitude"),
|
||||||
|
"location_lon": article.get("Longitude"),
|
||||||
|
"location_name": article.get("Location"),
|
||||||
|
"source_timestamp": article.get("FirstCreated"),
|
||||||
|
"entities": [
|
||||||
|
{"name": e.get("Topic"), "type": "topic"}
|
||||||
|
for e in article.get("Mentions", [])
|
||||||
|
if e.get("Topic")
|
||||||
|
],
|
||||||
|
"raw": article,
|
||||||
|
}
|
||||||
|
await publish_event("events.gdelt", event)
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
logger.info("Ingested %d articles from GDELT", count)
|
||||||
|
return count
|
||||||
|
|
||||||
|
|
||||||
def _parse_gdelt_tone(tone: str) -> float | None:
|
def _parse_gdelt_tone(tone: str) -> float | None:
|
||||||
|
|
@ -544,45 +137,34 @@ def _parse_gdelt_tone(tone: str) -> float | None:
|
||||||
USGS_API = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson"
|
USGS_API = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson"
|
||||||
|
|
||||||
|
|
||||||
def parse_usgs_feature(feature: dict) -> dict:
|
|
||||||
"""Map one USGS GeoJSON feature, keeping the stable event id."""
|
|
||||||
props = feature.get("properties") or {}
|
|
||||||
geometry = (feature.get("geometry") or {}).get("coordinates") or []
|
|
||||||
usgs_id = feature.get("id")
|
|
||||||
url = props.get("url") or (
|
|
||||||
f"https://earthquake.usgs.gov/earthquakes/eventpage/{usgs_id}" if usgs_id else None
|
|
||||||
)
|
|
||||||
raw = dict(props)
|
|
||||||
raw["usgs_id"] = usgs_id
|
|
||||||
return {
|
|
||||||
"source_type": "earthquake",
|
|
||||||
"title": props.get("title"),
|
|
||||||
"body": props.get("description"),
|
|
||||||
"url": url,
|
|
||||||
"location_lat": geometry[1] if len(geometry) > 1 else None,
|
|
||||||
"location_lon": geometry[0] if len(geometry) > 0 else None,
|
|
||||||
"location_name": props.get("place"),
|
|
||||||
"sentiment_label": "neutral",
|
|
||||||
"tags": [f"magnitude:{props.get('mag')}"] if props.get("mag") else [],
|
|
||||||
"source_timestamp": (
|
|
||||||
datetime.utcfromtimestamp(props.get("time", 0) / 1000)
|
|
||||||
.replace(tzinfo=timezone.utc)
|
|
||||||
.isoformat()
|
|
||||||
),
|
|
||||||
"raw": raw,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def ingest_earthquakes():
|
async def ingest_earthquakes():
|
||||||
"""Fetch recent earthquakes from USGS."""
|
"""Fetch recent earthquakes from USGS."""
|
||||||
async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client:
|
async with httpx.AsyncClient(timeout=30) as client:
|
||||||
resp = await client.get(USGS_API)
|
resp = await client.get(USGS_API)
|
||||||
resp.raise_for_status()
|
resp.raise_for_status()
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
|
|
||||||
count = 0
|
count = 0
|
||||||
for feature in data.get("features", []):
|
for feature in data.get("features", []):
|
||||||
event = parse_usgs_feature(feature)
|
props = feature.get("properties", {})
|
||||||
|
geometry = feature.get("geometry", {}).get("coordinates", [])
|
||||||
|
event = {
|
||||||
|
"source_type": "earthquake",
|
||||||
|
"title": props.get("title"),
|
||||||
|
"body": props.get("description"),
|
||||||
|
"url": props.get("url"),
|
||||||
|
"location_lat": geometry[1] if len(geometry) > 1 else None,
|
||||||
|
"location_lon": geometry[0] if len(geometry) > 0 else None,
|
||||||
|
"location_name": props.get("place"),
|
||||||
|
"sentiment_label": "neutral",
|
||||||
|
"tags": [f"magnitude:{props.get('mag')}"] if props.get("mag") else [],
|
||||||
|
"source_timestamp": (
|
||||||
|
datetime.utcfromtimestamp(props.get("time", 0) / 1000)
|
||||||
|
.replace(tzinfo=timezone.utc)
|
||||||
|
.isoformat()
|
||||||
|
),
|
||||||
|
"raw": props,
|
||||||
|
}
|
||||||
await publish_event("events.earthquake", event)
|
await publish_event("events.earthquake", event)
|
||||||
count += 1
|
count += 1
|
||||||
|
|
||||||
|
|
@ -590,108 +172,6 @@ async def ingest_earthquakes():
|
||||||
return count
|
return count
|
||||||
|
|
||||||
|
|
||||||
# ─── NASA EONET v3 ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
EONET_API = "https://eonet.gsfc.nasa.gov/api/v3/events"
|
|
||||||
|
|
||||||
|
|
||||||
def parse_eonet_events(payload: dict) -> list[dict]:
|
|
||||||
events = []
|
|
||||||
for item in payload.get("events") or []:
|
|
||||||
if not isinstance(item, dict):
|
|
||||||
continue
|
|
||||||
eid = item.get("id")
|
|
||||||
geoms = item.get("geometry") or []
|
|
||||||
point = None
|
|
||||||
for g in geoms:
|
|
||||||
if isinstance(g, dict) and g.get("type") == "Point":
|
|
||||||
point = g
|
|
||||||
if point is None:
|
|
||||||
continue
|
|
||||||
coords = point.get("coordinates") or []
|
|
||||||
if len(coords) < 2:
|
|
||||||
continue
|
|
||||||
lon, lat = float(coords[0]), float(coords[1])
|
|
||||||
cats = item.get("categories") or []
|
|
||||||
tags = []
|
|
||||||
for c in cats:
|
|
||||||
if isinstance(c, dict) and c.get("id"):
|
|
||||||
tags.append(str(c["id"]))
|
|
||||||
url = item.get("link") or (f"https://eonet.gsfc.nasa.gov/api/v3/events/{eid}" if eid else None)
|
|
||||||
ts = point.get("date") or datetime.now(timezone.utc).isoformat()
|
|
||||||
events.append({
|
|
||||||
"source_type": "disaster",
|
|
||||||
"title": item.get("title"),
|
|
||||||
"body": ", ".join(tags) if tags else None,
|
|
||||||
"url": url,
|
|
||||||
"location_lat": lat,
|
|
||||||
"location_lon": lon,
|
|
||||||
"location_name": item.get("title"),
|
|
||||||
"tags": tags,
|
|
||||||
"source_timestamp": ts,
|
|
||||||
"raw": {**item, "eonet_id": eid},
|
|
||||||
})
|
|
||||||
return events
|
|
||||||
|
|
||||||
|
|
||||||
async def ingest_eonet():
|
|
||||||
"""Volcanoes, storms, floods, drought — gaps USGS/FIRMS don't cover."""
|
|
||||||
async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client:
|
|
||||||
resp = await client.get(EONET_API, params={"status": "open", "limit": 100})
|
|
||||||
resp.raise_for_status()
|
|
||||||
data = resp.json()
|
|
||||||
events = parse_eonet_events(data if isinstance(data, dict) else {})
|
|
||||||
published = await _publish_unknown("events.disaster", events)
|
|
||||||
logger.info("Ingested %d EONET events (%d already known)", published, len(events) - published)
|
|
||||||
return published
|
|
||||||
|
|
||||||
|
|
||||||
# ─── CISA KEV ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
CISA_KEV_API = (
|
|
||||||
"https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_cisa_kev(payload: dict) -> list[dict]:
|
|
||||||
events = []
|
|
||||||
for row in payload.get("vulnerabilities") or []:
|
|
||||||
if not isinstance(row, dict):
|
|
||||||
continue
|
|
||||||
cve = row.get("cveID")
|
|
||||||
if not cve:
|
|
||||||
continue
|
|
||||||
title = row.get("vulnerabilityName") or cve
|
|
||||||
vendor = row.get("vendorProject") or ""
|
|
||||||
product = row.get("product") or ""
|
|
||||||
events.append({
|
|
||||||
"source_type": "disaster",
|
|
||||||
"title": f"{cve}: {title}",
|
|
||||||
"body": row.get("shortDescription") or f"{vendor} {product}".strip(),
|
|
||||||
"url": f"https://nvd.nist.gov/vuln/detail/{cve}",
|
|
||||||
"location_lat": None,
|
|
||||||
"location_lon": None,
|
|
||||||
"location_name": None,
|
|
||||||
"tags": ["cisa-kev", cve, "ransomware" if row.get("knownRansomwareCampaignUse") == "Known" else None],
|
|
||||||
"source_timestamp": row.get("dateAdded") or datetime.now(timezone.utc).isoformat(),
|
|
||||||
"raw": {**row, "cveID": cve},
|
|
||||||
})
|
|
||||||
events[-1]["tags"] = [t for t in events[-1]["tags"] if t]
|
|
||||||
return events
|
|
||||||
|
|
||||||
|
|
||||||
async def ingest_cisa_kev():
|
|
||||||
"""Exploited-in-the-wild CVEs. No fake map coords — ticker/events only."""
|
|
||||||
async with httpx.AsyncClient(timeout=30, headers=_ua_headers(), follow_redirects=True) as client:
|
|
||||||
resp = await client.get(CISA_KEV_API)
|
|
||||||
resp.raise_for_status()
|
|
||||||
data = resp.json()
|
|
||||||
events = parse_cisa_kev(data if isinstance(data, dict) else {})
|
|
||||||
published = await _publish_unknown("events.disaster", events)
|
|
||||||
logger.info("Ingested %d CISA KEV rows (%d already known)", published, len(events) - published)
|
|
||||||
return published
|
|
||||||
|
|
||||||
|
|
||||||
# ─── Social Signals (Twitter/X-like placeholder) ────────────────────────
|
# ─── Social Signals (Twitter/X-like placeholder) ────────────────────────
|
||||||
|
|
||||||
async def ingest_social_signals(query: str = "", max_items: int = 50):
|
async def ingest_social_signals(query: str = "", max_items: int = 50):
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -186,14 +186,15 @@ async def track_range() -> dict:
|
||||||
async with async_session() as session:
|
async with async_session() as session:
|
||||||
row = (await session.execute(text(
|
row = (await session.execute(text(
|
||||||
"""
|
"""
|
||||||
SELECT min(t) AS tmin, max(t) AS tmax FROM (
|
SELECT
|
||||||
SELECT min(bucket) AS t FROM vessel_tracks_1min
|
LEAST(
|
||||||
UNION ALL SELECT max(bucket) FROM vessel_tracks_1min
|
(SELECT min(bucket) FROM vessel_tracks_1min),
|
||||||
UNION ALL SELECT min(bucket) FROM aircraft_tracks_1min
|
(SELECT min(bucket) FROM aircraft_tracks_1min)
|
||||||
UNION ALL SELECT max(bucket) FROM aircraft_tracks_1min
|
) AS tmin,
|
||||||
UNION ALL SELECT min(poll_at) FROM vessels
|
GREATEST(
|
||||||
UNION ALL SELECT max(poll_at) FROM vessels
|
(SELECT max(bucket) FROM vessel_tracks_1min),
|
||||||
) s
|
(SELECT max(bucket) FROM aircraft_tracks_1min)
|
||||||
|
) AS tmax
|
||||||
"""
|
"""
|
||||||
))).mappings().first()
|
))).mappings().first()
|
||||||
if not row or row["tmin"] is None:
|
if not row or row["tmin"] is None:
|
||||||
|
|
|
||||||
671
app/vesselapi.py
671
app/vesselapi.py
|
|
@ -1,671 +0,0 @@
|
||||||
"""VesselAPI REST poller — quota-capped AIS for the Middle East (free tier 150 calls/mo).
|
|
||||||
|
|
||||||
VesselAPI and AISStream are two independent, first-class vessel providers —
|
|
||||||
not a primary/fallback pair. AISStream (WebSocket) owns live US-coast AIS;
|
|
||||||
VesselAPI (REST) covers the Strait of Hormuz (default box) where AISStream
|
|
||||||
has no coverage. Missing one key never disables the other. This worker polls
|
|
||||||
the REST ``GET /v1/location/vessels/bounding-box`` endpoint at most
|
|
||||||
``VESSELAPI_MAX_CALLS_PER_DAY`` (default 5) *successful 2xx* calls per UTC day
|
|
||||||
and upserts the results into the shared ``vessel_last_known`` store.
|
|
||||||
|
|
||||||
Idle (no crash) when VESSELAPI_API_KEY is unset. Never called from the GET
|
|
||||||
/api/vessels path — map pans must not hit upstream. One request per poll,
|
|
||||||
``pagination.limit=50``, never follow ``nextToken``, never send ``filter.sat``.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import calendar
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import os
|
|
||||||
from datetime import date, datetime, timezone
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
from sqlalchemy import Column, Date, DateTime, Integer, Table, func, select, text
|
|
||||||
|
|
||||||
from config import (
|
|
||||||
OSINT_USER_AGENT,
|
|
||||||
VESSELAPI_API_KEY,
|
|
||||||
VESSELAPI_BBOX,
|
|
||||||
VESSELAPI_INTERVAL,
|
|
||||||
VESSELAPI_MAX_CALLS_PER_DAY,
|
|
||||||
)
|
|
||||||
from database import async_session, engine, metadata
|
|
||||||
from live_layers import parse_bbox, to_marker, upsert_vessel, vessel_last_known, vessel_lock
|
|
||||||
|
|
||||||
logger = logging.getLogger("osint.vesselapi")
|
|
||||||
|
|
||||||
BASE_URL = "https://api.vesselapi.com/v1"
|
|
||||||
ENDPOINT = f"{BASE_URL}/location/vessels/bounding-box"
|
|
||||||
MAX_SPAN_DEG = 4.0 # |dLat| + |dLon| — VesselAPI 400s above this.
|
|
||||||
PAGE_LIMIT = 50 # pagination.limit; never follow nextToken on the free tier.
|
|
||||||
|
|
||||||
_client: httpx.AsyncClient | None = None
|
|
||||||
_client_lock = asyncio.Lock()
|
|
||||||
|
|
||||||
|
|
||||||
# ── Box parsing / span validation ─────────────────────────────────────────
|
|
||||||
|
|
||||||
class BboxError(ValueError):
|
|
||||||
"""A configured VesselAPI box violates the 4° span rule or is malformed."""
|
|
||||||
|
|
||||||
|
|
||||||
def validate_bbox_span(
|
|
||||||
minlat: float, minlon: float, maxlat: float, maxlon: float,
|
|
||||||
) -> None:
|
|
||||||
"""Reject boxes VesselAPI would 400 on (span > 4°, bad order, bad range)."""
|
|
||||||
if not (-90 <= minlat <= 90 and -90 <= maxlat <= 90
|
|
||||||
and -180 <= minlon <= 180 and -180 <= maxlon <= 180):
|
|
||||||
raise BboxError("coordinates out of range")
|
|
||||||
if minlat >= maxlat or minlon >= maxlon:
|
|
||||||
raise BboxError("bbox must have min < max on both axes")
|
|
||||||
dlat = abs(maxlat - minlat)
|
|
||||||
dlon = abs(maxlon - minlon)
|
|
||||||
if dlat + dlon > MAX_SPAN_DEG:
|
|
||||||
raise BboxError(
|
|
||||||
f"span |dLat|+|dLon| = {dlat + dlon:.2f}° exceeds {MAX_SPAN_DEG}° cap"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_boxes(raw: str) -> list[tuple[float, float, float, float]]:
|
|
||||||
"""Env format: ``minlat,minlon,maxlat,maxlon[; ...]`` (lat/lon order)."""
|
|
||||||
out: list[tuple[float, float, float, float]] = []
|
|
||||||
for chunk in (raw or "").split(";"):
|
|
||||||
parts = [p.strip() for p in chunk.split(",") if p.strip()]
|
|
||||||
if len(parts) != 4:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
minlat = float(parts[0])
|
|
||||||
minlon = float(parts[1])
|
|
||||||
maxlat = float(parts[2])
|
|
||||||
maxlon = float(parts[3])
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
out.append((minlat, minlon, maxlat, maxlon))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def parse_boxes_validated(raw: str) -> list[tuple[float, float, float, float]]:
|
|
||||||
"""Parse boxes, log + skip any that violate the span/order/range rules."""
|
|
||||||
valid: list[tuple[float, float, float, float]] = []
|
|
||||||
for box in parse_boxes(raw):
|
|
||||||
try:
|
|
||||||
validate_bbox_span(*box)
|
|
||||||
valid.append(box)
|
|
||||||
except BboxError as exc:
|
|
||||||
logger.warning("VesselAPI bbox %r skipped: %s", box, exc)
|
|
||||||
return valid
|
|
||||||
|
|
||||||
|
|
||||||
# ── Position → marker transform ───────────────────────────────────────────
|
|
||||||
|
|
||||||
def _f(value: object) -> float | None:
|
|
||||||
if value is None or value == "":
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
return float(value)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _s(value: object) -> str | None:
|
|
||||||
if value is None:
|
|
||||||
return None
|
|
||||||
text = str(value).strip()
|
|
||||||
return text or None
|
|
||||||
|
|
||||||
|
|
||||||
def transform_vesselapi_position(obj: dict | None) -> dict | None:
|
|
||||||
"""Map one VesselAPI position object to the shared marker contract.
|
|
||||||
|
|
||||||
Returns None for glitch rows, missing MMSI, or missing coordinates.
|
|
||||||
"""
|
|
||||||
if not obj or not isinstance(obj, dict):
|
|
||||||
return None
|
|
||||||
if obj.get("suspected_glitch") is True:
|
|
||||||
return None
|
|
||||||
mmsi = obj.get("mmsi")
|
|
||||||
if mmsi is None:
|
|
||||||
return None
|
|
||||||
lat = _f(obj.get("latitude"))
|
|
||||||
lon = _f(obj.get("longitude"))
|
|
||||||
if lat is None or lon is None:
|
|
||||||
return None
|
|
||||||
mmsi_s = str(mmsi)
|
|
||||||
name = _s(obj.get("vessel_name") or obj.get("name"))
|
|
||||||
heading = _f(obj.get("heading"))
|
|
||||||
if heading is None:
|
|
||||||
heading = _f(obj.get("cog"))
|
|
||||||
sog = _f(obj.get("sog"))
|
|
||||||
extra: dict = {
|
|
||||||
"src": "vesselapi",
|
|
||||||
"mmsi": mmsi_s,
|
|
||||||
"cog": obj.get("cog"),
|
|
||||||
"sog": obj.get("sog"),
|
|
||||||
"navstat": obj.get("nav_status"),
|
|
||||||
}
|
|
||||||
imo = obj.get("imo")
|
|
||||||
if imo:
|
|
||||||
extra["imo"] = imo
|
|
||||||
dest = _s(obj.get("dest") or obj.get("destination"))
|
|
||||||
if dest:
|
|
||||||
extra["dest"] = dest
|
|
||||||
ts = obj.get("timestamp") or obj.get("processed_timestamp")
|
|
||||||
if ts:
|
|
||||||
extra["timestamp"] = ts
|
|
||||||
return to_marker(
|
|
||||||
mmsi_s, lat, lon,
|
|
||||||
heading=heading,
|
|
||||||
speed=sog,
|
|
||||||
label=name or mmsi_s,
|
|
||||||
extra=extra,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def transform_vesselapi_payload(payload: dict | None) -> list[dict]:
|
|
||||||
"""Flatten a bounding-box response ``{vessels: [...]}`` to markers."""
|
|
||||||
if not payload or not isinstance(payload, dict):
|
|
||||||
return []
|
|
||||||
rows = payload.get("vessels") or []
|
|
||||||
out = []
|
|
||||||
for row in rows:
|
|
||||||
marker = transform_vesselapi_position(row)
|
|
||||||
if marker:
|
|
||||||
out.append(marker)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def utc_day_start(now: datetime) -> datetime:
|
|
||||||
"""Floor ``now`` to 00:00:00 UTC."""
|
|
||||||
if now.tzinfo is None:
|
|
||||||
now = now.replace(tzinfo=timezone.utc)
|
|
||||||
now = now.astimezone(timezone.utc)
|
|
||||||
return now.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
||||||
|
|
||||||
|
|
||||||
def pick_poll_at(poll_times: list[datetime], as_of: datetime) -> datetime | None:
|
|
||||||
"""Latest poll timestamp at or before ``as_of`` (DVR as-of)."""
|
|
||||||
if as_of.tzinfo is None:
|
|
||||||
as_of = as_of.replace(tzinfo=timezone.utc)
|
|
||||||
else:
|
|
||||||
as_of = as_of.astimezone(timezone.utc)
|
|
||||||
eligible: list[datetime] = []
|
|
||||||
for raw in poll_times:
|
|
||||||
ts = raw if raw.tzinfo else raw.replace(tzinfo=timezone.utc)
|
|
||||||
ts = ts.astimezone(timezone.utc)
|
|
||||||
if ts <= as_of:
|
|
||||||
eligible.append(ts)
|
|
||||||
return max(eligible) if eligible else None
|
|
||||||
|
|
||||||
|
|
||||||
def snapshot_as_of(rows: list[dict], as_of: datetime) -> list[dict]:
|
|
||||||
"""Keep only rows from the latest poll_at ≤ ``as_of``."""
|
|
||||||
chosen = pick_poll_at(
|
|
||||||
[r["poll_at"] for r in rows if r.get("poll_at") is not None],
|
|
||||||
as_of,
|
|
||||||
)
|
|
||||||
if chosen is None:
|
|
||||||
return []
|
|
||||||
out = []
|
|
||||||
for row in rows:
|
|
||||||
ts = row.get("poll_at")
|
|
||||||
if ts is None:
|
|
||||||
continue
|
|
||||||
if ts.tzinfo is None:
|
|
||||||
ts = ts.replace(tzinfo=timezone.utc)
|
|
||||||
if ts.astimezone(timezone.utc) == chosen:
|
|
||||||
out.append(row)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
# ── Durable daily quota (Postgres, survives restarts) ─────────────────────
|
|
||||||
# Mirrors keystore.api_keys: lazy CREATE TABLE IF NOT EXISTS, no alembic fork.
|
|
||||||
|
|
||||||
vesselapi_quota = Table(
|
|
||||||
"vesselapi_quota",
|
|
||||||
metadata,
|
|
||||||
Column("day", Date, primary_key=True),
|
|
||||||
Column("calls", Integer, nullable=False, server_default="0"),
|
|
||||||
Column("remaining", Integer, nullable=True),
|
|
||||||
Column("updated_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
|
|
||||||
)
|
|
||||||
|
|
||||||
_CREATE_QUOTA_SQL = text(
|
|
||||||
"""
|
|
||||||
CREATE TABLE IF NOT EXISTS vesselapi_quota (
|
|
||||||
day DATE PRIMARY KEY,
|
|
||||||
calls INTEGER NOT NULL DEFAULT 0,
|
|
||||||
remaining INTEGER,
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
)
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
|
|
||||||
_quota_lock = asyncio.Lock()
|
|
||||||
_quota_ensured = False
|
|
||||||
|
|
||||||
|
|
||||||
async def ensure_quota_table() -> None:
|
|
||||||
global _quota_ensured
|
|
||||||
if _quota_ensured:
|
|
||||||
return
|
|
||||||
async with _quota_lock:
|
|
||||||
if _quota_ensured:
|
|
||||||
return
|
|
||||||
async with engine.begin() as conn:
|
|
||||||
await conn.execute(_CREATE_QUOTA_SQL)
|
|
||||||
_quota_ensured = True
|
|
||||||
|
|
||||||
|
|
||||||
class PgQuotaStore:
|
|
||||||
"""Postgres-backed daily call counter. Injected for tests."""
|
|
||||||
|
|
||||||
async def calls_today(self, day: date) -> int:
|
|
||||||
await ensure_quota_table()
|
|
||||||
async with async_session() as session:
|
|
||||||
row = (await session.execute(
|
|
||||||
select(vesselapi_quota.c.calls).where(vesselapi_quota.c.day == day)
|
|
||||||
)).scalar()
|
|
||||||
return int(row) if row else 0
|
|
||||||
|
|
||||||
async def remaining_today(self, day: date) -> int | None:
|
|
||||||
await ensure_quota_table()
|
|
||||||
async with async_session() as session:
|
|
||||||
row = (await session.execute(
|
|
||||||
select(vesselapi_quota.c.remaining).where(vesselapi_quota.c.day == day)
|
|
||||||
)).scalar()
|
|
||||||
return int(row) if row is not None else None
|
|
||||||
|
|
||||||
async def bump(self, day: date, remaining: int | None) -> int:
|
|
||||||
await ensure_quota_table()
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
async with async_session() as session:
|
|
||||||
existing = (await session.execute(
|
|
||||||
select(vesselapi_quota.c.calls).where(vesselapi_quota.c.day == day)
|
|
||||||
)).scalar()
|
|
||||||
if existing is None:
|
|
||||||
await session.execute(
|
|
||||||
vesselapi_quota.insert().values(
|
|
||||||
day=day, calls=1, remaining=remaining, updated_at=now,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
await session.execute(
|
|
||||||
vesselapi_quota.update()
|
|
||||||
.where(vesselapi_quota.c.day == day)
|
|
||||||
.values(
|
|
||||||
calls=vesselapi_quota.c.calls + 1,
|
|
||||||
remaining=remaining,
|
|
||||||
updated_at=now,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
await session.commit()
|
|
||||||
return (int(existing) if existing else 0) + 1
|
|
||||||
|
|
||||||
|
|
||||||
# ── Daily VesselAPI snapshots (DVR as-of + survive restarts) ──────────────
|
|
||||||
# Cleared at the UTC day boundary so the table holds today's 5 polls only.
|
|
||||||
|
|
||||||
_CREATE_VESSELS_SQL = text(
|
|
||||||
"""
|
|
||||||
CREATE TABLE IF NOT EXISTS vessels (
|
|
||||||
mmsi TEXT NOT NULL,
|
|
||||||
poll_at TIMESTAMPTZ NOT NULL,
|
|
||||||
lat DOUBLE PRECISION NOT NULL,
|
|
||||||
lon DOUBLE PRECISION NOT NULL,
|
|
||||||
heading DOUBLE PRECISION,
|
|
||||||
speed DOUBLE PRECISION,
|
|
||||||
label TEXT,
|
|
||||||
extra JSONB,
|
|
||||||
PRIMARY KEY (mmsi, poll_at)
|
|
||||||
)
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
_CREATE_VESSELS_POLL_IDX = text(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_vessels_poll_at ON vessels (poll_at DESC)"
|
|
||||||
)
|
|
||||||
_CREATE_VESSELS_BBOX_IDX = text(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_vessels_bbox ON vessels (lon, lat)"
|
|
||||||
)
|
|
||||||
|
|
||||||
_vessels_lock = asyncio.Lock()
|
|
||||||
_vessels_ensured = False
|
|
||||||
|
|
||||||
|
|
||||||
async def ensure_vessels_table() -> None:
|
|
||||||
global _vessels_ensured
|
|
||||||
if _vessels_ensured:
|
|
||||||
return
|
|
||||||
async with _vessels_lock:
|
|
||||||
if _vessels_ensured:
|
|
||||||
return
|
|
||||||
async with engine.begin() as conn:
|
|
||||||
await conn.execute(_CREATE_VESSELS_SQL)
|
|
||||||
await conn.execute(_CREATE_VESSELS_POLL_IDX)
|
|
||||||
await conn.execute(_CREATE_VESSELS_BBOX_IDX)
|
|
||||||
_vessels_ensured = True
|
|
||||||
|
|
||||||
|
|
||||||
def _marker_from_vessel_row(r) -> dict:
|
|
||||||
extra = r.get("extra") or {}
|
|
||||||
if isinstance(extra, str):
|
|
||||||
try:
|
|
||||||
extra = json.loads(extra)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
extra = {}
|
|
||||||
if not isinstance(extra, dict):
|
|
||||||
extra = {}
|
|
||||||
extra.setdefault("src", "vesselapi")
|
|
||||||
poll_at = r.get("poll_at")
|
|
||||||
if poll_at is not None and hasattr(poll_at, "isoformat"):
|
|
||||||
extra["poll_at"] = poll_at.isoformat()
|
|
||||||
marker = to_marker(
|
|
||||||
str(r["id"]), r["lat"], r["lon"],
|
|
||||||
heading=r.get("heading"), speed=r.get("speed"),
|
|
||||||
label=r.get("label") or str(r["id"]),
|
|
||||||
extra=extra,
|
|
||||||
)
|
|
||||||
marker["seen_at"] = extra.get("poll_at") or datetime.now(timezone.utc).isoformat()
|
|
||||||
return marker
|
|
||||||
|
|
||||||
|
|
||||||
async def persist_vessel_snapshot(markers: list[dict], poll_at: datetime) -> None:
|
|
||||||
"""Write one VesselAPI poll into ``vessels`` (today's snapshots)."""
|
|
||||||
await ensure_vessels_table()
|
|
||||||
if not markers:
|
|
||||||
return
|
|
||||||
async with async_session() as session:
|
|
||||||
for m in markers:
|
|
||||||
vid = str(m.get("id") or "")
|
|
||||||
lat, lon = m.get("lat"), m.get("lon")
|
|
||||||
if not vid or lat is None or lon is None:
|
|
||||||
continue
|
|
||||||
extra = dict(m.get("extra") or {})
|
|
||||||
extra.setdefault("src", "vesselapi")
|
|
||||||
await session.execute(
|
|
||||||
text(
|
|
||||||
"""
|
|
||||||
INSERT INTO vessels
|
|
||||||
(mmsi, poll_at, lat, lon, heading, speed, label, extra)
|
|
||||||
VALUES
|
|
||||||
(:mmsi, :poll_at, :lat, :lon, :heading, :speed, :label,
|
|
||||||
CAST(:extra AS jsonb))
|
|
||||||
ON CONFLICT (mmsi, poll_at) DO UPDATE SET
|
|
||||||
lat = EXCLUDED.lat,
|
|
||||||
lon = EXCLUDED.lon,
|
|
||||||
heading = EXCLUDED.heading,
|
|
||||||
speed = EXCLUDED.speed,
|
|
||||||
label = EXCLUDED.label,
|
|
||||||
extra = EXCLUDED.extra
|
|
||||||
"""
|
|
||||||
),
|
|
||||||
{
|
|
||||||
"mmsi": vid,
|
|
||||||
"poll_at": poll_at,
|
|
||||||
"lat": float(lat),
|
|
||||||
"lon": float(lon),
|
|
||||||
"heading": m.get("heading"),
|
|
||||||
"speed": m.get("speed"),
|
|
||||||
"label": m.get("label") or vid,
|
|
||||||
"extra": json.dumps(extra),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
await session.commit()
|
|
||||||
|
|
||||||
|
|
||||||
async def purge_old_vessels(before: datetime | None = None) -> None:
|
|
||||||
"""Drop snapshots from before the current UTC day (or ``before``)."""
|
|
||||||
await ensure_vessels_table()
|
|
||||||
cutoff = before or utc_day_start(datetime.now(timezone.utc))
|
|
||||||
async with async_session() as session:
|
|
||||||
await session.execute(
|
|
||||||
text("DELETE FROM vessels WHERE poll_at < :cutoff"),
|
|
||||||
{"cutoff": cutoff},
|
|
||||||
)
|
|
||||||
await session.commit()
|
|
||||||
|
|
||||||
|
|
||||||
async def fetch_vessels_as_of(
|
|
||||||
ts: datetime,
|
|
||||||
bbox: str | None = None,
|
|
||||||
limit: int = 2000,
|
|
||||||
) -> list[dict]:
|
|
||||||
"""Latest VesselAPI poll at or before ``ts`` (DVR as-of, not exact minute)."""
|
|
||||||
try:
|
|
||||||
await ensure_vessels_table()
|
|
||||||
async with async_session() as session:
|
|
||||||
poll = (await session.execute(
|
|
||||||
text("SELECT max(poll_at) FROM vessels WHERE poll_at <= :ts"),
|
|
||||||
{"ts": ts},
|
|
||||||
)).scalar()
|
|
||||||
if poll is None:
|
|
||||||
return []
|
|
||||||
sql = """
|
|
||||||
SELECT mmsi AS id, lat, lon, heading, speed, label, extra, poll_at
|
|
||||||
FROM vessels
|
|
||||||
WHERE poll_at = :poll
|
|
||||||
"""
|
|
||||||
params: dict = {"poll": poll, "limit": limit}
|
|
||||||
if bbox:
|
|
||||||
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
|
|
||||||
sql += (
|
|
||||||
" AND lon BETWEEN :minlon AND :maxlon"
|
|
||||||
" AND lat BETWEEN :minlat AND :maxlat"
|
|
||||||
)
|
|
||||||
params.update(
|
|
||||||
minlon=minlon, minlat=minlat, maxlon=maxlon, maxlat=maxlat,
|
|
||||||
)
|
|
||||||
sql += " LIMIT :limit"
|
|
||||||
rows = (await session.execute(text(sql), params)).mappings().all()
|
|
||||||
return [_marker_from_vessel_row(r) for r in rows]
|
|
||||||
except Exception:
|
|
||||||
logger.exception("VesselAPI snapshot fetch failed")
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
async def hydrate_last_known() -> int:
|
|
||||||
"""Seed in-memory last-known from today's latest poll (app boot)."""
|
|
||||||
try:
|
|
||||||
rows = await fetch_vessels_as_of(datetime.now(timezone.utc))
|
|
||||||
except Exception:
|
|
||||||
logger.exception("VesselAPI hydrate failed")
|
|
||||||
return 0
|
|
||||||
if not rows:
|
|
||||||
return 0
|
|
||||||
async with vessel_lock:
|
|
||||||
for m in rows:
|
|
||||||
vid = str(m.get("id") or "")
|
|
||||||
if vid:
|
|
||||||
vessel_last_known[vid] = m
|
|
||||||
return len(rows)
|
|
||||||
|
|
||||||
|
|
||||||
# ── Budget / scheduling (pure, unit-testable) ─────────────────────────────
|
|
||||||
|
|
||||||
def days_left_in_month(now: datetime) -> int:
|
|
||||||
"""UTC days remaining in the current month, inclusive of today."""
|
|
||||||
_, last = calendar.monthrange(now.year, now.month)
|
|
||||||
return last - now.day + 1
|
|
||||||
|
|
||||||
|
|
||||||
def budget_allows(
|
|
||||||
calls_today: int,
|
|
||||||
remaining: int | None,
|
|
||||||
days_left: int,
|
|
||||||
max_per_day: int,
|
|
||||||
) -> bool:
|
|
||||||
"""True if another poll is permitted today.
|
|
||||||
|
|
||||||
Local hard cap: fewer than ``max_per_day`` successful calls today.
|
|
||||||
Monthly floor: if ``X-RateLimit-Remaining`` is known, keep at least
|
|
||||||
``max_per_day * days_left`` in reserve for the rest of the month.
|
|
||||||
"""
|
|
||||||
if calls_today >= max_per_day:
|
|
||||||
return False
|
|
||||||
if remaining is not None and remaining <= max_per_day * days_left:
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def choose_box(
|
|
||||||
boxes: list[tuple[float, float, float, float]],
|
|
||||||
calls_today: int,
|
|
||||||
max_per_day: int,
|
|
||||||
) -> int:
|
|
||||||
"""Index into ``boxes`` for the next poll.
|
|
||||||
|
|
||||||
Prefer refreshing the first (primary) box rather than spraying one call
|
|
||||||
across every region — round-robin only when the remaining daily budget is
|
|
||||||
enough to cover all boxes.
|
|
||||||
"""
|
|
||||||
if len(boxes) <= 1:
|
|
||||||
return 0
|
|
||||||
budget_left = max_per_day - calls_today
|
|
||||||
if budget_left >= len(boxes):
|
|
||||||
return calls_today % len(boxes)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
# ── HTTP / poll ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
async def _resolve_key() -> str:
|
|
||||||
from keystore import get_api_key
|
|
||||||
return (
|
|
||||||
os.getenv("VESSELAPI_API_KEY")
|
|
||||||
or VESSELAPI_API_KEY
|
|
||||||
or (await get_api_key("VESSELAPI_API_KEY"))
|
|
||||||
or ""
|
|
||||||
).strip()
|
|
||||||
|
|
||||||
|
|
||||||
async def _get_client() -> httpx.AsyncClient:
|
|
||||||
global _client
|
|
||||||
if _client is None:
|
|
||||||
async with _client_lock:
|
|
||||||
if _client is None:
|
|
||||||
_client = httpx.AsyncClient(
|
|
||||||
timeout=httpx.Timeout(15.0, connect=5.0),
|
|
||||||
follow_redirects=True,
|
|
||||||
headers={"User-Agent": OSINT_USER_AGENT, "Accept": "application/json"},
|
|
||||||
limits=httpx.Limits(max_connections=1, max_keepalive_connections=1),
|
|
||||||
)
|
|
||||||
return _client
|
|
||||||
|
|
||||||
|
|
||||||
async def close_client() -> None:
|
|
||||||
global _client
|
|
||||||
if _client is not None:
|
|
||||||
await _client.aclose()
|
|
||||||
_client = None
|
|
||||||
|
|
||||||
|
|
||||||
def _int_header(value: str | None) -> int | None:
|
|
||||||
if value is None:
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
return int(value)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
async def poll_once(store, boxes: list[tuple[float, float, float, float]], key: str) -> bool:
|
|
||||||
"""One quota-checked poll. Returns True if a successful 2xx was made.
|
|
||||||
|
|
||||||
Only successful 2xx responses count against the monthly quota; 4xx/5xx/429
|
|
||||||
are skipped without retry-storming (Retry-After respected by simply
|
|
||||||
sleeping the interval).
|
|
||||||
"""
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
today = now.date()
|
|
||||||
calls = await store.calls_today(today)
|
|
||||||
remaining = await store.remaining_today(today)
|
|
||||||
days_left = days_left_in_month(now)
|
|
||||||
if not budget_allows(calls, remaining, days_left, VESSELAPI_MAX_CALLS_PER_DAY):
|
|
||||||
logger.info(
|
|
||||||
"VesselAPI quota reached (calls_today=%d, remaining=%s, days_left=%d) — skip poll",
|
|
||||||
calls, remaining, days_left,
|
|
||||||
)
|
|
||||||
return False
|
|
||||||
|
|
||||||
idx = choose_box(boxes, calls, VESSELAPI_MAX_CALLS_PER_DAY)
|
|
||||||
minlat, minlon, maxlat, maxlon = boxes[idx]
|
|
||||||
client = await _get_client()
|
|
||||||
params = {
|
|
||||||
"filter.latBottom": str(minlat),
|
|
||||||
"filter.latTop": str(maxlat),
|
|
||||||
"filter.lonLeft": str(minlon),
|
|
||||||
"filter.lonRight": str(maxlon),
|
|
||||||
"pagination.limit": str(PAGE_LIMIT),
|
|
||||||
}
|
|
||||||
headers = {"Authorization": f"Bearer {key}"}
|
|
||||||
try:
|
|
||||||
resp = await client.get(ENDPOINT, params=params, headers=headers)
|
|
||||||
except httpx.HTTPError as exc:
|
|
||||||
logger.warning("VesselAPI request failed: %s", exc)
|
|
||||||
return False
|
|
||||||
|
|
||||||
if resp.status_code == 429:
|
|
||||||
logger.warning(
|
|
||||||
"VesselAPI rate-limited (Retry-After=%s) — skip poll",
|
|
||||||
resp.headers.get("Retry-After"),
|
|
||||||
)
|
|
||||||
return False
|
|
||||||
if resp.status_code >= 400:
|
|
||||||
logger.warning("VesselAPI HTTP %d — not counted against quota", resp.status_code)
|
|
||||||
return False
|
|
||||||
|
|
||||||
# 2xx success — counts against the monthly quota.
|
|
||||||
remaining = _int_header(resp.headers.get("X-RateLimit-Remaining"))
|
|
||||||
calls = await store.bump(today, remaining)
|
|
||||||
try:
|
|
||||||
data = resp.json()
|
|
||||||
except ValueError:
|
|
||||||
logger.warning("VesselAPI 2xx with non-JSON body — counted but ignored")
|
|
||||||
return True
|
|
||||||
markers = transform_vesselapi_payload(data)
|
|
||||||
for m in markers:
|
|
||||||
await upsert_vessel(m)
|
|
||||||
try:
|
|
||||||
await persist_vessel_snapshot(markers, now)
|
|
||||||
await purge_old_vessels(utc_day_start(now))
|
|
||||||
except Exception: # noqa: BLE001 — live overlay must not die on persist
|
|
||||||
logger.exception("VesselAPI snapshot persist failed")
|
|
||||||
logger.info(
|
|
||||||
"VesselAPI poll OK: %d vessels (remaining=%s, calls_today=%d)",
|
|
||||||
len(markers), remaining, calls,
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
# ── Worker loop ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
async def run_vesselapi_worker(store: PgQuotaStore | None = None) -> None:
|
|
||||||
"""Long-lived poll loop. Idle when the key is unset; never crashes the app."""
|
|
||||||
if store is None:
|
|
||||||
store = PgQuotaStore()
|
|
||||||
boxes = parse_boxes_validated(VESSELAPI_BBOX)
|
|
||||||
if not boxes:
|
|
||||||
logger.warning(
|
|
||||||
"VESSELAPI_BBOX has no valid boxes (span ≤ %.1f°) — poller idle", MAX_SPAN_DEG,
|
|
||||||
)
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
if not boxes:
|
|
||||||
await asyncio.sleep(VESSELAPI_INTERVAL)
|
|
||||||
continue
|
|
||||||
key = await _resolve_key()
|
|
||||||
if not key:
|
|
||||||
logger.warning(
|
|
||||||
"VESSELAPI_API_KEY not set — VesselAPI poller idle. "
|
|
||||||
"Create a free key at https://dashboard.vesselapi.com/"
|
|
||||||
)
|
|
||||||
await asyncio.sleep(VESSELAPI_INTERVAL)
|
|
||||||
continue
|
|
||||||
await poll_once(store, boxes, key)
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
raise
|
|
||||||
except Exception: # noqa: BLE001 — keep the loop alive across transient failures
|
|
||||||
logger.exception("VesselAPI poll error")
|
|
||||||
await asyncio.sleep(VESSELAPI_INTERVAL)
|
|
||||||
|
|
@ -8,18 +8,10 @@ from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import UUID
|
|
||||||
|
|
||||||
BBox = tuple[float, float, float, float] # minlon, minlat, maxlon, maxlat
|
BBox = tuple[float, float, float, float] # minlon, minlat, maxlon, maxlat
|
||||||
|
|
||||||
|
|
||||||
def _uuid_str(value: object) -> str | None:
|
|
||||||
try:
|
|
||||||
return str(UUID(str(value)))
|
|
||||||
except (ValueError, TypeError, AttributeError):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def point_in_bbox(lon: float, lat: float, bbox: BBox | None) -> bool:
|
def point_in_bbox(lon: float, lat: float, bbox: BBox | None) -> bool:
|
||||||
"""True if (lon, lat) sits inside an axis-aligned viewport."""
|
"""True if (lon, lat) sits inside an axis-aligned viewport."""
|
||||||
if bbox is None:
|
if bbox is None:
|
||||||
|
|
@ -34,7 +26,6 @@ class ConnectionManager:
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self._queues: dict[str, asyncio.Queue] = {}
|
self._queues: dict[str, asyncio.Queue] = {}
|
||||||
self._viewports: dict[str, BBox] = {}
|
self._viewports: dict[str, BBox] = {}
|
||||||
self._watched: dict[str, set[str]] = {}
|
|
||||||
|
|
||||||
def register(self, client_id: str, maxsize: int = 256) -> asyncio.Queue:
|
def register(self, client_id: str, maxsize: int = 256) -> asyncio.Queue:
|
||||||
q: asyncio.Queue = asyncio.Queue(maxsize=maxsize)
|
q: asyncio.Queue = asyncio.Queue(maxsize=maxsize)
|
||||||
|
|
@ -44,21 +35,6 @@ class ConnectionManager:
|
||||||
def unregister(self, client_id: str) -> None:
|
def unregister(self, client_id: str) -> None:
|
||||||
self._queues.pop(client_id, None)
|
self._queues.pop(client_id, None)
|
||||||
self._viewports.pop(client_id, None)
|
self._viewports.pop(client_id, None)
|
||||||
self._watched.pop(client_id, None)
|
|
||||||
|
|
||||||
def set_watched_geofences(self, client_id: str, ids: list[str]) -> None:
|
|
||||||
"""Watch these fence UUIDs so geofence_alert delivers off-viewport.
|
|
||||||
|
|
||||||
Invalid UUIDs are ignored. Empty list = watch none (viewport-only).
|
|
||||||
"""
|
|
||||||
if client_id not in self._queues:
|
|
||||||
return
|
|
||||||
watched: set[str] = set()
|
|
||||||
for raw in ids:
|
|
||||||
uid = _uuid_str(raw)
|
|
||||||
if uid is not None:
|
|
||||||
watched.add(uid)
|
|
||||||
self._watched[client_id] = watched
|
|
||||||
|
|
||||||
def set_viewport(self, client_id: str, bbox: BBox) -> None:
|
def set_viewport(self, client_id: str, bbox: BBox) -> None:
|
||||||
if client_id in self._queues:
|
if client_id in self._queues:
|
||||||
|
|
@ -67,9 +43,6 @@ class ConnectionManager:
|
||||||
def viewport_of(self, client_id: str) -> BBox | None:
|
def viewport_of(self, client_id: str) -> BBox | None:
|
||||||
return self._viewports.get(client_id)
|
return self._viewports.get(client_id)
|
||||||
|
|
||||||
def viewports(self) -> list[BBox]:
|
|
||||||
return list(self._viewports.values())
|
|
||||||
|
|
||||||
def has_clients(self) -> bool:
|
def has_clients(self) -> bool:
|
||||||
return bool(self._queues)
|
return bool(self._queues)
|
||||||
|
|
||||||
|
|
@ -83,21 +56,13 @@ class ConnectionManager:
|
||||||
) -> int:
|
) -> int:
|
||||||
"""Enqueue `{type, payload}` for clients whose viewport contains the point.
|
"""Enqueue `{type, payload}` for clients whose viewport contains the point.
|
||||||
|
|
||||||
kind=geofence_alert also delivers when payload.geofence_id is in the
|
Drops the oldest queued message if a client's buffer is full so a slow
|
||||||
client's watch set (even if the point is off-viewport). Other kinds
|
tab cannot stall ingest. Returns the number of clients that got a copy.
|
||||||
stay viewport-only. Drops the oldest queued message if a client's
|
|
||||||
buffer is full. Returns the number of clients that got a copy.
|
|
||||||
"""
|
"""
|
||||||
msg = {"type": kind, "payload": payload}
|
msg = {"type": kind, "payload": payload}
|
||||||
sent = 0
|
sent = 0
|
||||||
gid = _uuid_str(payload.get("geofence_id")) if kind == "geofence_alert" else None
|
|
||||||
for client_id, queue in list(self._queues.items()):
|
for client_id, queue in list(self._queues.items()):
|
||||||
in_view = point_in_bbox(lon, lat, self._viewports.get(client_id))
|
if not point_in_bbox(lon, lat, self._viewports.get(client_id)):
|
||||||
if kind == "geofence_alert":
|
|
||||||
watching = gid is not None and gid in self._watched.get(client_id, set())
|
|
||||||
if not in_view and not watching:
|
|
||||||
continue
|
|
||||||
elif not in_view:
|
|
||||||
continue
|
continue
|
||||||
if queue.full():
|
if queue.full():
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
31
deploy/README.md
Normal file
31
deploy/README.md
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
# systemd unit template — copy to /etc/systemd/system/osint-masscan.service
|
||||||
|
#
|
||||||
|
# The masscan service is a CONTINUOUS rolling sweep (a full IPv4 pass at a
|
||||||
|
# conservative rate takes ~5 days), so it runs as a long-lived service, NOT a
|
||||||
|
# daily timer. The [Install] WantedBy means it starts at boot and Restart=always
|
||||||
|
# keeps it up. Install steps (run once on the Pi, as root):
|
||||||
|
#
|
||||||
|
# apt install -y masscan # or: apt-get install masscan
|
||||||
|
# mkdir -p /etc/osint-dashboard /opt/siriusdevops
|
||||||
|
# cp deploy/masscan-excludes.txt /etc/osint-dashboard/masscan-excludes.txt
|
||||||
|
#
|
||||||
|
# # Optional tuning (override env in this file; the DB_* values in the unit
|
||||||
|
# # already point at the host-published Postgres on 127.0.0.1:5432):
|
||||||
|
# cat > /etc/osint-dashboard/masscan.env <<'EOF'
|
||||||
|
# MASSCAN_RANGE=0.0.0.0/0
|
||||||
|
# MASSCAN_PORTS=554
|
||||||
|
# MASSCAN_RATE=1000
|
||||||
|
# EOF
|
||||||
|
#
|
||||||
|
# # Venv for the scanner (host-level, not the compose image):
|
||||||
|
# cd /opt/siriusdevops/osint-dashboard
|
||||||
|
# python3 -m venv .venv-masscan
|
||||||
|
# .venv-masscan/bin/pip install -r app/requirements.txt
|
||||||
|
#
|
||||||
|
# install -m 644 deploy/osint-masscan.service /etc/systemd/system/
|
||||||
|
# systemctl daemon-reload
|
||||||
|
# systemctl enable --now osint-masscan
|
||||||
|
#
|
||||||
|
# Watch: journalctl -u osint-masscan -f
|
||||||
|
# DB: writes into the same Postgres the compose stack uses (127.0.0.1:5432)
|
||||||
|
# so findings appear on the dashboard camera map automatically.
|
||||||
33
deploy/masscan-excludes.txt
Normal file
33
deploy/masscan-excludes.txt
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
# masscan excludefile — never probe these ranges.
|
||||||
|
# RFC1918 private + loopback + link-local + multicast + documentation/bogons.
|
||||||
|
# The service refuses to start if this file is missing (fail closed).
|
||||||
|
|
||||||
|
# Loopback
|
||||||
|
127.0.0.0/8
|
||||||
|
|
||||||
|
# RFC1918 private
|
||||||
|
10.0.0.0/8
|
||||||
|
172.16.0.0/12
|
||||||
|
192.168.0.0/16
|
||||||
|
|
||||||
|
# Link-local
|
||||||
|
169.254.0.0/16
|
||||||
|
|
||||||
|
# CGNAT (RFC 6598)
|
||||||
|
100.64.0.0/10
|
||||||
|
|
||||||
|
# Multicast + reserved
|
||||||
|
224.0.0.0/4
|
||||||
|
240.0.0.0/4
|
||||||
|
|
||||||
|
# Documentation / benchmark / example ranges (never real hosts)
|
||||||
|
0.0.0.0/8
|
||||||
|
192.0.2.0/24
|
||||||
|
198.51.100.0/24
|
||||||
|
203.0.113.0/24
|
||||||
|
192.0.0.0/24
|
||||||
|
198.18.0.0/15
|
||||||
|
255.255.255.255/32
|
||||||
|
|
||||||
|
# Carrier NAT / TEST-NET leftovers
|
||||||
|
233.252.0.0/24
|
||||||
29
deploy/osint-masscan.service
Normal file
29
deploy/osint-masscan.service
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
[Unit]
|
||||||
|
Description=OSINT dashboard — masscan rolling sweep (open RTSP port 554)
|
||||||
|
Documentation=https://forgejo.siriusdevops.com/sirius/osint-dashboard
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
# masscan needs raw sockets (CAP_NET_RAW) — run as root on the Pi host.
|
||||||
|
User=root
|
||||||
|
WorkingDirectory=/opt/siriusdevops/osint-dashboard
|
||||||
|
EnvironmentFile=-/etc/osint-dashboard/masscan.env
|
||||||
|
# Point at the compose-published Postgres on the HOST (127.0.0.1:5432), not the
|
||||||
|
# docker service name 'postgres' which doesn't resolve outside the compose net.
|
||||||
|
Environment=DB_HOST=127.0.0.1
|
||||||
|
Environment=DB_PORT=5432
|
||||||
|
Environment=DB_USER=osint
|
||||||
|
Environment=DB_PASSWORD=osint
|
||||||
|
Environment=DB_NAME=osint_data
|
||||||
|
Environment=MASSCAN_EXCLUDEFILE=/etc/osint-dashboard/masscan-excludes.txt
|
||||||
|
ExecStart=/opt/siriusdevops/osint-dashboard/.venv-masscan/bin/python app/run_masscan_service.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10
|
||||||
|
# Log the sweep to journald (read with: journalctl -u osint-masscan -f)
|
||||||
|
StandardOutput=journal
|
||||||
|
StandardError=journal
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
# osint.rpi.local — Sentinel-1 SAR tile proxy (/titiler/)
|
|
||||||
#
|
|
||||||
# GitOps: this file is the source of truth. On the Pi:
|
|
||||||
# sudo cp deploy/osint-titiler.nginx.conf /etc/nginx/snippets/osint-titiler.conf
|
|
||||||
# then `include snippets/osint-titiler.conf;` inside the osint.rpi.local server
|
|
||||||
# block (before `location /`), `nginx -t && systemctl reload nginx`.
|
|
||||||
#
|
|
||||||
# The browser hits /titiler/cog/tiles/... (same-origin). We strip the /titiler
|
|
||||||
# prefix so self-hosted TiTiler (127.0.0.1:8001) sees /cog/tiles/... and proxy
|
|
||||||
# its response straight back. Tiles are heavy PNGs — disable buffering so a
|
|
||||||
# slow client doesn't hold a worker open.
|
|
||||||
|
|
||||||
location /titiler/ {
|
|
||||||
proxy_pass http://127.0.0.1:8001/;
|
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
proxy_buffering off;
|
|
||||||
proxy_read_timeout 300s;
|
|
||||||
}
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
# osint.rpi.local — WebSocket upgrade for /ws/live
|
|
||||||
#
|
|
||||||
# GitOps: this file is the source of truth. On the Pi:
|
|
||||||
# sudo cp deploy/osint-ws.nginx.conf /etc/nginx/snippets/osint-ws.conf
|
|
||||||
# then `include snippets/osint-ws.conf;` inside the osint.rpi.local server
|
|
||||||
# block (before `location /`), `nginx -t && systemctl reload nginx`.
|
|
||||||
#
|
|
||||||
# Without these headers nginx proxies GET /ws/live as HTTP/1.0 → FastAPI 404
|
|
||||||
# and the HUD reconnects every few seconds.
|
|
||||||
|
|
||||||
location /ws/ {
|
|
||||||
proxy_pass http://127.0.0.1:8000;
|
|
||||||
proxy_http_version 1.1;
|
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
|
||||||
proxy_set_header Connection "upgrade";
|
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
proxy_read_timeout 3600s;
|
|
||||||
proxy_send_timeout 3600s;
|
|
||||||
proxy_buffering off;
|
|
||||||
}
|
|
||||||
|
|
@ -20,10 +20,8 @@ services:
|
||||||
# networks (and ISP abuse-mitigation blackholes) block, so rebuilding it
|
# networks (and ISP abuse-mitigation blackholes) block, so rebuilding it
|
||||||
# on every CI deploy made the pipeline flaky. Rebuild manually when the
|
# on every CI deploy made the pipeline flaky. Rebuild manually when the
|
||||||
# base image or extensions need bumping:
|
# base image or extensions need bumping:
|
||||||
# docker build -f Dockerfile.pg -t localhost/osint-dashboard-pg:latest .
|
# docker compose build db && docker compose up -d db
|
||||||
# FORCE_RECREATE_DB=1 scripts/compose-reup.sh db
|
|
||||||
image: localhost/osint-dashboard-pg:latest
|
image: localhost/osint-dashboard-pg:latest
|
||||||
pull_policy: never
|
|
||||||
container_name: osint-db
|
container_name: osint-db
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
|
|
@ -54,7 +52,6 @@ services:
|
||||||
|
|
||||||
nats:
|
nats:
|
||||||
image: nats:2.10
|
image: nats:2.10
|
||||||
pull_policy: missing
|
|
||||||
platform: linux/arm64
|
platform: linux/arm64
|
||||||
container_name: osint-nats
|
container_name: osint-nats
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
@ -70,7 +67,6 @@ services:
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
platforms: ["linux/arm64"]
|
platforms: ["linux/arm64"]
|
||||||
image: localhost/osint-dashboard:latest
|
image: localhost/osint-dashboard:latest
|
||||||
pull_policy: never
|
|
||||||
container_name: osint-ingester
|
container_name: osint-ingester
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
profiles: ["ingest"]
|
profiles: ["ingest"]
|
||||||
|
|
@ -97,15 +93,10 @@ services:
|
||||||
FIRMS_DATASETS: ${FIRMS_DATASETS:-VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT}
|
FIRMS_DATASETS: ${FIRMS_DATASETS:-VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT}
|
||||||
FIRMS_BBOX: ${FIRMS_BBOX:--180,-60,180,75}
|
FIRMS_BBOX: ${FIRMS_BBOX:--180,-60,180,75}
|
||||||
FIRMS_INTERVAL: ${FIRMS_INTERVAL:-900}
|
FIRMS_INTERVAL: ${FIRMS_INTERVAL:-900}
|
||||||
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted; [email protected])}
|
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted)}
|
||||||
AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-}
|
AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-}
|
||||||
AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66}
|
AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66}
|
||||||
AISSTREAM_IN_INGEST: ${AISSTREAM_IN_INGEST:-0}
|
AISSTREAM_IN_INGEST: ${AISSTREAM_IN_INGEST:-0}
|
||||||
VESSELAPI_API_KEY: ${VESSELAPI_API_KEY:-}
|
|
||||||
VESSELAPI_BBOX: ${VESSELAPI_BBOX:-25.5,55.4,27.3,57.2}
|
|
||||||
VESSELAPI_INTERVAL: ${VESSELAPI_INTERVAL:-17280}
|
|
||||||
VESSELAPI_MAX_CALLS_PER_DAY: ${VESSELAPI_MAX_CALLS_PER_DAY:-5}
|
|
||||||
VESSELAPI_IN_INGEST: ${VESSELAPI_IN_INGEST:-0}
|
|
||||||
command: ["python", "app/run_ingester.py"]
|
command: ["python", "app/run_ingester.py"]
|
||||||
entrypoint: ["python", "app/run_ingester.py"]
|
entrypoint: ["python", "app/run_ingester.py"]
|
||||||
|
|
||||||
|
|
@ -115,7 +106,6 @@ services:
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
platforms: ["linux/arm64"]
|
platforms: ["linux/arm64"]
|
||||||
image: localhost/osint-dashboard:latest
|
image: localhost/osint-dashboard:latest
|
||||||
pull_policy: never
|
|
||||||
container_name: osint-dashboard
|
container_name: osint-dashboard
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
depends_on:
|
depends_on:
|
||||||
|
|
@ -137,20 +127,10 @@ services:
|
||||||
FIRMS_DATASET: ${FIRMS_DATASET:-VIIRS_NOAA20_NRT}
|
FIRMS_DATASET: ${FIRMS_DATASET:-VIIRS_NOAA20_NRT}
|
||||||
FIRMS_DATASETS: ${FIRMS_DATASETS:-VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT}
|
FIRMS_DATASETS: ${FIRMS_DATASETS:-VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT}
|
||||||
FIRMS_BBOX: ${FIRMS_BBOX:--180,-60,180,75}
|
FIRMS_BBOX: ${FIRMS_BBOX:--180,-60,180,75}
|
||||||
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted; [email protected])}
|
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted)}
|
||||||
NOMINATIM_URL: ${NOMINATIM_URL:-https://nominatim.openstreetmap.org}
|
|
||||||
NOMINATIM_MIN_INTERVAL: ${NOMINATIM_MIN_INTERVAL:-1.0}
|
|
||||||
AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-}
|
AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-}
|
||||||
AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66}
|
AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66}
|
||||||
AISSTREAM_IN_APP: ${AISSTREAM_IN_APP:-1}
|
AISSTREAM_IN_APP: ${AISSTREAM_IN_APP:-1}
|
||||||
VESSELAPI_API_KEY: ${VESSELAPI_API_KEY:-}
|
|
||||||
VESSELAPI_BBOX: ${VESSELAPI_BBOX:-25.5,55.4,27.3,57.2}
|
|
||||||
VESSELAPI_INTERVAL: ${VESSELAPI_INTERVAL:-17280}
|
|
||||||
VESSELAPI_MAX_CALLS_PER_DAY: ${VESSELAPI_MAX_CALLS_PER_DAY:-5}
|
|
||||||
VESSELAPI_IN_APP: ${VESSELAPI_IN_APP:-1}
|
|
||||||
# ── Self-hosted TiTiler (Sentinel-1 SAR tiles) ──
|
|
||||||
TITILER_PUBLIC_BASE: ${TITILER_PUBLIC_BASE:-/titiler}
|
|
||||||
TITILER_INTERNAL_URL: ${TITILER_INTERNAL_URL:-http://titiler:8000}
|
|
||||||
ports:
|
ports:
|
||||||
- "127.0.0.1:8000:8000"
|
- "127.0.0.1:8000:8000"
|
||||||
deploy:
|
deploy:
|
||||||
|
|
@ -163,35 +143,12 @@ services:
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 5
|
retries: 5
|
||||||
|
|
||||||
# ── Self-hosted TiTiler (Sentinel-1 SAR COG → XYZ tiles) ────────────────
|
|
||||||
# Warps the signed Planetary Computer COG into WebMercator XYZ tiles so the
|
|
||||||
# browser never loads a multi-GB GeoTIFF. The FastAPI app signs the COG URL
|
|
||||||
# and returns a /titiler/... template; nginx routes /titiler/ here.
|
|
||||||
# Listens on 8000 INSIDE the container (the app already owns host 8000);
|
|
||||||
# published on host loopback 127.0.0.1:8001 only.
|
|
||||||
titiler:
|
|
||||||
image: ghcr.io/developmentseed/titiler:latest@sha256:1809958d063543e3ec858259536002b2de78e9f8f09a22a8d9591bdc2b550b14
|
|
||||||
pull_policy: missing
|
|
||||||
container_name: osint-titiler
|
|
||||||
platform: linux/arm64
|
|
||||||
restart: unless-stopped
|
|
||||||
environment:
|
|
||||||
- PORT=8000
|
|
||||||
- WORKERS_PER_CORE=1
|
|
||||||
ports:
|
|
||||||
- "127.0.0.1:8001:8000"
|
|
||||||
deploy:
|
|
||||||
resources:
|
|
||||||
limits:
|
|
||||||
memory: 1G
|
|
||||||
|
|
||||||
camera-service:
|
camera-service:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
platforms: ["linux/arm64"]
|
platforms: ["linux/arm64"]
|
||||||
image: localhost/osint-dashboard:latest
|
image: localhost/osint-dashboard:latest
|
||||||
pull_policy: never
|
|
||||||
container_name: osint-camera-scraper
|
container_name: osint-camera-scraper
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
profiles: ["ingest"]
|
profiles: ["ingest"]
|
||||||
|
|
@ -219,7 +176,7 @@ services:
|
||||||
volumes:
|
volumes:
|
||||||
- camera-snapshots:/data/snapshots
|
- camera-snapshots:/data/snapshots
|
||||||
|
|
||||||
# ── News pipeline: continuous scraper + 15-min summarizer ───────────────
|
# ── News pipeline: hourly scraper (:00) + summarizer (:05) ───────────────
|
||||||
# Both services point at the EXISTING osint-db (tables articles +
|
# Both services point at the EXISTING osint-db (tables articles +
|
||||||
# article_summaries, created by idempotent alembic migration 003_news).
|
# article_summaries, created by idempotent alembic migration 003_news).
|
||||||
# Scheduling replaces the upstream k8s CronJobs with in-compose wall-clock
|
# Scheduling replaces the upstream k8s CronJobs with in-compose wall-clock
|
||||||
|
|
@ -230,7 +187,6 @@ services:
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
platforms: ["linux/arm64"]
|
platforms: ["linux/arm64"]
|
||||||
image: localhost/osint-news-scraper:latest
|
image: localhost/osint-news-scraper:latest
|
||||||
pull_policy: never
|
|
||||||
container_name: osint-news-scraper
|
container_name: osint-news-scraper
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
profiles: ["ingest"]
|
profiles: ["ingest"]
|
||||||
|
|
@ -244,7 +200,7 @@ services:
|
||||||
DB_PORT: ${DB_PORT:-5432}
|
DB_PORT: ${DB_PORT:-5432}
|
||||||
DB_NAME: ${DB_NAME:-osint_data}
|
DB_NAME: ${DB_NAME:-osint_data}
|
||||||
LOG_LEVEL: ${NEWS_LOG_LEVEL:-INFO}
|
LOG_LEVEL: ${NEWS_LOG_LEVEL:-INFO}
|
||||||
NEWS_SCRAPE_INTERVAL_S: ${NEWS_SCRAPE_INTERVAL_S:-10}
|
NEWS_SCRAPE_MINUTE: ${NEWS_SCRAPE_MINUTE:-0}
|
||||||
NEWS_SCRAPE_RUN_ON_START: ${NEWS_SCRAPE_RUN_ON_START:-1}
|
NEWS_SCRAPE_RUN_ON_START: ${NEWS_SCRAPE_RUN_ON_START:-1}
|
||||||
# Override the image ENTRYPOINT ["scrapy"] with the scheduler loop.
|
# Override the image ENTRYPOINT ["scrapy"] with the scheduler loop.
|
||||||
entrypoint: []
|
entrypoint: []
|
||||||
|
|
@ -256,7 +212,6 @@ services:
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
platforms: ["linux/arm64"]
|
platforms: ["linux/arm64"]
|
||||||
image: localhost/osint-news-summarizer:latest
|
image: localhost/osint-news-summarizer:latest
|
||||||
pull_policy: never
|
|
||||||
container_name: osint-news-summarizer
|
container_name: osint-news-summarizer
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
profiles: ["ingest"]
|
profiles: ["ingest"]
|
||||||
|
|
@ -269,19 +224,14 @@ services:
|
||||||
DB_HOST: db
|
DB_HOST: db
|
||||||
DB_PORT: ${DB_PORT:-5432}
|
DB_PORT: ${DB_PORT:-5432}
|
||||||
DB_NAME: ${DB_NAME:-osint_data}
|
DB_NAME: ${DB_NAME:-osint_data}
|
||||||
NOUS_API_KEY: ${NOUS_API_KEY:-}
|
# Required to do real work; unset → the loop logs and idles.
|
||||||
NOUS_BASE_URL: ${NOUS_BASE_URL:-https://inference-api.nousresearch.com/v1}
|
GEMINI_API_KEY: ${GEMINI_API_KEY:-}
|
||||||
SUMMARY_MODEL: ${SUMMARY_MODEL:-}
|
SUMMARY_MODEL: ${SUMMARY_MODEL:-gemini-2.0-flash}
|
||||||
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard-news-summarizer}
|
|
||||||
BATCH_SIZE: ${NEWS_BATCH_SIZE:-50}
|
BATCH_SIZE: ${NEWS_BATCH_SIZE:-50}
|
||||||
SUMMARY_WINDOW_MINUTES: ${SUMMARY_WINDOW_MINUTES:-15}
|
SUMMARY_WINDOW_HOURS: ${SUMMARY_WINDOW_HOURS:-1}
|
||||||
INCLUDE_FUTURES: ${INCLUDE_FUTURES:-0}
|
INCLUDE_FUTURES: ${INCLUDE_FUTURES:-0}
|
||||||
NEWS_SUMMARIZE_INTERVAL_S: ${NEWS_SUMMARIZE_INTERVAL_S:-900}
|
NEWS_SUMMARIZE_MINUTE: ${NEWS_SUMMARIZE_MINUTE:-5}
|
||||||
NEWS_SUMMARIZE_RUN_ON_START: ${NEWS_SUMMARIZE_RUN_ON_START:-1}
|
NEWS_SUMMARIZE_RUN_ON_START: ${NEWS_SUMMARIZE_RUN_ON_START:-1}
|
||||||
NEWS_SUMMARIZE_FORCE: ${NEWS_SUMMARIZE_FORCE:-0}
|
|
||||||
TZ: ${TZ:-America/New_York}
|
|
||||||
NEWS_RECAP_HOUR: ${NEWS_RECAP_HOUR:-23}
|
|
||||||
NEWS_RECAP_MINUTE: ${NEWS_RECAP_MINUTE:-0}
|
|
||||||
command: ["python", "run_news_summarizer.py"]
|
command: ["python", "run_news_summarizer.py"]
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
|
|
|
||||||
86
docs/auth.md
86
docs/auth.md
|
|
@ -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.
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
Builder brief for backend + frontend. Researched 2026-08-27. Every endpoint below was either live-probed from this machine or taken from the provider’s current docs. Prefer **free, no-key, CORS-open** sources first. Keys are called out explicitly.
|
Builder brief for backend + frontend. Researched 2026-08-27. Every endpoint below was either live-probed from this machine or taken from the provider’s current docs. Prefer **free, no-key, CORS-open** sources first. Keys are called out explicitly.
|
||||||
|
|
||||||
This is **not** a camera-discovery change. Existing camera rules still apply: never emit `rtsp://` hrefs; camera pins go through `/api/cameras/{id}/snapshot`; HTTP directory cams use `/stream` MJPEG.
|
This is **not** a camera-discovery / masscan change. Existing camera rules still apply: never emit `rtsp://` hrefs; masscan pins go through `/api/cameras/{id}/snapshot`; HTTP directory cams use `/stream` MJPEG.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -13,7 +13,7 @@ This is **not** a camera-discovery change. Existing camera rules still apply: ne
|
||||||
| NASA FIRMS VIIRS hotspots | Ingested (`app/fire_sources.py` → NATS `events.fire` → `fires` hypertable → `GET /api/fires`) | Needs free `FIRMS_MAP_KEY`. See `docs/firms.md`. |
|
| NASA FIRMS VIIRS hotspots | Ingested (`app/fire_sources.py` → NATS `events.fire` → `fires` hypertable → `GET /api/fires`) | Needs free `FIRMS_MAP_KEY`. See `docs/firms.md`. |
|
||||||
| NASA GIBS basemaps | Frontend tiles via `app/gibs_map.py` | No key. CORS `*`. |
|
| NASA GIBS basemaps | Frontend tiles via `app/gibs_map.py` | No key. CORS `*`. |
|
||||||
| GIBS VIIRS thermal tiles | Documented, not wired as overlay | Same GIBS stack; no key. |
|
| GIBS VIIRS thermal tiles | Documented, not wired as overlay | Same GIBS stack; no key. |
|
||||||
| Cameras | Scraper → `cameras` table | Defaults already include ALERTWest JPEGs + Live-Environment-Streams HLS/YouTube GeoJSON. |
|
| Cameras | Scraper + masscan → `cameras` table | Defaults already include ALERTWest JPEGs + Live-Environment-Streams HLS/YouTube GeoJSON. |
|
||||||
| News / RSS / GDELT / USGS quakes | Ingest | Out of scope for this brief. |
|
| News / RSS / GDELT / USGS quakes | Ingest | Out of scope for this brief. |
|
||||||
|
|
||||||
**Action for existing fire ingest:** NASA will stop Suomi NPP product delivery on **2026-11-01**. Switch `FIRMS_DATASET` from `VIIRS_SNPP_NRT` to `VIIRS_NOAA20_NRT` and/or `VIIRS_NOAA21_NRT` before then.[20]
|
**Action for existing fire ingest:** NASA will stop Suomi NPP product delivery on **2026-11-01**. Switch `FIRMS_DATASET` from `VIIRS_SNPP_NRT` to `VIIRS_NOAA20_NRT` and/or `VIIRS_NOAA21_NRT` before then.[20]
|
||||||
|
|
@ -261,7 +261,7 @@ Use later if you want commuter rail / subway vehicle positions (LA Metro, MTA, e
|
||||||
|
|
||||||
## 6. Open video / camera feeds (official public only)
|
## 6. Open video / camera feeds (official public only)
|
||||||
|
|
||||||
Do **not** add Insecam-style random IP cams as a new source. The scraper already has a public list; this section is **agency-published** JPEG/HLS.
|
Do **not** add Insecam-style random IP cams as a new source. The scraper already has a public list + masscan; this section is **agency-published** JPEG/HLS.
|
||||||
|
|
||||||
### 6.1 Already wired
|
### 6.1 Already wired
|
||||||
|
|
||||||
|
|
@ -304,7 +304,7 @@ Do not call the YouTube Data API unless you want search. Embedding existing stre
|
||||||
|
|
||||||
### 6.5 Skip
|
### 6.5 Skip
|
||||||
|
|
||||||
- Insecam / random “public IP cam” aggregators — ToS / privacy.
|
- Insecam / random “public IP cam” aggregators — ToS / privacy / already covered by masscan ethics.
|
||||||
- TrafficLand, EarthCam commercial APIs.
|
- TrafficLand, EarthCam commercial APIs.
|
||||||
- SkylineWebcams — scraping, not an API.
|
- SkylineWebcams — scraping, not an API.
|
||||||
|
|
||||||
|
|
@ -523,7 +523,7 @@ Attribution bar (required): OpenSky / ADSB.lol ODbL / Amtraker / RainViewer / IE
|
||||||
|
|
||||||
## 12. Legal / ethics (non-negotiable)
|
## 12. Legal / ethics (non-negotiable)
|
||||||
|
|
||||||
- RTSP policy unchanged (never emit `rtsp://` hrefs).
|
- Masscan / RTSP policy unchanged.
|
||||||
- AISStream: server-side only; do not put the key in JS.[5]
|
- AISStream: server-side only; do not put the key in JS.[5]
|
||||||
- OpenSky: non-commercial unless licensed; cite if you publish.[2]
|
- OpenSky: non-commercial unless licensed; cite if you publish.[2]
|
||||||
- ADSB.lol: ODbL share-alike on derived databases.[4]
|
- ADSB.lol: ODbL share-alike on derived databases.[4]
|
||||||
|
|
|
||||||
310
docs/news.md
310
docs/news.md
|
|
@ -1,136 +1,67 @@
|
||||||
# News pipeline — scraper + Nous Portal summarizer
|
# News pipeline — scraper + summarizer
|
||||||
|
|
||||||
The OSINT dashboard ingests a large curated feed list (`news/scraper/urls.txt`)
|
The OSINT dashboard ingests ~257 global news RSS sources hourly and produces
|
||||||
continuously and produces an English LLM brief plus flagged ticker/map rows
|
LLM master summaries. Both services were vendored from the upstream
|
||||||
every 15 minutes. Both services were vendored from the upstream
|
`~/Projects/newsPipeline` project and re-integrated here to replace the old
|
||||||
`~/Projects/newsPipeline` project and re-integrated here against the EXISTING
|
k8s CronJob choreography with in-compose scheduling against the EXISTING
|
||||||
osint-db — **no second Postgres**. The LLM is **Nous Portal**
|
osint-db — **no second Postgres**.
|
||||||
(`inference-api.nousresearch.com`) — not Gemini.
|
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
```
|
```
|
||||||
urls.txt (RSS + homepages)
|
257 RSS feeds (news/scraper/urls.txt)
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
news-scraper (Scrapy, continuous) ──► articles table (osint-db)
|
news-scraper (Scrapy, hourly :00) ──► articles table (osint-db)
|
||||||
│ │
|
│ │
|
||||||
│ ▼
|
│ ▼
|
||||||
news-summarizer (Nous Portal, every 15m + 23:00 recap) ──► article_summaries + news_items
|
news-summarizer (Gemini map-reduce, hourly :05) ──► article_summaries table
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
GET /api/news · /api/news/summaries · /api/news/ticker · /api/news/map
|
GET /api/news · GET /api/news/summaries
|
||||||
GET /api/news/models · GET/PUT /api/settings
|
|
||||||
```
|
```
|
||||||
|
|
||||||
| Component | Image | Container | Scheduling |
|
| Component | Image | Container | Scheduling |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| Scraper | `localhost/osint-news-scraper` | `osint-news-scraper` | loop, `NEWS_SCRAPE_INTERVAL_S` (default 10s after each crawl) |
|
| Scraper | `localhost/osint-news-scraper` | `osint-news-scraper` | wall-clock loop, minute `NEWS_SCRAPE_MINUTE` (default :00) |
|
||||||
| Summarizer | `localhost/osint-news-summarizer` | `osint-news-summarizer` | loop, `NEWS_SUMMARIZE_INTERVAL_S` (default 900s) |
|
| Summarizer | `localhost/osint-news-summarizer` | `osint-news-summarizer` | wall-clock loop, minute `NEWS_SUMMARIZE_MINUTE` (default :05) |
|
||||||
|
|
||||||
Both services live under the `ingest` compose profile (same as the ingester
|
Both services live under the `ingest` compose profile (same as the ingester
|
||||||
and camera-scraper): `docker compose --profile ingest up -d`.
|
and camera-scraper): `docker compose --profile ingest up -d`.
|
||||||
|
|
||||||
The summarizer is a batch sidecar, **not** a live overlay. Do **not** reuse
|
|
||||||
`GET /api/alerts` (dashboard entity/keyword alerts). Do **not** stuff news
|
|
||||||
into `overlay_catalog()` — `/api/map/layers` `overlays` stays live upstream
|
|
||||||
feeds (`GET /api/news` exact key set is unchanged on purpose).
|
|
||||||
|
|
||||||
## Data flow
|
## Data flow
|
||||||
|
|
||||||
1. **Scraper** — `news/scraper/run_news_scraper.py` runs
|
1. **Scraper** — `news/scraper/run_news_scraper.py` runs
|
||||||
`scrapy crawl articles` back-to-back (default 10s pause). The spider reads
|
`scrapy crawl articles` (spider `news/scraper/newsScraper/spiders/news_spider.py`)
|
||||||
URLs from `urls.txt` (homepages autodiscover RSS; feed URLs are parsed
|
at the top of each hour. The spider reads the RSS feed URLs from `urls.txt`,
|
||||||
directly), follows each `<item>` link, extracts the main article body, and
|
follows each `<item>` link, extracts the main article body, and the
|
||||||
the `PostgresPipeline` writes to `articles` with URL-based dedup
|
`PostgresPipeline` writes to `articles` with URL-based dedup
|
||||||
(`ON CONFLICT (url) DO NOTHING`). Items whose parsed publish date is more
|
(`ON CONFLICT (url) DO NOTHING`).
|
||||||
than 2 hours in the future are dropped at ingest (`future_dated_dropped`)
|
|
||||||
and never surface via `/api/news`, which additionally hides any
|
|
||||||
`articles.timestamp > now()` row until its date arrives.
|
|
||||||
2. **Summarizer** — `news/summerizer/run_news_summarizer.py` runs
|
2. **Summarizer** — `news/summerizer/run_news_summarizer.py` runs
|
||||||
`summarizer.py` every `NEWS_SUMMARIZE_INTERVAL_S` (default 900) over the
|
`summarizer.py` at :05 past each hour. It reads articles from the last
|
||||||
last `SUMMARY_WINDOW_MINUTES` (default 15), and again at 23:00
|
`SUMMARY_WINDOW_HOURS`, map-reduces them through Gemini
|
||||||
`America/New_York` (`TZ`) over the last 24 hours as a daily recap
|
(`SUMMARY_MODEL`, default `gemini-2.0-flash`), and inserts one master
|
||||||
(`kind=daily_recap`). Both map-reduce through Nous Portal (`SUMMARY_MODEL`
|
summary into `article_summaries`.
|
||||||
/ Settings, default `Hermes-4.3-36B`), write the English brief to
|
|
||||||
`article_summaries` (column `model` is the LLM id; `kind` is
|
|
||||||
`interval` or `daily_recap`), and flagged ticker/map rows to `news_items`.
|
|
||||||
|
|
||||||
Loops are serial (two crawls/summaries never overlap). Interval idempotency:
|
Scheduling is done with small in-compose wall-clock loops (not host cron): each
|
||||||
if `article_summaries` already has a row in the last interval, the summarizer
|
loop runs once on boot (`*_RUN_ON_START=1`, seeds data fast) then sleeps until
|
||||||
**skips** (prevents double-pins on `RUN_ON_START` recreate). Set
|
the next scheduled minute. The loop is serial, so a run that overruns its slot
|
||||||
`NEWS_SUMMARIZE_FORCE=1` to ignore that skip.
|
simply shifts to the next boundary — two crawls/summaries never overlap.
|
||||||
|
|
||||||
The `articles` and `article_summaries` tables are created by the idempotent
|
The `articles` and `article_summaries` tables are created by the idempotent
|
||||||
alembic migration `003_news` (also created by the scraper's own
|
alembic migration `003_news` (also created by the scraper's own
|
||||||
`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items` and
|
`CREATE TABLE IF NOT EXISTS`, so container startup order doesn't matter).
|
||||||
`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.
|
|
||||||
|
|
||||||
## Keys and Settings
|
|
||||||
|
|
||||||
- **`NOUS_API_KEY`** — paste in the dashboard **Keys** UI (`api_keys` /
|
|
||||||
`keystore.KEY_REGISTRY`). Env / `.env` is an **override** (env wins, same
|
|
||||||
as FIRMS). Never returned by any API; never emitted into `index.html`;
|
|
||||||
never proxied from the browser.
|
|
||||||
- **Idle without a key** — if env is unset **and** the keystore row is empty,
|
|
||||||
the summarizer logs and idles (never crashes). News intel APIs return `[]`.
|
|
||||||
- **Model** — non-secret. Settings UI model selector `PUT /api/settings`
|
|
||||||
`{ "summary_model": "…" }` stores `SUMMARY_MODEL` in `app_settings` (1–128
|
|
||||||
chars). `GET /api/settings` echoes `{summary_model, nous_base_url}`.
|
|
||||||
`nous_base_url` is read-only. Default `Hermes-4.3-36B`. Live catalog is
|
|
||||||
best-effort `GET /api/news/models`.
|
|
||||||
|
|
||||||
## Endpoints
|
## Endpoints
|
||||||
|
|
||||||
### GET /api/news — recent articles
|
### GET /api/news — recent articles
|
||||||
|
|
||||||
Key set **unchanged** (no `lat`/`lon` on articles; geo lives on `/api/news/map`).
|
|
||||||
|
|
||||||
| Query param | Meaning | Default |
|
| Query param | Meaning | Default |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `domain` | filter by source domain (e.g. `www.reuters.com`) | none |
|
| `domain` | filter by source domain (e.g. `www.reuters.com`) | none |
|
||||||
| `since` | only articles captured at/after this UTC instant (ISO-8601) | none |
|
| `since` | only articles captured at/after this UTC instant (ISO-8601) | none |
|
||||||
| `limit` | max rows | `50` (max `500`) |
|
| `limit` | max rows | `50` (max `500`) |
|
||||||
| `offset` | pagination offset | `0` |
|
| `offset` | pagination offset | `0` |
|
||||||
| `include_content` | include full article body | `false` |
|
|
||||||
|
|
||||||
```json
|
```json
|
||||||
[
|
[
|
||||||
|
|
@ -138,14 +69,14 @@ Key set **unchanged** (no `lat`/`lon` on articles; geo lives on `/api/news/map`)
|
||||||
"id": 1,
|
"id": 1,
|
||||||
"title": "…",
|
"title": "…",
|
||||||
"url": "https://…",
|
"url": "https://…",
|
||||||
"content": null,
|
"content": "full extracted article text…",
|
||||||
"domain": "www.reuters.com",
|
"domain": "www.reuters.com",
|
||||||
"timestamp": "2026-08-24T18:10:00Z"
|
"timestamp": "2026-08-24T18:10:00Z"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
```
|
```
|
||||||
|
|
||||||
### GET /api/news/summaries — master LLM briefs
|
### GET /api/news/summaries — master LLM summaries
|
||||||
|
|
||||||
| Query param | Meaning | Default |
|
| Query param | Meaning | Default |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
|
@ -157,191 +88,52 @@ Key set **unchanged** (no `lat`/`lon` on articles; geo lives on `/api/news/map`)
|
||||||
[
|
[
|
||||||
{
|
{
|
||||||
"id": 1,
|
"id": 1,
|
||||||
"summary_text": "English markdown brief…",
|
"summary_text": "master LLM summary (markdown)…",
|
||||||
"batch_timestamp": "2026-08-24T18:10:00Z",
|
"batch_timestamp": "2026-08-24T18:10:00Z"
|
||||||
"model": "Hermes-4.3-36B",
|
|
||||||
"kind": "daily_recap"
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
```
|
```
|
||||||
|
|
||||||
`model` and `kind` are additive (`interval` | `daily_recap` | `null` for old rows).
|
|
||||||
`?kind=daily_recap` pins the nightly 24h recap. Empty DB → `[]` (no crash).
|
|
||||||
Malformed `kind` → `422`.
|
|
||||||
|
|
||||||
### GET /api/news/ticker — HUD headlines
|
|
||||||
|
|
||||||
Critical/high `news_items` with `kind=ticker` first. If none are flagged,
|
|
||||||
medium/low ticker rows fill the tape so the dock is not blank. Do **not**
|
|
||||||
reuse `GET /api/alerts`. Bottom HUD `#nt-track` scrolls these rows, not a
|
|
||||||
dump of the whole brief.
|
|
||||||
|
|
||||||
| Query param | Meaning | Default |
|
|
||||||
|---|---|---|
|
|
||||||
| `since` | only items created at/after this UTC instant | none |
|
|
||||||
| `limit` | max rows | `20` (max `50`) |
|
|
||||||
|
|
||||||
```json
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"headline": "…",
|
|
||||||
"importance": "critical",
|
|
||||||
"location_name": "Kyiv",
|
|
||||||
"url": "https://…",
|
|
||||||
"created_at": "2026-08-24T18:10:00Z"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
### GET /api/news/map — geolocated critical/high pins
|
|
||||||
|
|
||||||
Only rows with valid `lat`/`lon`. Optional bbox. **No zoom skip** — world
|
|
||||||
view is the point. Layer-panel toggle uses this dedicated path (same as
|
|
||||||
event blips), not `overlay_catalog`.
|
|
||||||
|
|
||||||
| Query param | Meaning | Default |
|
|
||||||
|---|---|---|
|
|
||||||
| `bbox` | `minlon,minlat,maxlon,maxlat` | all flagged pins |
|
|
||||||
| `since` | only items created at/after this UTC instant | last 24 hours |
|
|
||||||
| `limit` | max rows | `200` (max `500`) |
|
|
||||||
|
|
||||||
Malformed bbox → `422`.
|
|
||||||
|
|
||||||
```json
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"id": 1,
|
|
||||||
"headline": "…",
|
|
||||||
"importance": "high",
|
|
||||||
"location_name": "Kyiv",
|
|
||||||
"lat": 50.45,
|
|
||||||
"lon": 30.52,
|
|
||||||
"location_confidence": "city",
|
|
||||||
"category": "military/conflict",
|
|
||||||
"url": "https://…",
|
|
||||||
"created_at": "2026-08-24T18:10:00Z"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
Pins are LLM-estimated and clamped (`lat∈[-90,90]`, `lon∈[-180,180]`). No
|
|
||||||
Nominatim. No writes into `events`.
|
|
||||||
|
|
||||||
### GET /api/news/models — Settings dropdown catalog
|
|
||||||
|
|
||||||
Never 502s. `{ "source": "live"|"fallback", "models": [{"id": "…"}] }`.
|
|
||||||
|
|
||||||
### GET /api/settings · PUT /api/settings
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "summary_model": "Hermes-4.3-36B", "nous_base_url": "https://inference-api.nousresearch.com/v1" }
|
|
||||||
```
|
|
||||||
|
|
||||||
PUT body is `{ "summary_model": "<1–128 char id>" }`. `nous_base_url` is
|
|
||||||
ignored even if sent.
|
|
||||||
|
|
||||||
## Reduce JSON contract
|
|
||||||
|
|
||||||
Reduce phase (`response_format: json_object`, English only) must be a single
|
|
||||||
object. Parser (`intel.parse_reduce_json`) strips `<think>…</think>` and
|
|
||||||
markdown json fences, then brace-slices:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"summary_en": "English markdown brief or the no-qualifying-events sentence",
|
|
||||||
"ticker": [
|
|
||||||
{"headline": "", "importance": "critical", "url": "", "location_name": ""}
|
|
||||||
],
|
|
||||||
"map_items": [
|
|
||||||
{
|
|
||||||
"headline": "",
|
|
||||||
"importance": "critical",
|
|
||||||
"location_name": "",
|
|
||||||
"lat": 0,
|
|
||||||
"lon": 0,
|
|
||||||
"location_confidence": "city",
|
|
||||||
"category": "military/conflict",
|
|
||||||
"url": ""
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Persist ticker for critical/high first; if none, persist medium/low so the
|
|
||||||
tape is not empty. Map rows stay critical/high with valid coords; Unknown /
|
|
||||||
invented places are dropped. Caps: 12 ticker (≤140 chars, no markdown), 20
|
|
||||||
map. `summary_en` lands in `article_summaries.summary_text`.
|
|
||||||
|
|
||||||
## Configuration (all via env / `.env`)
|
## Configuration (all via env / `.env`)
|
||||||
|
|
||||||
| Var | Default | Notes |
|
| Var | Default | Notes |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `NOUS_API_KEY` | *(blank)* | **Required for summaries.** Prefer Keys UI; env overrides. Unset in **both** env and `api_keys` = summarizer logs and idles (never crashes); APIs return `[]`. |
|
| `GEMINI_API_KEY` | *(blank)* | **Required for summaries.** Unset = summarizer logs and idles (never crashes). |
|
||||||
| `NOUS_BASE_URL` | `https://inference-api.nousresearch.com/v1` | Read-only in Settings. |
|
| `SUMMARY_MODEL` | `gemini-2.0-flash` | Gemini model id. |
|
||||||
| `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. |
|
||||||
| `NEWS_BATCH_SIZE` | `50` | Articles per map-phase batch (compose maps to container `BATCH_SIZE`). |
|
| `SUMMARY_WINDOW_HOURS` | `1` | How far back the summarizer looks for new articles. |
|
||||||
| `SUMMARY_MIN_SCORE` | `60` | Map-phase score a block must reach to enter the reduce brief. |
|
| `INCLUDE_FUTURES` | `0` | Legacy futures-prices coupling (upstream pipeline). OFF for OSINT; set `1` + install `yfinance` to enable. |
|
||||||
| `SUMMARY_TOP_N` | `12` | Max blocks passed to the reduce phase (best score first). |
|
| `NEWS_SCRAPE_MINUTE` | `0` | Wall-clock minute the scraper fires. |
|
||||||
| `SUMMARY_FALLBACK_TOP` | `3` | Blocks used when nothing clears `SUMMARY_MIN_SCORE`; `0` = empty DATA. |
|
| `NEWS_SUMMARIZE_MINUTE` | `5` | Wall-clock minute the summarizer fires. |
|
||||||
| `SUMMARY_FALLBACK_MIN_SCORE` | `40` | Score floor for the fallback set; below it the reduce phase gets empty DATA. |
|
|
||||||
| `SUMMARY_DEDUPE` | `1` | Collapse syndicated wire copies before selection; `0` skips dedupe entirely. |
|
|
||||||
| `SUMMARY_DEDUPE_SIMILARITY` | `0.85` | Normalised-title similarity at which two blocks count as the same story (1.0 = verbatim only). |
|
|
||||||
| `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles (window is `(now - N, now]`; future-dated rows are ignored). |
|
|
||||||
| `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). |
|
|
||||||
| `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). |
|
|
||||||
| `TZ` | `America/New_York` | Timezone for the 23:00 daily recap. |
|
|
||||||
| `NEWS_RECAP_HOUR` | `23` | Local hour of the daily 24h recap. |
|
|
||||||
| `NEWS_RECAP_MINUTE` | `0` | Local minute of the daily recap. |
|
|
||||||
| `NEWS_SCRAPE_RUN_ON_START` | `1` | Run one scrape immediately on container start. |
|
| `NEWS_SCRAPE_RUN_ON_START` | `1` | Run one scrape immediately on container start. |
|
||||||
| `NEWS_SUMMARIZE_RUN_ON_START` | `1` | Run one summarize immediately on container start. |
|
| `NEWS_SUMMARIZE_RUN_ON_START` | `1` | Run one summarize immediately on container start. |
|
||||||
| `NEWS_SUMMARIZE_FORCE` | `0` | `1` ignores the interval/recap idempotency skip (double-pins on recreate). |
|
|
||||||
| `INCLUDE_FUTURES` | `0` | Legacy. Ignored — prompts never inject futures/market tape. |
|
|
||||||
| `NEWS_LOG_LEVEL` | `INFO` | Scrapy log level. |
|
| `NEWS_LOG_LEVEL` | `INFO` | Scrapy log level. |
|
||||||
| `OSINT_USER_AGENT` | `osint-dashboard-news-summarizer` | Sent on every outbound Nous call. |
|
|
||||||
| `TELEGRAM_TOKEN` / `TELEGRAM_CHAT_ID` | *(blank)* | Reserved for the (out-of-scope) Telegram delivery bot. |
|
| `TELEGRAM_TOKEN` / `TELEGRAM_CHAT_ID` | *(blank)* | Reserved for the (out-of-scope) Telegram delivery bot. |
|
||||||
|
|
||||||
DB_* for both services is mapped to the shared osint-db credentials
|
DB_* for both services is mapped to the shared osint-db credentials
|
||||||
(`DB_HOST=db`, same `DB_USER/DB_PASSWORD/DB_NAME` as the rest of the stack).
|
(`DB_HOST=db`, same `DB_USER/DB_PASSWORD/DB_NAME` as the rest of the stack).
|
||||||
|
|
||||||
Nous chat: `POST {NOUS_BASE_URL}/chat/completions` via `news/summerizer/nous_client.py`
|
|
||||||
(`httpx`, no `openai` SDK). Auth is a Bearer token from `NOUS_API_KEY`.
|
|
||||||
No Hermes-4 reasoning system prompt. Reduce uses `json_mode=True`.
|
|
||||||
|
|
||||||
## Prompts
|
## Prompts
|
||||||
|
|
||||||
Both prompts are env-overridable. Defaults recap the articles actually
|
Both prompts are env-overridable — the default `MAP_PROMPT` is OSINT-neutral
|
||||||
provided, ranked by breaking important news, and ignore futures / commodity
|
(facts, locations, entities, category, OSINT signal per article) and the default
|
||||||
tape. ticker/map may be empty; `summary_en` must still be a real brief.
|
`SUMMARY_PROMPT` produces a concise executive summary of the most impactful
|
||||||
`RECAP_PROMPT` (23:00, 24h window) is the daily recap; `SUMMARY_PROMPT` is the
|
items (with a "no qualifying events" escape hatch). Upstream's futures/markets
|
||||||
15-min analyst. `INCLUDE_FUTURES` is ignored.
|
prompt language is gated behind `INCLUDE_FUTURES=1`.
|
||||||
|
|
||||||
## Tests
|
## Tests
|
||||||
|
|
||||||
```bash
|
`tests/test_api_news.py` — DB-backed API contract tests (auto-skip without a
|
||||||
PYTHONPATH=news/summerizer pytest news/summerizer/tests -v
|
reachable test database, same as the FIRMS tests):
|
||||||
# intel + nous_client tests PASS (no network)
|
|
||||||
|
|
||||||
PYTHONPATH=app pytest tests/test_api_news.py \
|
```bash
|
||||||
tests/test_api_settings.py tests/test_api_live_layers.py -v
|
DB_HOST=... DB_PORT=... DB_USER=osint DB_PASSWORD=... DB_NAME=osint_data \
|
||||||
# DB-marked tests skip without Postgres; live_layers must still PASS
|
pytest tests/test_api_news.py -v
|
||||||
# /api/map/layers overlays key set UNCHANGED
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Live verification
|
## Live verification
|
||||||
|
|
||||||
After deploy / compose rebuild of `news-summarizer` on the Pi:
|
End-to-end (real crawl → DB → API) is verified after deploy on the Pi: check
|
||||||
|
`docker compose --profile ingest logs -f news-scraper news-summarizer`, then
|
||||||
1. Keys UI: save `NOUS_API_KEY` → status `****last4`.
|
`curl -s localhost:8000/api/news | head`. Summaries additionally require
|
||||||
2. Settings: pick a model → Save → `GET /api/settings` echoes it.
|
`GEMINI_API_KEY` to be set in `.env` on the Pi.
|
||||||
3. `docker compose --profile ingest logs -f news-summarizer` — next run (or
|
|
||||||
`NEWS_SUMMARIZE_RUN_ON_START=1` recreate) logs `Processing N articles with <model>`.
|
|
||||||
4. `curl -s localhost:8000/api/news/summaries?limit=1` — English `summary_text`, `model` set.
|
|
||||||
5. `curl -s localhost:8000/api/news/ticker` — flagged headlines only.
|
|
||||||
6. `curl -s localhost:8000/api/news/map` — only rows with lat/lon.
|
|
||||||
7. HUD: NEWS ticker scrolls flagged items; map overlay pins popup with location.
|
|
||||||
8. Unset key + empty keystore → summarizer logs idle, APIs return `[]`, no crash.
|
|
||||||
|
|
||||||
**Operator action after merge:** paste a Nous Portal API key in API Keys; pick
|
|
||||||
a model in Settings if the default `Hermes-4.3-36B` is not wanted; rebuild
|
|
||||||
`osint-news-summarizer` on the Pi (`pi-app-deploy` / compose).
|
|
||||||
|
|
|
||||||
|
|
@ -1,347 +0,0 @@
|
||||||
# Free satellite feeds for the OSINT map
|
|
||||||
|
|
||||||
Builder inventory (research profile). Probed **2026-08-29** from this machine. Do **not** treat search snippets as live — every row below had a `curl`/GET (tile, GetCapabilities, STAC, or GetMap). 404 tile rows are omitted unless Capabilities/DescribeDomains still prove the layer exists (sparse fire overlays 404 on empty tiles).
|
|
||||||
|
|
||||||
**Pi rules:** browser `L.tileLayer` when CORS `*`; do not proxy multi-GB COGs through the Pi; STAC+SAS like existing Sentinel-1 is “backend same as S-1”; no Redis; home uplink is small.
|
|
||||||
|
|
||||||
GIBS Web Mercator REST template (no key):[2]
|
|
||||||
|
|
||||||
```
|
|
||||||
https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/{layer}/default/{time}/{TileMatrixSet}/{z}/{y}/{x}.{jpg|png}
|
|
||||||
```
|
|
||||||
|
|
||||||
Omit `{time}` for static layers. Sub-daily GOES/Himawari accept `YYYY-MM-DD` **or** `YYYY-MM-DDTHH:MI:SSZ` (GIBS snaps to nearest).[2] Attribution: NASA asks clients to acknowledge GIBS/ESDIS.[1]
|
|
||||||
|
|
||||||
Live GetCapabilities `epsg3857/best` on 2026-08-29: **1315** `Layer` entries, **all** with a `GoogleMapsCompatible_LevelN` matrix, `access-control-allow-origin: *`.[4] GIBS documents **1000+** visualizations; many LANCE layers appear within **3.5 hours** of observation.[3]
|
|
||||||
|
|
||||||
Worldview is the interactive catalog of the same tiles.[5] GIBS developer portal: Earthdata GIBS API page (HTTP 403 from this host at probe time; docs site above is the working copy).[27]
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Already in the product (do not rediscover)
|
|
||||||
|
|
||||||
| id | status |
|
|
||||||
|---|---|
|
|
||||||
| `BlueMarble_ShadedRelief_Bathymetry` | GIBS basemap (`app/gibs_map.py`) |
|
|
||||||
| `VIIRS_SNPP_CorrectedReflectance_TrueColor` | GIBS basemap |
|
|
||||||
| `MODIS_Terra_CorrectedReflectance_TrueColor` | GIBS basemap |
|
|
||||||
| `MODIS_Aqua_CorrectedReflectance_TrueColor` | GIBS basemap |
|
|
||||||
| `VIIRS_SNPP_DayNightBand_ENCC` | GIBS night lights |
|
|
||||||
| FIRMS VIIRS hotspot CSV | ingest + `FIRMS_MAP_KEY` |
|
|
||||||
| `VIIRS_SNPP_Thermal_Anomalies_375m_All` | overlay in `app/live_layers.py` (`gibs_thermal`). **Caps now say TMS `GoogleMapsCompatible_Level8`**, not Level9 — the wired URL uses Level9 (will 400). |
|
|
||||||
| Sentinel-1 GRD | Planetary Computer STAC + SAS + TiTiler `GET /api/map/sentinel1` |
|
|
||||||
| IEM NEXRAD / RainViewer | weather radar, not satellite |
|
|
||||||
|
|
||||||
Repo docs already flag **Suomi NPP product stop 2026-11-01** — swap SNPP true color / DNB / thermal / FIRMS `VIIRS_SNPP_NRT` to NOAA-20/21 before then.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Ranked “add tomorrow” (sections 1–2)
|
|
||||||
|
|
||||||
Most new OSINT signal per **zero dollars**, browser tiles only:
|
|
||||||
|
|
||||||
1. **VIIRS NOAA-20 + NOAA-21 true color** — SNPP replacement, same dropdown pattern.
|
|
||||||
2. **VIIRS false-color SWIR** (`BandsM11-I2-I1`, `BandsM3-I3-M11`, MODIS 7-2-1) — burn scars, flood, bare soil.
|
|
||||||
3. **GIBS GOES-East/West GeoColor + Band13 IR** — 10-minute weather-sat, Hormuz + CONUS.
|
|
||||||
4. **GIBS Himawari AHI vis + IR** — same for IO/WestPac.
|
|
||||||
5. **HLS S30/L30** — 30 m Landsat/Sentinel-2 look without TiTiler.
|
|
||||||
6. **OPERA RTC Sentinel-1 + DIST-ALERT + DSWx** — SAR / disturbance / flood as GIBS tiles (not COGs).
|
|
||||||
7. **NOAA-20/21 DNB** — night lights after SNPP.
|
|
||||||
8. **IEM GOES XYZ** — “latest” tiles, no time in the URL, already CORS `*` like NEXRAD.[6]
|
|
||||||
9. **EUMETView WMS** — Meteosat/MTG for Europe–Africa–IO, CORS `*`.[18]
|
|
||||||
10. **GFW GLAD-S2 / integrated deforestation alerts** — raster tiles, CORS `*` when `Origin` is sent.[15]
|
|
||||||
11. **MUR SST + VIIRS/PACE/OLCI chlorophyll** — ocean.
|
|
||||||
12. **MODIS NDVI 8-day + IMERG rain** — veg / flood context.
|
|
||||||
13. **SRTM / ASTER GDEM color index** — satellite-derived DEM, static.
|
|
||||||
14. **NOAA-20/21 thermal anomalies** — FIRMS-shaped overlay after SNPP; empty tiles 404.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Drop-in GIBS WMTS
|
|
||||||
|
|
||||||
All rows: **key? no**. **CORS `*`**. **Pi fit: browser `L.tileLayer`**. Same time-domain helper as `gibs_map.py` (`…/1.0.0/{id}/default/{tms}/all/all.xml`).
|
|
||||||
|
|
||||||
Format of URL column: layer id + TMS + ext. Date used in probes: `2026-08-27` unless noted.
|
|
||||||
|
|
||||||
### 1.1 Optical (true / false / SWIR)
|
|
||||||
|
|
||||||
| id | what you see | tile pattern | cadence | max zoom | license | already have? | probe |
|
|
||||||
|---|---|---|---|---|---|---|---|
|
|
||||||
| `VIIRS_NOAA20_CorrectedReflectance_TrueColor` | Daily true color, JPSS-1 | `…/{id}/default/{time}/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg` | daily | 9 (~250 m) | NASA GIBS ack[1] | **no** (SNPP only) | 200 `*` jpeg |
|
|
||||||
| `VIIRS_NOAA21_CorrectedReflectance_TrueColor` | Daily true color, JPSS-2 | same Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
|
|
||||||
| `VIIRS_SNPP_CorrectedReflectance_BandsM11-I2-I1` | False color SWIR (burns, flood) | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
|
|
||||||
| `VIIRS_SNPP_CorrectedReflectance_BandsM3-I3-M11` | False color (snow/ice/desert) | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
|
|
||||||
| `VIIRS_NOAA20_CorrectedReflectance_BandsM11-I2-I1` | NOAA-20 SWIR false color | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
|
|
||||||
| `VIIRS_NOAA21_CorrectedReflectance_BandsM11-I2-I1` | NOAA-21 SWIR false color | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
|
|
||||||
| `MODIS_Terra_CorrectedReflectance_Bands721` | Classic 7-2-1 burn/SWIR | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
|
|
||||||
| `MODIS_Terra_CorrectedReflectance_Bands367` | 3-6-7 false color | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
|
|
||||||
| `MODIS_Aqua_CorrectedReflectance_Bands721` | Aqua 7-2-1 | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 |
|
|
||||||
| `HLS_S30_Nadir_BRDF_Adjusted_Reflectance` | Harmonized Sentinel-2 30 m RGB | Level12 png | ~2–3 d when a granule exists | 12 (~30 m) | NASA GIBS[1] | no | 200 at z=5 NC; 404 on empty granules is normal. Domain from 2015–present |
|
|
||||||
| `HLS_L30_Nadir_BRDF_Adjusted_Reflectance` | Harmonized Landsat 30 m | Level12 png | 8–16 d | 12 | NASA GIBS[1] | no | in caps; tile 404 on empty scene |
|
|
||||||
| `Landsat_WELD_CorrectedReflectance_TrueColor_Global_Monthly` | Landsat WELD monthly mosaic | Level12 jpg | monthly, **not NRT** | 12 | NASA GIBS[1] | no | 200 |
|
|
||||||
| `Landsat_WELD_CorrectedReflectance_TrueColor_Global_Annual` | WELD annual | Level12 jpg | yearly | 12 | NASA GIBS[1] | no | 200 |
|
|
||||||
|
|
||||||
### 1.2 Weather satellites (imagery, not NEXRAD)
|
|
||||||
|
|
||||||
Sub-daily. Probe with `2026-08-27` **and** `2026-08-27T18:00:00Z` both 200 (nearestValue).[2]
|
|
||||||
|
|
||||||
| id | what you see | TMS / ext | cadence | max zoom | already have? | probe |
|
|
||||||
|---|---|---|---|---|---|---|
|
|
||||||
| `GOES-East_ABI_GeoColor` | GeoColor full disk (Americas, Atlantic, Hormuz west edge) | Level7 png | ~10 min | 7 | no | 200 |
|
|
||||||
| `GOES-West_ABI_GeoColor` | GeoColor Pacific / CONUS west | Level7 png | ~10 min | 7 | no | 200 (also 200 over CA with ISO time) |
|
|
||||||
| `GOES-East_ABI_Band2_Red_Visible_1km` | ABI vis | Level7 png | ~10 min | 7 | no | 200 |
|
|
||||||
| `GOES-West_ABI_Band2_Red_Visible_1km` | ABI vis | Level7 png | ~10 min | 7 | no | 200 |
|
|
||||||
| `GOES-East_ABI_Band13_Clean_Infrared` | Clean IR window | Level6 png | ~10 min | 6 | no | 200 |
|
|
||||||
| `GOES-West_ABI_Band13_Clean_Infrared` | Clean IR | Level6 png | ~10 min | 6 | no | 200 |
|
|
||||||
| `GOES-East_ABI_FireTemp` | Fire temperature RGB | Level7 png | ~10 min | 7 | no | 200 |
|
|
||||||
| `GOES-West_ABI_FireTemp` | Fire temperature RGB | Level7 png | ~10 min | 7 | no | 404 on NC tile (wrong disk); use west longitudes |
|
|
||||||
| `GOES-East_ABI_Dust` | Dust RGB | Level7 png | ~10 min | 7 | no | 200 |
|
|
||||||
| `GOES-East_ABI_Air_Mass` | Air mass RGB | Level6 png | ~10 min | 6 | no | 200 |
|
|
||||||
| `GOES-West_ABI_Air_Mass` | Air mass RGB | Level6 png | ~10 min | 6 | no | 200 |
|
|
||||||
| `Himawari_AHI_Band3_Red_Visible_1km` | Himawari vis (IO / WestPac / Aus) | Level7 png | ~10 min | 7 | no | 200 (ISO time over Japan) |
|
|
||||||
| `Himawari_AHI_Band13_Clean_Infrared` | Himawari IR | Level6 png | ~10 min | 6 | no | 200 |
|
|
||||||
| `Himawari_AHI_Air_Mass` | Himawari air mass | Level6 png | ~10 min | 6 | no | 200 |
|
|
||||||
|
|
||||||
**Meteosat is not in GIBS.** Use section 2 EUMETView.
|
|
||||||
|
|
||||||
### 1.3 SAR / flood / disturbance (GIBS tiles — skip TiTiler)
|
|
||||||
|
|
||||||
| id | what you see | TMS | cadence | max zoom | already have? | probe |
|
|
||||||
|---|---|---|---|---|---|---|
|
|
||||||
| `OPERA_L2_Radiometric_Terrain_Corrected_SAR_Sentinel-1` | S-1 RTC browse (better than GRD for terrain) | Level12 png | scene-based from 2025-01 | 12 | **no** (you have GRD COGs, not RTC tiles) | 200 at z=5; domain 2025-01-10/… |
|
|
||||||
| `OPERA_L3_DIST-ALERT-HLS_Color_Index` | Vegetation disturbance / clearing alert | Level12 png | ~2–3 d | 12 | no | 200 |
|
|
||||||
| `OPERA_L3_DIST-ANN-HLS_Color_Index` | Annual DIST | Level12 png | yearly | 12 | no | in caps |
|
|
||||||
| `OPERA_L3_Dynamic_Surface_Water_Extent-HLS` | Surface water / flood (HLS, 30 m) | Level12 png | ~2–3 d | 12 | no | 200 at z=5 |
|
|
||||||
| `OPERA_L3_Dynamic_Surface_Water_Extent-Sentinel-1` | Surface water from S-1 (clouds irrelevant) | Level12 png | S-1 revisit | 12 | no | 200 at z=5 |
|
|
||||||
| `NISAR_L2_Geocoded_Polarimetric_Covariance` | NISAR early browse | Level13 png | when downlinked | 13 | no | 200 (layer exists; coverage still sparse) |
|
|
||||||
| `SMAP_L4_Analyzed_Surface_Soil_Moisture` | Soil moisture | Level6 png | daily | 6 | no | 200 |
|
|
||||||
| `SMAP_L3_Active_Sigma0_VV` | SMAP radar σ0 | Level6 png | 2–3 d | 6 | no | in caps (SMAP radar died 2015 — historical) |
|
|
||||||
|
|
||||||
No ICEYE / Capella / Umbra / ALOS PALSAR **daily** layers in this GIBS 3857 dump.[4] ALOS shows up as mosaics on Planetary Computer (section 3).
|
|
||||||
|
|
||||||
### 1.4 Thermal / fire / volcano
|
|
||||||
|
|
||||||
Sparse PNG overlays: **empty tiles 404**. Capabilities + DescribeDomains still 200. Frontend must tolerate 404 (Leaflet does).
|
|
||||||
|
|
||||||
| id | what you see | TMS | cadence | max zoom | already have? | probe |
|
|
||||||
|---|---|---|---|---|---|---|
|
|
||||||
| `VIIRS_SNPP_Thermal_Anomalies_375m_All` | 375 m hotspots | **Level8** png (not 9) | daily | 8 | **yes**, but wired as Level9 | Domain 200; many tiles 404 |
|
|
||||||
| `VIIRS_NOAA20_Thermal_Anomalies_375m_All` | NOAA-20 hotspots | Level8 png | daily | 8 | no | Domain 200 (`2020-01-01/…` through at least 2025-09); tiles 404 if no fire in tile |
|
|
||||||
| `VIIRS_NOAA21_Thermal_Anomalies_375m_All` | NOAA-21 hotspots | Level8 png | daily | 8 | no | same |
|
|
||||||
| `VIIRS_*_Thermal_Anomalies_375m_{Day,Night}` | day/night split | Level8 png | daily | 8 | no | in caps |
|
|
||||||
| `MODIS_{Terra,Aqua,Combined}_Thermal_Anomalies_All` | 1 km MODIS fire | Level7 png | daily | 7 | no | in caps |
|
|
||||||
| `GOES-East_ABI_FireTemp` | geostationary fire RGB | Level7 png | ~10 min | 7 | no | 200 |
|
|
||||||
|
|
||||||
Also keep FIRMS CSV — points beat raster for click/query.
|
|
||||||
|
|
||||||
### 1.5 Night lights (beyond current DNB ENCC)
|
|
||||||
|
|
||||||
| id | what you see | TMS / ext | cadence | max zoom | already have? | probe |
|
|
||||||
|---|---|---|---|---|---|---|
|
|
||||||
| `VIIRS_NOAA20_DayNightBand` | NOAA-20 DNB | Level7 png | daily | 7 | no | 200 |
|
|
||||||
| `VIIRS_NOAA21_DayNightBand` | NOAA-21 DNB | Level7 png | daily | 7 | no | 200 |
|
|
||||||
| `VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance` | radiance, not ENCC | Level8 png | daily | 8 | no | 200 |
|
|
||||||
| `VIIRS_SNPP_DayNightBand_At_Sensor_Radiance` | SNPP radiance | Level8 png | daily | 8 | no | 200 |
|
|
||||||
| `VIIRS_NOAA20_DayNightBand_AtSensor_M15` | DNB+M15 composite jpg | Level8 jpg | daily | 8 | no | 200 |
|
|
||||||
| `VIIRS_Night_Lights` | Black-marble-style annual-ish | Level8 png | time-dim | 8 | no | 200 on 2026-08-27 mosaic date |
|
|
||||||
| `VIIRS_CityLights_2012` | Static 2012 city lights | Level8 jpg | **static** (`has_time=false`) | 8 | no | 200 |
|
|
||||||
|
|
||||||
`VIIRS_Black_Marble` and `VIIRS_NOAA20_DayNightBand_ENCC` are in caps; ENCC-NOAA20 returned HTTP 400 on the Level8 template we tried — do not ship until DescribeDomains + a known-good date are wired. SNPP ENCC stays as the current layer.
|
|
||||||
|
|
||||||
### 1.6 Ocean
|
|
||||||
|
|
||||||
| id | what you see | TMS | cadence | max zoom | probe |
|
|
||||||
|---|---|---|---|---|---|
|
|
||||||
| `GHRSST_L4_MUR_Sea_Surface_Temperature` | 1 km MUR SST | Level7 png | daily | 7 | 200 |
|
|
||||||
| `GHRSST_L4_MUR_Sea_Surface_Temperature_Anomalies` | SST anomaly | Level7 png | daily | 7 | in caps |
|
|
||||||
| `MODIS_Aqua_L3_SST_MidIR_4km_Night_Daily` | MODIS SST | Level6 png | daily | 6 | 200 |
|
|
||||||
| `MODIS_Aqua_L2_Chlorophyll_A` | Aqua chl-a | Level7 png | daily | 7 | 200 |
|
|
||||||
| `VIIRS_SNPP_L2_Chlorophyll_A` | VIIRS chl-a | Level7 png | daily | 7 | 200 |
|
|
||||||
| `VIIRS_NOAA20_Chlorophyll_a` | NOAA-20 chl-a | Level7 png | daily | 7 | 200 |
|
|
||||||
| `OCI_PACE_Chlorophyll_a` | PACE OCI chl-a | Level7 png | daily | 7 | 200 |
|
|
||||||
| `S3A_OLCI_Chlorophyll_a` | Sentinel-3A OLCI chl-a | Level7 png | daily | 7 | 200 |
|
|
||||||
| `S3B_OLCI_Chlorophyll_a` | Sentinel-3B OLCI | Level7 png | daily | 7 | in caps |
|
|
||||||
| `MODIS_Terra_Sea_Ice` | sea ice | Level7 png | daily | 7 | 200 |
|
|
||||||
| `GHRSST_L4_MUR_Sea_Ice_Concentration` | MUR ice | Level7 png | daily | 7 | in caps |
|
|
||||||
|
|
||||||
No dedicated “SAR oil slick” GIBS layer in the 3857 dump. Closest: OPERA RTC / DSWx-S1 + existing S-1 GRD TiTiler.
|
|
||||||
|
|
||||||
### 1.7 Vegetation / burn / flood / precip / atm
|
|
||||||
|
|
||||||
| id | what you see | TMS | cadence | max zoom | probe |
|
|
||||||
|---|---|---|---|---|---|
|
|
||||||
| `MODIS_Terra_NDVI_8Day` | NDVI | Level9 png | 8-day | 9 | 200 |
|
|
||||||
| `MODIS_Terra_L3_NDVI_16Day` | NDVI 16-day | Level9 png | 16-day | 9 | 200 |
|
|
||||||
| `IMERG_Precipitation_Rate` | GPM IMERG rain | Level6 png | sub-daily | 6 | 200 |
|
|
||||||
| `MODIS_Terra_Aerosol` | AOD | Level6 png | daily | 6 | 200 |
|
|
||||||
| `MODIS_Terra_Land_Surface_Temp_Day` | LST | Level7 png | daily | 7 | 200 |
|
|
||||||
| `VIIRS_SNPP_Land_Surface_Temp_Day` | VIIRS LST | Level7 png | daily | 7 | 200 |
|
|
||||||
| `AIRS_L3_Carbon_Monoxide_500hPa_Volume_Mixing_Ratio_Daily_Night` | CO (fires, industry) | Level6 png | daily | 6 | 200 |
|
|
||||||
| `OMI_NO2` / `OMI_Aerosol_Index` | NO2 / smoke index | Level6 png | daily | 6 | OMI AI 200; several OMPS 200 |
|
|
||||||
| `MODIS_Water_Mask` | static water mask | Level9 png | static | 9 | 200 |
|
|
||||||
|
|
||||||
MODIS burned-area monthly (`MCD64` / `MODIS_Combined_L3_Burned_Area_Monthly`) is in caps; our dated tile 400’d — wire only after a DescribeDomains date hits 200.
|
|
||||||
|
|
||||||
### 1.8 DEM (satellite-derived, tileable)
|
|
||||||
|
|
||||||
| id | what you see | TMS / ext | cadence | max zoom | probe |
|
|
||||||
|---|---|---|---|---|---|
|
|
||||||
| `SRTM_Color_Index` | SRTM elevation color | Level12 png | static | 12 | 200 |
|
|
||||||
| `ASTER_GDEM_Color_Index` | ASTER GDEM color | Level12 png | static | 12 | 200 |
|
|
||||||
| `ASTER_GDEM_Color_Shaded_Relief` | ASTER hillshade | Level12 jpg | static | 12 | 200 |
|
|
||||||
| `ASTER_GDEM_Greyscale_Shaded_Relief` | grey hillshade | Level12 jpg | static | 12 | in caps |
|
|
||||||
| `GEDI_ISS_L3_Canopy_Height_Mean_RH100_201904-202303` | GEDI canopy height | Level7 png | static epoch | 7 | related GEDI biomass 200 |
|
|
||||||
|
|
||||||
Blue Marble shaded relief is **already** the basemap — these are extra.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Other XYZ / WMTS / WMS (no key)
|
|
||||||
|
|
||||||
Ranked after GIBS for signal/$; still free.
|
|
||||||
|
|
||||||
| id | what you see | provider | URL pattern | key? | CORS | cadence | max zoom / res | license / attribution | Pi fit | already have? | probe 2026-08-29 |
|
|
||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
||||||
| `iem_goes_east_conus_ch02` | GOES-East CONUS ABI ch02 vis, **latest** | Iowa State IEM | `https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/goes_east_conus_ch02/{z}/{x}/{y}.png` | no | `*` | ~5 min cache header | TMS; vis ~1 km | Cite IEM / NOAA GOES[6][7] | **browser** (same stack as NEXRAD) | no | 200 image/png `*` |
|
|
||||||
| `iem_goes_east_conus_ch13` | GOES-East CONUS IR ch13 | IEM | `…/goes_east_conus_ch13/{z}/{x}/{y}.png` | no | `*` | ~5 min | IR ~2 km | IEM[6] | browser | no | 200 |
|
|
||||||
| `iem_goes_east_fulldisk_ch02` | GOES-East full disk vis | IEM | `…/goes_east_fulldisk_ch02/{z}/{x}/{y}.png` | no | `*` | ~5 min | full disk | IEM[6] | browser | no | 200 |
|
|
||||||
| `iem_goes_west_conus_ch02` | GOES-West CONUS vis | IEM | `…/goes_west_conus_ch02/{z}/{x}/{y}.png` | no | `*` | ~5 min | | IEM[6] | browser | no | 200 |
|
|
||||||
| `iem_goes_vis_1km` | Legacy name → GOES-East vis | IEM | `…/goes-vis-1km/{z}/{x}/{y}.png` | no | `*` | ~5 min | | IEM[6] | browser | no | 200 |
|
|
||||||
| IEM GOES template | Any bird/sector/channel | IEM | `goes_{east\|west}_{fulldisk\|conus\|mesoscale-1\|mesoscale-2\|alaska\|puertorico}_ch{01–16}`[6] | no | `*` | NRT | 16 ABI bands | IEM[6] | browser | no | template documented; ch02/ch13 probed |
|
|
||||||
| `eumet_msg_natural` | Meteosat natural color | EUMETSAT EUMETView GeoServer | WMS `https://view.eumetsat.int/geoserver/ows` layer `msg_fes:rgb_natural` EPSG:3857 GetMap | no | `*` | NRT | SEVIRI ~3 km | EUMETSAT viz; cite EUMETSAT[18] | **browser `L.tileLayer.wms`** (not XYZ). Caps 200, 165 layer names | no | GetMap 200 image/png `*` |
|
|
||||||
| `eumet_msg_ir108` | Meteosat IR 10.8 | EUMETView | WMS `msg_fes:ir108` | no | `*` | NRT | | EUMETSAT | browser WMS | no | name in caps |
|
|
||||||
| `eumet_msg_fire` | Meteosat fire | EUMETView | WMS `msg_fes:fire` | no | `*` | NRT | | EUMETSAT | browser WMS | no | name in caps |
|
|
||||||
| `eumet_mtg_ir105` | MTG-I IR | EUMETView | WMS `mtg_fd:ir105_hrfi` | no | `*` | NRT | FCI | EUMETSAT | browser WMS | no | name in caps |
|
|
||||||
| `eumet_s3_olci_rgb` | S3 OLCI RGB mosaic | EUMETView | WMS `copernicus:daily_sentinel3ab_olci_l1_rgb_fulres` | no | `*` | daily | OLCI | Copernicus/EUMETSAT | browser WMS | no | name in caps |
|
|
||||||
| `eumet_s3_chl` | S3 chl-a | EUMETView | WMS `copernicus:daily_sentinel3ab_olci_l2_chl_fullres` | no | `*` | daily | | Copernicus | browser WMS | no | name in caps |
|
|
||||||
| `gfw_glad_s2` | GLAD Sentinel-2 deforestation alerts | GFW tile cache | `https://tiles.globalforestwatch.org/umd_glad_sentinel2_alerts/latest/default/{z}/{x}/{y}.png` | no | `*` **if `Origin` header** (null without it) | ~daily | raster z 0–22 documented[15] | WRI/UMD; cite GFW | **browser** (Leaflet sends Origin) | no | 200 image/png; with Origin → CORS `*` |
|
|
||||||
| `gfw_integrated` | Integrated deforestation alerts | GFW | `https://tiles.globalforestwatch.org/gfw_integrated_alerts/latest/default/{z}/{x}/{y}.png` | no | `*` + Origin | ~daily | | GFW | browser | no | 200 |
|
|
||||||
| `gfw_tcl` | UMD tree-cover loss | GFW | `https://tiles.globalforestwatch.org/umd_tree_cover_loss/latest/tcd_30/{z}/{x}/{y}.png` | no | (same host) | annual | | GFW/UMD | browser | no | 200 |
|
|
||||||
| `star_goes19_fd_geocolor` | GOES-19 full-disk GeoColor **JPEG** (not XYZ) | NOAA NESDIS STAR CDN | `https://cdn.star.nesdis.noaa.gov/GOES19/ABI/FD/GEOCOLOR/latest.jpg` also `…/CONUS/GEOCOLOR/latest.jpg` | no | `*` | minutes | full-disk / CONUS image | NOAA | **not a map layer** — optional lightbox. Do not tile-proxy | no | 200 jpeg `*`[21] |
|
|
||||||
| `star_goes18_fd_geocolor` | GOES-18 FD GeoColor JPEG | STAR | `https://cdn.star.nesdis.noaa.gov/GOES18/ABI/FD/GEOCOLOR/latest.jpg` | no | `*` | minutes | | NOAA | lightbox only | no | 200 |
|
|
||||||
|
|
||||||
IEM JSON `…/GOES/conus/channel02/GOES-16_C02.json` is **stale** (`generated_at` 2025-04-07) but the **tile names still 200**. Prefer GIBS GeoColor when you need a time slider; prefer IEM when you want “whatever is latest” with zero time plumbing.[6][7]
|
|
||||||
|
|
||||||
### 2.x Works but **not** browser-direct (no CORS)
|
|
||||||
|
|
||||||
| id | what you see | URL | CORS | Pi fit | probe |
|
|
||||||
|---|---|---|---|---|---|
|
|
||||||
| RAMMB/CIRA SLIDER GeoColor tiles | GOES-19 / Himawari / JPSS loops, ~10 min | Times: `https://rammb-slider.cira.colostate.edu/data/json/goes-19/full_disk/geocolor/latest_times.json` (`timestamps_int`). Tile: `https://rammb-slider.cira.colostate.edu/data/imagery/{YYYY}/{MM}/{DD}/goes-19---full_disk/geocolor/{ts}/{zz}/{yyy}_{xxx}.png` e.g. `…/2026/08/28/goes-19---full_disk/geocolor/20260828225021/00/000_000.png`. Himawari times JSON also 200. | **none** | **Do not proxy tiles through the Pi.** Bookmark / deep-link SLIDER instead.[19][26] | times 200; tile 200 png; CORS null |
|
|
||||||
| NICT Himawari-8 Real-time Web | 10-min full disk PNG grid | `https://himawari8.nict.go.jp/img/D531106/latest.json` then `https://himawari8.nict.go.jp/img/D531106/2d/550/{YYYY}/{MM}/{DD}/{HHMMSS}_{x}_{y}.png` | **none** | same — no Pi proxy | latest.json 200; tile 200 png; CORS null[22] |
|
|
||||||
| OpenAerialMap | Per-scene TMS of open UAV/sat | `https://api.openaerialmap.org/meta` → `properties.tms` | CORS **only** `https://map.openaerialmap.org` | not usable from the dashboard origin without a proxy; opportunistic, not a global basemap[23][25] | meta 200 |
|
|
||||||
| USGS LandsatLook STAC | Landsat C2 STAC | `https://landsatlook.usgs.gov/stac-server` | CORS locked to `https://landsatlook.usgs.gov/stac-server` | backend-only if ever; prefer Earth Search / PC / GIBS HLS[24] | collections + search 200 |
|
|
||||||
| NOAA CoastWatch ERDDAP WMS (`jplMURSST41`) | MUR SST WMS | `https://coastwatch.pfeg.noaa.gov/erddap/wms/jplMURSST41/request` | mixed | **flaky**: GetCapabilities 200 earlier, **503** on later GetMap/GetCapabilities. Prefer GIBS MUR | 503 on 2nd pass |
|
|
||||||
| RainViewer `satellite.infrared` | would be IR sat frames | `https://api.rainviewer.com/public/weather-maps.json` | `*` | **empty list** (`"infrared": []`) at probe time — do not ship. Radar path already in product[20] | JSON 200, satellite IR empty |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. STAC / COG (TiTiler, same pattern as Sentinel-1)
|
|
||||||
|
|
||||||
Do **not** stream COGs through the Pi for a basemap. Viewport bbox + short datetime window + SAS/public HTTPS + existing TiTiler. Prefer GIBS HLS / OPERA tiles (section 1) when a browse PNG is enough.
|
|
||||||
|
|
||||||
| id | what you see | provider | STAC | key? | CORS | cadence | res | license | Pi fit | already have? | probe |
|
|
||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
||||||
| `sentinel-2-l2a` (Earth Search) | S2 L2A COGs, public HTTPS | Element 84 / AWS Open Data | `https://earth-search.aws.element84.com/v1` collections: `sentinel-2-l2a`, `sentinel-2-c1-l2a`, `sentinel-2-l1c`, `sentinel-2-pre-c1-l2a`, `sentinel-1-grd`, `landsat-c2-l2`, `naip`, `cop-dem-glo-30`, `cop-dem-glo-90`[8][9] | no | STAC `*` | S2 ~5 d | 10 m | Copernicus open; AWS public bucket HTTPS (not requester-pays for these COGs)[9] | **backend same as S-1**: search → TCI/visual COG → TiTiler. Live item `S2A_40RCP_20260827_0_L2A` href `https://sentinel-cogs.s3.us-west-2.amazonaws.com/…/TCI.tif` | no | collections + search 200 `*` |
|
|
||||||
| `sentinel-2-l2a` (Planetary Computer) | same S2 on Azure | Microsoft PC | `https://planetarycomputer.microsoft.com/api/stac/v1/collections/sentinel-2-l2a` | SAS token (unsigned search works) | STAC `*` | ~5 d | 10 m | Copernicus; Azure blob needs SAS like current S-1 | backend same as S-1 | no | collection + search 200 `*` (136 collections listed)[10][11] |
|
|
||||||
| `sentinel-1-rtc` | S-1 IW RTC γ0 COGs | PC / Catalyst | `/collections/sentinel-1-rtc` | **PC account required to retrieve SAS** for RTC blobs[12] | STAC `*` | IW land | ~10 m pixels | **CC BY 4.0**[12] | backend same as S-1 **plus** PC login for SAS. Prefer GIBS OPERA RTC tiles if browse is enough | no | collection 200; search item `S1D_IW_GRDH_…_rtc` assets `vv,vh,tilejson,rendered_preview` |
|
|
||||||
| `sentinel-1-grd` (PC) | GRD | PC | `/collections/sentinel-1-grd` | SAS | `*` | 6–12 d | | Copernicus | **already have** | yes | 200 |
|
|
||||||
| `sentinel-1-grd` (Earth Search) | GRD on AWS | E84 | `/collections/sentinel-1-grd` | requester-pays **s3://** URLs per E84 README[9] | `*` | | | Copernicus | worse than PC for the Pi (AWS creds) | no | collection 200 |
|
|
||||||
| `landsat-c2-l2` | Landsat 8/9 SR | E84 + PC | both catalogs | no / SAS | `*` | 8–16 d | 30 m | USGS public | backend TiTiler; or just use GIBS HLS | no | both 200 |
|
|
||||||
| `hls2-s30` / `hls2-l30` | HLS v2 COGs | PC | `/collections/hls2-s30`, `hls2-l30` | SAS | `*` | 2–3 d | 30 m | NASA | prefer GIBS HLS tiles | no | collections 200 |
|
|
||||||
| `goes-cmi` | GOES Cloud & Moisture Imagery COGs | PC | `/collections/goes-cmi` | SAS | `*` | 5–10 min | ABI | NOAA | **overkill vs GIBS/IEM tiles** | no | collection 200 |
|
|
||||||
| `modis-14A1-061` / `modis-64A1-061` | MODIS fire / burned area | PC | `/collections/modis-14A1-061`, `modis-64A1-061` | SAS | `*` | daily / monthly | 1 km / 500 m | NASA | prefer GIBS fire tiles + FIRMS | no | 200 |
|
|
||||||
| `alos-palsar-mosaic` / `alos-fnf-mosaic` | ALOS PALSAR yearly mosaic / forest-nonforest | PC | those collection ids | SAS | `*` | **annual** | 25 m | JAXA (check collection) | backend mosaic, not live SAR | no | 200 |
|
|
||||||
| `nasadem` / `cop-dem-glo-30` | DEM COGs | PC + E84 | `nasadem`, `cop-dem-glo-30` | public / SAS | `*` | static | 30 m | NASA / Copernicus | prefer GIBS SRTM/ASTER tiles | no | 200 |
|
|
||||||
| `naip` | USDA NAIP aerial (CONUS) | E84 + PC | `naip` | no | `*` | leaf-on, not NRT | ~0.6 m | USDA | CONUS only; huge. Optional TiTiler | no | 200 |
|
|
||||||
| `io-lulc-annual-v02` | 10 m land cover | PC | `io-lulc-annual-v02` | SAS | `*` | annual | 10 m | various | overlay, not sat photo | no | 200 |
|
|
||||||
| CDSE `sentinel-2-l2a` / `sentinel-1-grd` | Copernicus Dataspace STAC | ESA CDSE | `https://stac.dataspace.copernicus.eu/v1/collections/sentinel-2-l2a` (lowercase ids work; `SENTINEL-2` 404) | **free account** for many assets | **CORS none** | same as ESA | | Copernicus | backend only; Earth Search/PC easier on a Pi | no | collection 200, CORS null. List endpoint is paginated (first page was CLMS burned-area COGs)[14] |
|
|
||||||
|
|
||||||
PC catalog also has Sentinel-3 OLCI/SLSTR NetCDF, Sentinel-5P, GOES-GLM — NetCDF is a bad TiTiler citizen; use GIBS/EUMETView for those.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Free-account / license-gated (no card this week)
|
|
||||||
|
|
||||||
| id | note | why not a dropdown tomorrow |
|
|
||||||
|---|---|---|
|
|
||||||
| Microsoft PC SAS for RTC (and some blobs) | “A Planetary Computer account is required to retrieve SAS tokens to read the RTC data.”[12] | Search is open; **read** needs an account. GRD path you already have may not need this. |
|
|
||||||
| Copernicus Data Space (`stac.dataspace.copernicus.eu`) | STAC search 200 without cookie; **no CORS**; downloads often need a free CDSE login | Use Earth Search/PC unless you want official ESA provenance |
|
|
||||||
| JAXA P-Tree / Himawari Monitor | Himawari standard data, account | NICT/GIBS already cover browse |
|
|
||||||
| EUMETSAT Data Store | full MTG/MSG granules | EUMETView WMS is the browse path |
|
|
||||||
| FIRMS map key | already in product | add `VIIRS_NOAA20_NRT` / `VIIRS_NOAA21_NRT` before SNPP sunset |
|
|
||||||
| USGS ERS / EarthExplorer | Landsat/ASTER download login | GIBS HLS + Earth Search cover browse |
|
|
||||||
| Planet Tropical Forest Observatory | paid successor after NICFI | see skip |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Skip / costs money / dead
|
|
||||||
|
|
||||||
| id | why |
|
|
||||||
|---|---|
|
|
||||||
| **NICFI / Planet tropical mosaics (free)** | Free NICFI phase **ended 1 Apr 2025**. Removed from GFW and Collect Earth Online. Successor is Planet **Tropical Forest Observatory (subscription)** or a future NICFI re-compete.[16][17] PC collections `planet-nicfi-analytic` / `planet-nicfi-visual` still exist but assets are **RFP winners only** + proprietary PLA.[13] |
|
|
||||||
| Sentinel Hub (paid tiers) | billed processing units |
|
|
||||||
| Google Earth Engine | billing project |
|
|
||||||
| Maxar / Planet commercial | $ |
|
|
||||||
| ICEYE commercial | no free global tile/STAC found this pass |
|
|
||||||
| Umbra / Capella / Maxar **open data** STAC | catalogs 200 (`maxar-opendata`, `umbra-open-data-catalog`) but **disaster events only**, not a standing layer |
|
|
||||||
| Esri World Imagery / Clarity | tiles 200 CORS `*` — **ToS not a free basemap we should wrap** |
|
|
||||||
| Mapbox / Google satellite | key + ToS |
|
|
||||||
| GEE Dynamic World / NICFI in EE | EE billing |
|
|
||||||
| `nowcoast.noaa.gov` | HTTP **403** |
|
|
||||||
| FIRMS WMS (`firms.modaps.eosdis.nasa.gov/wms/…`) | HTTP **404** — use CSV + GIBS |
|
|
||||||
| RainViewer satellite IR | payload empty[20] |
|
|
||||||
| CoastWatch ERDDAP | 503 at probe; GIBS MUR replaces SST |
|
|
||||||
| Proxying RAMMB or NICT tiles | no CORS; would soak the home uplink |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Implementation notes for builders
|
|
||||||
|
|
||||||
1. **GIBS dropdown:** reuse `MAP_LAYERS` in `app/gibs_map.py`. New rows are `{id, title, tms, format, has_time, max_zoom}`. Time-domain fetch already exists.
|
|
||||||
2. **SNPP sunset:** NOAA-20/21 true color, DNB, thermal, FIRMS datasets first. SNPP true color can stay as fallback until 2026-11-01.
|
|
||||||
3. **Fix thermal TMS:** caps say `GoogleMapsCompatible_Level8` for `VIIRS_*_Thermal_Anomalies_375m_*`. Level9 GetTile is HTTP 400 XML.
|
|
||||||
4. **GOES time:** either GIBS `{time}` ISO + existing date slider, or IEM “latest” XYZ with no time (simpler, CONUS/FD only).
|
|
||||||
5. **HLS / OPERA:** empty granules 404 — same as “today’s MODIS isn’t ingested yet”. Clamp latest date via DescribeDomains like current daily mosaics.
|
|
||||||
6. **Do not add TiTiler S2 as a global basemap.** 10 m COGs will thrash the Pi. GIBS HLS Level12 is the browse path; Earth Search TCI is a “inspect this viewport” action like S-1.
|
|
||||||
7. **EUMETView:** `L.tileLayer.wms` against `https://view.eumetsat.int/geoserver/ows`, layers `msg_fes:rgb_natural` / `msg_fes:ir108`. Caps CORS `*`.
|
|
||||||
8. **GFW:** send browser Origin (Leaflet does). No key.
|
|
||||||
9. **Attribution strings:** NASA GIBS acknowledgment[1]; IEM; EUMETSAT; GFW/UMD; NOAA STAR.
|
|
||||||
|
|
||||||
### Probe stats (this run)
|
|
||||||
|
|
||||||
- GIBS WMTS caps: 5 796 177 bytes, CORS `*`, 1315 layers.[4]
|
|
||||||
- Curated GIBS GetTile: **78/90 HTTP 200** first batch; extra GOES/DNB/HLS/OPERA/ocean 200 as tabulated.
|
|
||||||
- Earth Search collections (complete list): `sentinel-2-pre-c1-l2a`, `cop-dem-glo-30`, `naip`, `cop-dem-glo-90`, `landsat-c2-l2`, `sentinel-2-l2a`, `sentinel-2-l1c`, `sentinel-2-c1-l2a`, `sentinel-1-grd`.[8]
|
|
||||||
- Planetary Computer: 136 collections; S-1 RTC CC-BY-4.0.[11][12]
|
|
||||||
|
|
||||||
Raw probe JSON lives next to this file in the kanban workspace (`gibs_probes.json`, `wave2_probes.json`, `wave3_probes.json`, `gibs_all_layers.json`).
|
|
||||||
|
|
||||||
## Sources
|
|
||||||
|
|
||||||
[1] https://nasa-gibs.github.io/gibs-api-docs
|
|
||||||
[2] https://nasa-gibs.github.io/gibs-api-docs/access-basics
|
|
||||||
[3] https://nasa-gibs.github.io/gibs-api-docs/available-visualizations
|
|
||||||
[4] https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/1.0.0/WMTSCapabilities.xml
|
|
||||||
[5] https://worldview.earthdata.nasa.gov
|
|
||||||
[6] https://mesonet.agron.iastate.edu/ogc
|
|
||||||
[7] https://mesonet.agron.iastate.edu/GIS/goes.phtml
|
|
||||||
[8] https://earth-search.aws.element84.com/v1/collections
|
|
||||||
[9] https://github.com/Element84/earth-search
|
|
||||||
[10] https://planetarycomputer.microsoft.com/catalog
|
|
||||||
[11] https://planetarycomputer.microsoft.com/api/stac/v1/collections
|
|
||||||
[12] https://planetarycomputer.microsoft.com/dataset/sentinel-1-rtc
|
|
||||||
[13] https://planetarycomputer.microsoft.com/dataset/planet-nicfi-analytic
|
|
||||||
[14] https://stac.dataspace.copernicus.eu/v1/collections
|
|
||||||
[15] https://tiles.globalforestwatch.org
|
|
||||||
[16] https://www.collect.earth/planet-imagery-via-nicfi-is-no-longer-available-on-ceo
|
|
||||||
[17] https://www.globalforestwatch.org/blog/data-and-tools/planet-imagery-changes-gfw
|
|
||||||
[18] https://view.eumetsat.int/geoserver/ows?service=WMS&request=GetCapabilities
|
|
||||||
[19] https://rammb-slider.cira.colostate.edu
|
|
||||||
[20] https://api.rainviewer.com/public/weather-maps.json
|
|
||||||
[21] https://cdn.star.nesdis.noaa.gov/GOES19/ABI/FD/GEOCOLOR/latest.jpg
|
|
||||||
[22] https://himawari8.nict.go.jp
|
|
||||||
[23] https://api.openaerialmap.org/meta?limit=1
|
|
||||||
[24] https://landsatlook.usgs.gov/stac-server/collections
|
|
||||||
[25] https://openaerialmap.org
|
|
||||||
[26] https://bellingcat.gitbook.io/toolkit/more/all-tools/rammb-slider
|
|
||||||
[27] https://www.earthdata.nasa.gov/engage/open-data-services-software/earthdata-developer-portal/gibs-api
|
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
"""Feed helpers shared by the news spider (no Scrapy import)."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import datetime
|
|
||||||
import re
|
|
||||||
from email.utils import parsedate_to_datetime
|
|
||||||
from urllib.parse import urlparse
|
|
||||||
|
|
||||||
AUDIO_EXT = (".mp3", ".m4a", ".ogg", ".wav", ".aac", ".flac", ".opus")
|
|
||||||
|
|
||||||
|
|
||||||
def is_audio_url(url: str) -> bool:
|
|
||||||
path = urlparse(url or "").path.lower()
|
|
||||||
return any(path.endswith(ext) for ext in AUDIO_EXT)
|
|
||||||
|
|
||||||
|
|
||||||
def article_timestamp(pub_date: str | None) -> datetime.datetime:
|
|
||||||
"""Prefer the feed's pubDate/published; fall back to now (UTC)."""
|
|
||||||
if pub_date:
|
|
||||||
try:
|
|
||||||
return parsedate_to_datetime(pub_date).astimezone(datetime.timezone.utc)
|
|
||||||
except (TypeError, ValueError, IndexError):
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
raw = pub_date.replace("Z", "+00:00")
|
|
||||||
ts = datetime.datetime.fromisoformat(raw)
|
|
||||||
if ts.tzinfo is None:
|
|
||||||
ts = ts.replace(tzinfo=datetime.timezone.utc)
|
|
||||||
return ts
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
return datetime.datetime.now(datetime.timezone.utc)
|
|
||||||
|
|
||||||
|
|
||||||
# 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()
|
|
||||||
|
|
@ -3,51 +3,10 @@
|
||||||
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
|
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
|
||||||
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
|
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
|
||||||
|
|
||||||
import datetime
|
import logging
|
||||||
import logging
|
|
||||||
import psycopg2
|
import psycopg2
|
||||||
import os
|
import os
|
||||||
from scrapy.exceptions import DropItem
|
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:
|
class PostgresPipeline:
|
||||||
|
|
||||||
def __init__(self, db_config):
|
def __init__(self, db_config):
|
||||||
|
|
@ -55,8 +14,6 @@ class PostgresPipeline:
|
||||||
self.db_config = db_config
|
self.db_config = db_config
|
||||||
# 2. Initialize the set here so it exists when process_item is called
|
# 2. Initialize the set here so it exists when process_item is called
|
||||||
self.seen_urls = set()
|
self.seen_urls = set()
|
||||||
# 3. Future-dated drops, reported once per run in close_spider()
|
|
||||||
self.future_dated_dropped = 0
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_crawler(cls, crawler):
|
def from_crawler(cls, crawler):
|
||||||
|
|
@ -96,17 +53,8 @@ class PostgresPipeline:
|
||||||
self.connection.commit()
|
self.connection.commit()
|
||||||
|
|
||||||
def process_item(self, item, spider):
|
def process_item(self, item, spider):
|
||||||
url = item['url']
|
if item ['url'] in self.seen_urls:
|
||||||
if is_future_dated(item.get('timestamp')):
|
raise DropItem()
|
||||||
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:
|
try:
|
||||||
self.cur.execute("""
|
self.cur.execute("""
|
||||||
INSERT INTO articles (title, url, content, domain, timestamp)
|
INSERT INTO articles (title, url, content, domain, timestamp)
|
||||||
|
|
@ -120,23 +68,17 @@ class PostgresPipeline:
|
||||||
item['timestamp']
|
item['timestamp']
|
||||||
))
|
))
|
||||||
if self.cur.rowcount == 0:
|
if self.cur.rowcount == 0:
|
||||||
raise DropItem(f"Duplicate URL (database): {url}")
|
e = DropItem("Duplicate URL (database conflict)")
|
||||||
|
e.log_level = logging.DEBUG
|
||||||
|
raise e
|
||||||
self.connection.commit()
|
self.connection.commit()
|
||||||
return item
|
return item
|
||||||
except DropItem:
|
|
||||||
self.connection.rollback()
|
|
||||||
raise
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
spider.logger.error(f"Error saving to Postgres: {e}")
|
spider.logger.error(f"Error saving to Postgres: {e}")
|
||||||
self.connection.rollback()
|
self.connection.rollback()
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def close_spider(self, spider):
|
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.cur.close()
|
||||||
self.connection.close()
|
self.connection.close()
|
||||||
|
|
||||||
|
|
@ -146,3 +88,5 @@ from itemadapter import ItemAdapter
|
||||||
class NewsscraperPipeline:
|
class NewsscraperPipeline:
|
||||||
def process_item(self, item, spider):
|
def process_item(self, item, spider):
|
||||||
return item
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,13 +4,11 @@ from urllib.parse import urljoin, urlparse
|
||||||
import datetime
|
import datetime
|
||||||
import re
|
import re
|
||||||
|
|
||||||
from newsScraper.feed_util import article_timestamp, is_audio_url
|
|
||||||
|
|
||||||
|
|
||||||
class NewsRSSSpider(Spider):
|
class NewsRSSSpider(Spider):
|
||||||
"""Crawl the curated news sources in urls.txt and extract articles.
|
"""Crawl the curated news sources in urls.txt and extract articles.
|
||||||
|
|
||||||
urls.txt contains curated news HOMEPAGES and RSS/Atom feeds, so this spider
|
urls.txt contains 257 news HOMEPAGES (not feed URLs), so this spider
|
||||||
implements feed autodiscovery: it fetches each start URL, finds the
|
implements feed autodiscovery: it fetches each start URL, finds the
|
||||||
RSS/Atom feed link (`<link rel="alternate" type="application/rss+xml">`
|
RSS/Atom feed link (`<link rel="alternate" type="application/rss+xml">`
|
||||||
or a visible /rss|/feed link), follows it, and then follows each feed
|
or a visible /rss|/feed link), follows it, and then follows each feed
|
||||||
|
|
@ -89,8 +87,6 @@ class NewsRSSSpider(Spider):
|
||||||
or node.xpath('updated/text()').get()
|
or node.xpath('updated/text()').get()
|
||||||
)
|
)
|
||||||
if link:
|
if link:
|
||||||
if is_audio_url(link):
|
|
||||||
continue
|
|
||||||
yield scrapy.Request(
|
yield scrapy.Request(
|
||||||
link,
|
link,
|
||||||
callback=self.parse_article,
|
callback=self.parse_article,
|
||||||
|
|
@ -116,5 +112,5 @@ class NewsRSSSpider(Spider):
|
||||||
'url': response.url,
|
'url': response.url,
|
||||||
'text': pure_text,
|
'text': pure_text,
|
||||||
'domain': urlparse(response.url).netloc,
|
'domain': urlparse(response.url).netloc,
|
||||||
'timestamp': article_timestamp(response.meta.get('date')).isoformat()
|
'timestamp': datetime.datetime.now().isoformat()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,18 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Scheduler loop for the news scraper — crawl continuously.
|
"""Scheduler loop for the news scraper — hourly scrape at minute :00.
|
||||||
|
|
||||||
As soon as one Scrapy pass finishes, wait NEWS_SCRAPE_INTERVAL_S seconds
|
Replaces the k8s CronJob (`0 * * * *`) with an in-compose loop so the whole
|
||||||
and start the next. Two crawls never overlap (the loop is serial).
|
news pipeline lives inside docker-compose. Each iteration:
|
||||||
|
|
||||||
|
1. (optionally, on first boot) runs the Scrapy crawl once to seed data fast
|
||||||
|
2. sleeps until the next :NEWS_SCRAPE_MINUTE wall-clock boundary
|
||||||
|
|
||||||
|
Because the loop is serial, a crawl that overruns its hour simply delays the
|
||||||
|
next run to the following boundary — two crawls never overlap.
|
||||||
|
|
||||||
Env (all optional, 12-factor):
|
Env (all optional, 12-factor):
|
||||||
NEWS_SCRAPE_INTERVAL_S seconds between crawls (default 10)
|
NEWS_SCRAPE_MINUTE minute of the hour to fire (default 0)
|
||||||
NEWS_SCRAPE_RUN_ON_START "1" to crawl immediately on boot (default 1)
|
NEWS_SCRAPE_RUN_ON_START "1" to crawl once immediately on boot (default 1)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
@ -21,12 +27,19 @@ import time
|
||||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||||
logger = logging.getLogger("news.scraper")
|
logger = logging.getLogger("news.scraper")
|
||||||
|
|
||||||
INTERVAL_S = max(0, int(os.getenv("NEWS_SCRAPE_INTERVAL_S", "10")))
|
MINUTE = int(os.getenv("NEWS_SCRAPE_MINUTE", "0"))
|
||||||
RUN_ON_START = os.getenv("NEWS_SCRAPE_RUN_ON_START", "1").lower() in ("1", "true", "yes")
|
RUN_ON_START = os.getenv("NEWS_SCRAPE_RUN_ON_START", "1").lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
CRAWL_CMD = ["scrapy", "crawl", "articles"]
|
CRAWL_CMD = ["scrapy", "crawl", "articles"]
|
||||||
|
|
||||||
|
|
||||||
|
def seconds_until_next(minute: int) -> float:
|
||||||
|
"""Seconds until the next occurrence of ``minute`` past the hour (local time)."""
|
||||||
|
now = datetime.datetime.now()
|
||||||
|
nxt = now.replace(minute=minute, second=0, microsecond=0) + datetime.timedelta(hours=1)
|
||||||
|
return (nxt - now).total_seconds()
|
||||||
|
|
||||||
|
|
||||||
def run_crawl() -> None:
|
def run_crawl() -> None:
|
||||||
logger.info("scrape starting at %s", datetime.datetime.now().isoformat(timespec="seconds"))
|
logger.info("scrape starting at %s", datetime.datetime.now().isoformat(timespec="seconds"))
|
||||||
try:
|
try:
|
||||||
|
|
@ -38,14 +51,15 @@ def run_crawl() -> None:
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
logger.info(
|
logger.info(
|
||||||
"news scraper loop starting (interval_s=%s, run_on_start=%s)",
|
"news scraper loop starting (minute=%s, run_on_start=%s)",
|
||||||
INTERVAL_S, RUN_ON_START,
|
MINUTE, RUN_ON_START,
|
||||||
)
|
)
|
||||||
if RUN_ON_START:
|
if RUN_ON_START:
|
||||||
run_crawl()
|
run_crawl()
|
||||||
while True:
|
while True:
|
||||||
logger.info("next scrape in %ss", INTERVAL_S)
|
delay = seconds_until_next(MINUTE)
|
||||||
time.sleep(INTERVAL_S)
|
logger.info("next scrape at :%02d (in %.0fs)", MINUTE, delay)
|
||||||
|
time.sleep(delay)
|
||||||
run_crawl()
|
run_crawl()
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,336 +1,257 @@
|
||||||
https://www.investing.com/rss/news.rss
|
# --- NORTH AMERICA ---
|
||||||
https://www.ftchinese.com/rss
|
# USA
|
||||||
https://www.alwatan.com
|
https://www.npr.org
|
||||||
https://albiladpress.com
|
https://www.pbs.org/newshour
|
||||||
https://www.aletihad.ae/
|
https://www.usatoday.com
|
||||||
https://www.albayan.ae
|
https://www.cbsnews.com
|
||||||
https://www.aljazeera.com/xml/rss/all.xml
|
https://www.nbcnews.com
|
||||||
https://english.alarabiya.net/.mrss/en.xml
|
|
||||||
https://english.aawsat.com/home/rss
|
# Canada
|
||||||
https://www.newarab.com/rss
|
https://www.cbc.ca/news
|
||||||
https://www.skynewsarabia.com/rss/feeds/rss-1.xml
|
https://www.ctvnews.ca
|
||||||
https://www.thenationalnews.com/arc/outboundfeeds/rss/
|
https://globalnews.ca
|
||||||
https://www.arabnews.com/rss.xml
|
https://nationalpost.com
|
||||||
https://gulfnews.com/rss
|
https://www.thestar.com
|
||||||
https://www.kuwaittimes.com/feed/
|
|
||||||
https://www.omanobserver.om/feed/
|
# Mexico
|
||||||
https://www.khaleejtimes.com/rss/news
|
https://www.eluniversal.com.mx
|
||||||
http://www.akhbar-alkhaleej.com/rss/all
|
https://www.milenio.com
|
||||||
https://today.lorientleyour.com/rss
|
https://www.jornada.com.mx
|
||||||
https://www.annahar.com/english/rss
|
https://www.excelsior.com.mx
|
||||||
https://english.almayadeen.net/rss
|
https://aristeguinoticias.com
|
||||||
https://english.ahram.org.eg/rss/0/Home.aspx
|
|
||||||
https://www.dailynewsegypt.com/feed/
|
# --- SOUTH AMERICA ---
|
||||||
http://www.jordantimes.com/rss
|
# Brazil
|
||||||
https://www.alraimedia.com/rss
|
https://g1.globo.com
|
||||||
https://alghad.com/feed/
|
https://www.uol.com.br
|
||||||
https://nypost.com/feed/
|
https://agenciabrasil.ebc.com.br
|
||||||
https://gothamist.com/feed/
|
https://www.metropoles.com
|
||||||
https://www.cityandstateny.com/rss
|
https://www.terra.com.br/noticias
|
||||||
https://feeds.nytimes.com/nyt/rss/HomePage
|
|
||||||
https://www.thecity.nyc/rss/index.xml
|
# Argentina
|
||||||
https://brooklyneagle.com/feed/
|
https://www.infobae.com
|
||||||
https://www.reutersagency.com/feed/
|
https://www.clarin.com
|
||||||
https://newsatme.com/api/v1/rss/ap/world
|
https://www.lanacion.com.ar
|
||||||
https://feeds.bbci.co.uk/news/world/rss.xml
|
https://www.pagina12.com.ar
|
||||||
https://rss.dw.com/rdf/rss-en-all
|
https://www.cronista.com
|
||||||
https://www.france24.com/en/rss
|
|
||||||
https://www3.nhk.or.jp/rss/news/shakaitokushu.xml
|
# Colombia
|
||||||
https://www.cbc.ca/cctoc/rss/topstories.north
|
https://www.eltiempo.com
|
||||||
https://www.defensenews.com/arc/outboundfeeds/rss/
|
https://www.elespectador.com
|
||||||
https://therecord.media/feed
|
https://www.semana.com
|
||||||
https://www.cfr.org/rss/newsletters/daily-news-brief
|
https://www.bluradio.com
|
||||||
https://warontherocks.com/feed/
|
https://www.rcnradio.com
|
||||||
https://www.thecipherbrief.com/feed
|
|
||||||
https://www.foreignaffairs.com/rss.xml
|
# --- EUROPE ---
|
||||||
https://geopoliticalfutures.com/feed
|
# United Kingdom
|
||||||
# --- TACTICAL CYBER & VULNERABILITIES ---
|
https://www.bbc.com/news
|
||||||
https://www.bleepingcomputer.com/feed/
|
https://www.theguardian.com/uk
|
||||||
https://www.cisa.gov/cybersecurity-advisory-feeds
|
https://news.sky.com
|
||||||
https://krebsonsecurity.com/feed/
|
https://www.independent.co.uk
|
||||||
https://thehackernews.com/feeds/posts/default
|
https://metro.co.uk
|
||||||
https://www.darkreading.com/rss.xml
|
|
||||||
https://www.mandiant.com/resources/blog/rss.xml
|
# France
|
||||||
https://schneier.com/feed/atom/
|
https://www.france24.com/en
|
||||||
https://www.securityweek.com/feed/
|
https://www.lefigaro.fr
|
||||||
# --- REGIONAL THREAT LANDSCAPE ---
|
https://www.20minutes.fr
|
||||||
https://www.thenationalnews.com/rss/
|
https://www.francetvinfo.fr
|
||||||
https://www.scmp.com/rss/91/feed
|
https://www.lemonde.fr
|
||||||
https://www.batimes.com.ar/rss
|
|
||||||
https://brazilian.report/feed/
|
# Germany
|
||||||
https://www.khon2.com/feed/
|
https://www.dw.com/en
|
||||||
https://www.staradvertiser.com/feed/
|
https://www.tagesschau.de
|
||||||
https://www.westhawaiitoday.com/feed/
|
https://www.spiegel.de
|
||||||
https://mauinow.com/feed/
|
https://www.zeit.de
|
||||||
https://www.idahofallsidaho.gov/RSSFeed.aspx?ModID=1&CID=All-newsflash.xml
|
https://www.bild.de
|
||||||
https://www.eastidahonews.com/feed/
|
|
||||||
https://localnews8.com/feed/
|
# Spain
|
||||||
https://www.boisestatepublicradio.org/news.rss
|
https://elpais.com
|
||||||
https://www.illinoistimes.com/springfield/Rss.xml
|
https://www.elmundo.es
|
||||||
https://www.thecentersquare.com/search/?f=rss&t=article&l=20&s=start_time&fulltext=showtext&sd=desc&c%5B%5D=Illinois
|
https://www.rtve.es/noticias
|
||||||
https://chicago.suntimes.com/rss/index.xml
|
https://www.20minutos.es
|
||||||
https://wgntv.com/feed/
|
https://www.elconfidencial.com
|
||||||
http://feeds.indiana.statenews.net/rss/7b3aa09cdd5d5eac
|
|
||||||
https://fox59.com/feed/
|
# Italy
|
||||||
https://www.nwitimes.com/search/?f=rss&t=article&c=news/local&l=50&s=start_time&sd=desc
|
https://www.ansa.it
|
||||||
https://www.wishtv.com/feed/
|
https://www.corriere.it
|
||||||
https://www.kcci.com/topstories-rss
|
https://www.repubblica.it
|
||||||
https://www.myiowainfo.com/feed/
|
https://www.lastampa.it
|
||||||
https://feeds.feedburner.com/radioiowanews
|
https://tg24.sky.it
|
||||||
https://www.mississippivalleypublishing.com/search/?f=rss&t=article&c=the_hawk_eye&l=50&s=start_time&sd=desc
|
|
||||||
https://www.ksn.com/feed/
|
# Russia (State & Independent mix)
|
||||||
https://www.ksnt.com/feed/
|
https://tass.com
|
||||||
https://www.hdnews.net/feed/
|
https://www.interfax.ru
|
||||||
https://themercury.com/search/?f=rss&t=article&c=news&l=50&s=start_time&sd=desc
|
https://www.rt.com
|
||||||
https://www.wdrb.com/search/?f=rss&t=article&c=news&l=50&s=start_time&sd=desc
|
https://www.themoscowtimes.com
|
||||||
https://www.wtvq.com/feed/
|
https://meduza.io/en
|
||||||
https://www.wnky.com/feed/
|
|
||||||
https://www.wlky.com/topstories-rss
|
# --- ASIA ---
|
||||||
https://thehayride.com/feed/
|
# China
|
||||||
https://wgno.com/feed/
|
https://www.xinhuanet.com/english
|
||||||
https://feeds.feedburner.com/wbrz/news
|
https://www.chinadaily.com.cn
|
||||||
https://thelensnola.org/feed/
|
https://www.globaltimes.cn
|
||||||
https://www.pressherald.com/news/feed/
|
https://www.cgtn.com
|
||||||
https://www.centralmaine.com/feed/
|
https://www.scmp.com
|
||||||
https://www.bangordailynews.com/feed/
|
|
||||||
https://www.sunjournal.com/news/feed/
|
# India
|
||||||
https://www.wbaltv.com/topstories-rss
|
https://www.ndtv.com
|
||||||
https://www.manisteenews.com/news/feed/Latest-News-Feed-2564.php
|
https://timesofindia.indiatimes.com
|
||||||
https://www.theoaklandpress.com/feed/
|
https://indianexpress.com
|
||||||
https://www.macombdaily.com/feed/
|
https://www.thehindu.com
|
||||||
https://www.startribune.com/local/index.rss2
|
https://www.hindustantimes.com
|
||||||
https://www.wctrib.com/index.rss
|
|
||||||
https://www.austindailyherald.com/feed/
|
# Japan
|
||||||
https://helenair.com/search/?f=rss&t=article&l=50&s=start_time&sd=desc
|
https://www3.nhk.or.jp/nhkworld
|
||||||
https://www.ktvq.com/news.rss
|
https://www.japantimes.co.jp
|
||||||
https://mtstandard.com/search/?f=rss&t=article&l=50&s=start_time&sd=desc
|
https://www.asahi.com/ajw
|
||||||
https://www.ketv.com/topstories-rss
|
https://mainichi.jp/english
|
||||||
https://nebraskaexaminer.com/feed/
|
https://english.kyodonews.net
|
||||||
https://kearneyhub.com/rss
|
|
||||||
https://www.wowt.com/rss
|
# South Korea
|
||||||
https://thenevadaindependent.com/feed/
|
https://en.yna.co.kr
|
||||||
https://www.8newsnow.com/feed/
|
https://www.koreaherald.com
|
||||||
https://www.reviewjournal.com/feed/
|
https://koreajoongangdaily.joins.com
|
||||||
https://thisisreno.com/feed/
|
https://www.donga.com/en
|
||||||
https://www.conwaydailysun.com/search/?f=rss&t=article&c=berlin_sun/community/news&l=50&s=start_time&sd=desc
|
https://english.chosun.com
|
||||||
https://newhampshirebulletin.com/feed/
|
|
||||||
https://www.nhgazette.com/feed/
|
# --- AFRICA ---
|
||||||
https://www.nhbr.com/feed/
|
# South Africa
|
||||||
https://www.nj.com/arc/outboundfeeds/rss/?outputType=xml
|
https://www.news24.com
|
||||||
https://www.njspotlightnews.org/feed/
|
https://www.iol.co.za
|
||||||
https://njmonthly.com/feed/
|
https://www.dailymaverick.co.za
|
||||||
https://www.trentonian.com/feed/
|
https://www.sabcnews.com
|
||||||
https://www.krqe.com/feed/
|
https://www.timeslive.co.za
|
||||||
https://www.santafenewmexican.com/search/?f=rss&t=article&l=50&s=start_time&sd=desc
|
|
||||||
https://www.easternnewmexiconews.com/rss
|
# Nigeria
|
||||||
https://www.koat.com/topstories-rss
|
https://www.vanguardngr.com
|
||||||
https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml
|
https://punchng.com
|
||||||
https://www.thecity.nyc/feed/
|
https://dailypost.ng
|
||||||
https://www.nbcnewyork.com/?rss=y
|
https://saharareporters.com
|
||||||
https://www.wral.com/news/rss/48/
|
https://thenationonlineng.net
|
||||||
https://www.cbs17.com/news/north-carolina-news/feed/
|
|
||||||
https://abc11.com/feed/
|
# --- MIDDLE EAST ---
|
||||||
https://myfox8.com/news/feed/
|
# General Region
|
||||||
https://www.kxnet.com/feed/
|
https://www.aljazeera.com
|
||||||
https://www.wday.com/feed/
|
https://english.alarabiya.net
|
||||||
https://www.jamestownsun.com/index.rss
|
https://www.timesofisrael.com
|
||||||
https://www.inforum.com/index.rss
|
https://www.tehrantimes.com
|
||||||
http://rssfeeds.wkyc.com/wkyc/news
|
https://www.middleeasteye.net
|
||||||
https://theohiostar.com/feed/
|
|
||||||
https://feeds.feedblitz.com/wtol/news
|
# --- OCEANIA ---
|
||||||
https://www.wcpo.com/news.rss
|
# Australia
|
||||||
https://kfor.com/feed/
|
https://www.abc.net.au/news
|
||||||
https://oklahomawatch.org/feed/
|
https://www.news.com.au
|
||||||
https://freepressokc.com/feed/
|
https://www.9news.com.au
|
||||||
https://osagenews.org/feed/
|
https://www.smh.com.au
|
||||||
http://rssfeeds.kgw.com/kgw/local
|
https://www.theage.com.au
|
||||||
https://www.koin.com/feed/
|
# --- USA: MAJOR CITIES & LOCAL ---
|
||||||
https://www.bendsource.com/bend/Rss.xml/feed
|
https://www.latimes.com
|
||||||
https://eugeneweekly.com/feed/
|
https://www.chicagotribune.com
|
||||||
https://www.wtae.com/topstories-rss
|
https://www.sfchronicle.com
|
||||||
https://www.montgomerycountypa.gov/RSSFeed.aspx?ModID=76&CID=All-0
|
https://www.bostonglobe.com
|
||||||
https://www.mainlinemedianews.com/feed/
|
https://www.seattletimes.com
|
||||||
https://www.dailylocal.com/feed/
|
https://www.houstonchronicle.com
|
||||||
https://www.wpri.com/feed/
|
https://www.inquirer.com
|
||||||
https://www.abc6.com/feed/
|
https://www.denverpost.com
|
||||||
https://whdh.com/regional/rhode-island/feed/
|
https://www.miamiherald.com
|
||||||
https://warwickpost.com/feed/
|
https://www.dallasnews.com
|
||||||
https://www.wyff4.com/topstories-rss
|
https://www.startribune.com
|
||||||
https://www.wispolitics.com/feed/
|
https://www.detroitnews.com
|
||||||
https://wiseye.org/feed/
|
https://www.ajc.com
|
||||||
https://wisconsinexaminer.com/feed/
|
https://www.nydailynews.com
|
||||||
https://trib.com/search/?f=rss&t=article&c=news/state-and-regional&l=50&s=start_time&sd=desc
|
https://nypost.com
|
||||||
https://wyofile.com/feed/
|
https://www.mercurynews.com
|
||||||
https://www.wyomingnews.com/search/?f=rss&t=article&c=news&l=50&s=start_time&sd=desc
|
https://www.baltimoresun.com
|
||||||
https://www.wyodaily.com/rss
|
https://www.oregonlive.com
|
||||||
https://www.wnct.com/news/north-carolina/feed/
|
https://www.cleveland.com
|
||||||
https://www.usnews.com/rss/news/north-carolina
|
https://www.tampabay.com
|
||||||
https://indyweek.com/feed/
|
|
||||||
https://portcitydaily.com/feed/
|
# --- EUROPE: LOCAL & INDEPENDENT ---
|
||||||
https://www.theguardian.com/uk/rss
|
https://www.manchestereveningnews.co.uk
|
||||||
https://feeds.bbci.co.uk/news/england/rss.xml
|
https://www.scotsman.com
|
||||||
https://www.lemonde.fr/rss/une.xml
|
https://www.belfasttelegraph.co.uk
|
||||||
https://www.ansa.it/sito/notizie/rss.xml
|
https://www.irishtimes.com
|
||||||
https://www.ilgiornale.it/feed
|
https://www.berliner-zeitung.de
|
||||||
https://www.larepublica.it/rss/homepage/rss2.xml
|
https://www.leparisien.fr
|
||||||
https://www.sueddeutsche.de/rss
|
https://www.corriere.it
|
||||||
https://www.welt.de/feeds/top-news.rss
|
https://www.elperiodico.com
|
||||||
https://www.rfi.fr/en/rss
|
https://kyivindependent.com
|
||||||
https://www.bangkokpost.com/rss
|
https://www.pravda.com.ua/en
|
||||||
https://thephnompenhpost.com/rss
|
https://balkaninsight.com
|
||||||
https://www.thejakartapost.com/rss
|
https://www.ekathimerini.com
|
||||||
https://www.straitstimes.com/news/singapore/rss.xml
|
https://www.swissinfo.ch
|
||||||
https://www.channelnewsasia.com/rss
|
https://www.thelocal.se
|
||||||
https://www.antaranews.com/rss/
|
https://www.thelocal.fr
|
||||||
https://www.irrawaddy.com/feed
|
https://www.thelocal.de
|
||||||
https://news.abs-cbn.com/rss
|
https://www.novinite.com
|
||||||
https://www.hindustantimes.com/feeds/rss
|
https://www.romania-insider.com
|
||||||
https://www.africanews.com/feed/rss
|
https://hungarytoday.hu
|
||||||
https://www.clarin.com/rss
|
https://polandin.com
|
||||||
https://www.lanacion.com.ar/rss
|
|
||||||
https://www.eluniversal.com.mx/rss
|
# --- MIDDLE EAST & CONFLICT ZONES ---
|
||||||
https://www.excelsior.com.mx/rss
|
https://www.haaretz.com
|
||||||
https://www.eltiempo.com/rss
|
https://www.jpost.com
|
||||||
https://www.elespectador.com/rss
|
https://www.timesofisrael.com
|
||||||
https://www.larepublica.pe/rss
|
https://www.rudaw.net/english
|
||||||
https://www.elcomercio.com/rss
|
https://www.kurdistan24.net/en
|
||||||
https://www.abc.net.au/news/feed/
|
https://www.middleeasteye.net
|
||||||
https://www.smh.com.au/rss/world.xml
|
https://www.al-monitor.com
|
||||||
https://www.theage.com.au/rss
|
https://www.dailysabah.com
|
||||||
https://www.brisbanetimes.com.au/rss
|
https://www.duvarenglish.com
|
||||||
https://www.stuff.co.nz/rss
|
https://english.aawsat.com
|
||||||
https://www.nzherald.co.nz/arcio/rss/
|
https://www.arabnews.com
|
||||||
https://www.rnz.co.nz/rss
|
https://www.thenationalnews.com
|
||||||
https://globalvoices.org/regions/africa/feed/
|
https://www.jordantimes.com
|
||||||
https://globalvoices.org/regions/asia/feed/
|
https://www.naharnet.com
|
||||||
https://globalvoices.org/regions/latin-america/feed/
|
https://www.tehrantimes.com
|
||||||
https://globalvoices.org/regions/eastern-europe/feed/
|
|
||||||
https://globalvoices.org/regions/middle-east-north-africa/feed/
|
# --- ASIA: HOTSPOTS & LOCAL ---
|
||||||
https://globalvoices.org/regions/south-asia/feed/
|
https://www.taipeitimes.com
|
||||||
https://globalvoices.org/regions/sub-saharan-africa/feed/
|
https://focustaiwan.tw
|
||||||
https://globalvoices.org/regions/west-africa/feed/
|
https://hongkongfp.com
|
||||||
https://globalvoices.org/regions/east-asia/feed/
|
https://www.bangkokpost.com
|
||||||
https://globalvoices.org/regions/southeast-asia/feed/
|
https://www.thejakartapost.com
|
||||||
https://globalvoices.org/regions/central-asia/feed/
|
https://www.straitstimes.com
|
||||||
https://globalvoices.org/regions/pacific/feed/
|
https://www.khmertimeskh.com
|
||||||
https://globalvoices.org/regions/caribbean/feed/
|
https://www.irrawaddy.com
|
||||||
https://www.townandcountry-mo.gov/rss.aspx
|
https://www.myanmarnow.org/en
|
||||||
https://feeds.smh.com.au/rssheadlines/national.xml
|
https://www.rappler.com
|
||||||
https://www.abc.net.au/local/rss/sydney/
|
https://www.philstar.com
|
||||||
https://www.voanews.com/rssfeeds
|
https://english.hani.co.kr
|
||||||
https://rss.feedspot.com/southeast_asian_rss_feeds
|
https://www.japantoday.com
|
||||||
https://www.crisisgroup.org/rss
|
https://www.caixinglobal.com
|
||||||
https://news.panasonic.com/global/rss/area01/index.xml
|
https://thediplomat.com
|
||||||
https://news.panasonic.com/global/rss/area04/index.xml
|
|
||||||
https://allafrica.com/tools/headlines/rdf/latest/headlines.rdf
|
# --- LATIN AMERICA & AFRICA: LOCAL ---
|
||||||
https://www.afro.who.int/rss-feeds
|
https://buenosairesherald.com
|
||||||
https://pressat.co.uk/rss-list
|
https://riotimesonline.com
|
||||||
https://www.monitor.co.ug/rss
|
https://mercopress.com
|
||||||
https://www.standardmedia.co.ke/rss
|
https://www.elmostrador.cl
|
||||||
https://www.ft.com/rss/home
|
https://www.jornada.com.mx
|
||||||
https://www.economist.com/rss/the-world-this-week
|
https://www.theeastafrican.co.ke
|
||||||
https://feeds.bloomberg.com/economics/news.rss
|
https://allafrica.com
|
||||||
https://feeds.bloomberg.com/markets/news.rss
|
https://www.premiumtimesng.com
|
||||||
https://www.reuters.com/arc/outboundfeeds/newsroom/business/
|
https://www.dailytrust.com
|
||||||
https://www.cnbc.com/id/10000113/device/rss/rss.html
|
https://www.newtimes.co.rw
|
||||||
https://feeds.a.dj.com/rss/RSSWorldBusiness.xml
|
https://www.herald.co.zw
|
||||||
https://www.marketwatch.com/rss/topstories
|
https://www.namibian.com.na
|
||||||
https://www.investing.com/rss/news_14.rss
|
https://www.graphic.com.gh
|
||||||
https://feeds.bbci.co.uk/news/business/rss.xml
|
https://www.thecitizen.co.tz
|
||||||
https://feeds.feedburner.com/TheHackersNews
|
https://www.monitor.co.ug
|
||||||
https://www.darkreading.com/rss/all.xml
|
|
||||||
https://isc.sans.edu/rssfeed_full.xml
|
# --- ALTERNATIVE, INVESTIGATIVE & "FRINGE" ---
|
||||||
https://securelist.com/feed/
|
https://theintercept.com
|
||||||
https://feeds.feedburner.com/eset/blog
|
https://www.propublica.org
|
||||||
https://news.sophos.com/en-us/feed/
|
https://www.democracynow.org
|
||||||
https://www.schneier.com/feed/atom/
|
https://reason.com
|
||||||
https://www.securitymagazine.com/rss/topic/2236-cybersecurity-news
|
https://www.motherjones.com
|
||||||
https://www.reuters.com/arc/outboundfeeds/rss/?outputType=xml
|
https://www.vox.com
|
||||||
https://www.investing.com/rss/news_462.rss
|
https://slate.com
|
||||||
https://www.investing.com/rss/news_1.rss
|
https://www.axios.com
|
||||||
https://www.investing.com/rss/stock_Futures.rss
|
https://www.politico.com
|
||||||
https://www.ecb.europa.eu/rss/fxref-ecbpress.en.xml
|
https://www.vice.com
|
||||||
https://www.federalreserve.gov/feeds/news-events.xml
|
https://www.bellingcat.com
|
||||||
https://www.boj.or.jp/en/rss/whatsnew.xml
|
https://www.project-syndicate.org
|
||||||
https://www.bankofengland.co.uk/rss/news
|
https://cryptonews.com
|
||||||
https://www.centralbanking.com/feeds/rss
|
https://www.coindesk.com
|
||||||
https://oilprice.com/rss/
|
https://techcrunch.com
|
||||||
https://www.spglobal.com/commodityinsights/en/rss
|
|
||||||
https://www.eia.gov/tools/rssfeeds/
|
|
||||||
https://www.cmegroup.com/rss
|
|
||||||
https://globalvoices.org/-/topics/economics-business/feed/
|
|
||||||
http://globalization.einnews.com/rss
|
|
||||||
https://financefeeds.com/feed/
|
|
||||||
https://newsquawk.com/blog/feed.rss
|
|
||||||
https://www.coindesk.com/arc/outboundfeeds/rss/
|
|
||||||
https://ishookfinance.com/feed/
|
|
||||||
https://www.scmp.com/rss/92/feed
|
|
||||||
https://www.scmp.com/rss/93/feed
|
|
||||||
https://www.scmp.com/rss/94/feed
|
|
||||||
https://www.scmp.com/rss/317/feed
|
|
||||||
https://asia.nikkei.com/rss
|
|
||||||
https://www.caixin.com/rss/index_EN.xml
|
|
||||||
https://www.straitstimes.com/news/asia/rss.xml
|
|
||||||
https://www.straitstimes.com/business/rss.xml
|
|
||||||
https://www.reuters.com/arc/outboundfeeds/rss/?outputType=xml§ion=asia
|
|
||||||
https://www.reuters.com/arc/outboundfeeds/rss/?outputType=xml§ion=china
|
|
||||||
https://www.bloomberg.com/feeds/asia.rss
|
|
||||||
https://www.bloomberg.com/feeds/markets.rss
|
|
||||||
https://www.ft.com/asia-pacific?format=rss
|
|
||||||
https://www.ft.com/china?format=rss
|
|
||||||
https://english.kyodonews.net/rss/news.xml
|
|
||||||
https://en.yna.co.kr/RSS/news.xml
|
|
||||||
https://www.thejakartapost.com/rss/business
|
|
||||||
https://www.nationthailand.com/rss/business
|
|
||||||
https://www.aramco.com/api/v1/com/rss/news?sc_lang=en
|
|
||||||
https://www.worldoil.com/rss?feed=topic:saudi+arabia
|
|
||||||
https://www.worldoil.com/rss?feed=topic:iraq
|
|
||||||
https://www.worldoil.com/rss?feed=topic:uae
|
|
||||||
https://www.worldoil.com/rss?feed=topic:russia
|
|
||||||
https://www.worldoil.com/rss?feed=topic:canada
|
|
||||||
https://www.worldoil.com/rss?feed=topic:oil+sands
|
|
||||||
https://www.rigzone.com/news/europe_russia/production/rss/
|
|
||||||
https://www.argusmedia.com/en/news-and-insights/latest-market-news/rss
|
|
||||||
https://www.eia.gov/rss/
|
|
||||||
https://www.opec.org/opec_web/en/pressreleases.rss
|
|
||||||
https://www.opec.org
|
|
||||||
https://www.rosneft.com/press/news/rss/
|
|
||||||
https://feeds.content.dowjones.io/public/rss/RSSMarketsMain
|
|
||||||
https://feeds.content.dowjones.io/public/rss/socialeconomyfeed
|
|
||||||
https://feeds.content.dowjones.io/public/rss/WSJcomUSBusiness
|
|
||||||
https://feeds.content.dowjones.io/public/rss/RSSWorldNews
|
|
||||||
http://feeds.feedburner.com/EconomicEventsAgriculture
|
|
||||||
http://feeds.feedburner.com/EconomicEventsEnergy
|
|
||||||
http://feeds.feedburner.com/EconomicEventsInterestRates
|
|
||||||
http://feeds.feedburner.com/mediaroom/CMsF
|
|
||||||
http://feeds.feedburner.com/CMEClearPortNoticesRss
|
|
||||||
http://feeds.feedburner.com/GlobexAdvisories
|
|
||||||
https://feeds.content.dowjones.io/public/rss/mw_topstories
|
|
||||||
https://feeds.content.dowjones.io/public/rss/mw_realtimeheadlines
|
|
||||||
http://feeds.marketwatch.com/marketwatch/bulletins
|
|
||||||
https://feeds.content.dowjones.io/public/rss/mw_marketpulse
|
|
||||||
https://www.nasdaqtrader.com/rss.aspx?feed=currentheadlines&categorylist=51
|
|
||||||
https://www.nasdaqtrader.com/rss.aspx?feed=currentheadlines&categorylist=11
|
|
||||||
https://www.investing.com/rss/stock_Options.rss
|
|
||||||
https://www.investing.com/rss/news_11.rss
|
|
||||||
https://www.investing.com/rss/news_25.rss
|
|
||||||
https://www.nasdaq.com/feed/rssoutbound?category=Markets
|
|
||||||
https://www.nasdaq.com/feed/rssoutbound?category=Commodities
|
|
||||||
https://www.barchart.com/news/rss/financials/options-news
|
|
||||||
https://www.barchart.com/news/rss/commodities/futures-news
|
|
||||||
https://www.spglobal.com/spdji/en/rss
|
|
||||||
https://www.litefinance.org/rss/analytics/
|
|
||||||
https://www.mrt.com/arc/outboundfeeds/rss/category/business/oil/?outputType=xml
|
|
||||||
https://www.oaoa.com/category/local-news/inthepipeline/rss
|
|
||||||
https://pboilandgasmagazine.com/feed/
|
|
||||||
https://www.rigzone.com/news/rss.asp
|
|
||||||
https://rbnenergy.com/blogcast.rss
|
|
||||||
https://www.eia.gov/rss/todayinenergy.xml
|
|
||||||
https://www.firstalert7.com/news/energy
|
|
||||||
https://www.energyvoice.com/feed/?category=oilandgas/north-sea
|
|
||||||
https://www.rigzone.com/news/rss/north_sea
|
|
||||||
https://www.oedigital.com/feeds/rss
|
|
||||||
https://www.sodir.no/en/whats-new/news/rss
|
|
||||||
https://www.worldoil.com/rss?feed=topic:offshore
|
|
||||||
https://oilandgas.einnews.com/rss/north-sea-offshore
|
|
||||||
https://www.energyvoice.com/feed/
|
|
||||||
|
|
|
||||||
|
|
@ -7,14 +7,13 @@ WORKDIR /app
|
||||||
|
|
||||||
# libpq-dev + gcc for psycopg2 build/adapters; keep the image lean.
|
# libpq-dev + gcc for psycopg2 build/adapters; keep the image lean.
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
libpq-dev gcc tzdata \
|
libpq-dev gcc \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
COPY summarizer.py run_news_summarizer.py intel.py nous_client.py gazetteer.py ./
|
COPY summarizer.py run_news_summarizer.py ./
|
||||||
COPY data/ ./data/
|
|
||||||
|
|
||||||
# Security: run as a non-privileged user.
|
# Security: run as a non-privileged user.
|
||||||
RUN useradd -m summarizer_user
|
RUN useradd -m summarizer_user
|
||||||
|
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
# GeoNames reference data (offline gazetteer)
|
|
||||||
|
|
||||||
Vendored from GeoNames (https://www.geonames.org/), licensed CC-BY 4.0
|
|
||||||
(https://creativecommons.org/licenses/by/4.0/). Attribution: "GeoNames"
|
|
||||||
(https://www.geonames.org/) — the summarizer resolves place names to
|
|
||||||
proximate coordinates fully offline from these files; no geocoding API
|
|
||||||
is called at runtime.
|
|
||||||
|
|
||||||
## Files
|
|
||||||
|
|
||||||
- `cities15000.tsv` — trimmed `cities15000.txt` dump (all cities with
|
|
||||||
population > 15000, ~34k rows). Columns (tab-separated, no header):
|
|
||||||
`name asciiname latitude longitude population country_code admin1_code`
|
|
||||||
Source: https://download.geonames.org/export/dump/cities15000.zip
|
|
||||||
- `admin1.tsv` — trimmed `admin1CodesASCII.txt` (~3.9k first-level
|
|
||||||
divisions: states/regions). Columns: `code name asciiname`
|
|
||||||
(code is `CC.A1`, e.g. `US.TX`). Used to disambiguate "Paris, Texas"
|
|
||||||
from "Paris, France".
|
|
||||||
Source: https://download.geonames.org/export/dump/admin1CodesASCII.txt
|
|
||||||
- `countries.tsv` — trimmed `countryInfo.txt` (252 rows). Columns:
|
|
||||||
`iso_code country_name capital`
|
|
||||||
Source: https://download.geonames.org/export/dump/countryInfo.txt
|
|
||||||
Country-level lookups resolve to the capital's coordinates (the
|
|
||||||
countryInfo dump carries no centroid), confidence "approx".
|
|
||||||
|
|
||||||
Refresh: re-download the dumps, keep the same column layout. The loader
|
|
||||||
(`../gazetteer.py`) tolerates extra/missing trailing columns and skips
|
|
||||||
malformed rows.
|
|
||||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,252 +0,0 @@
|
||||||
AD Andorra Andorra la Vella
|
|
||||||
AE United Arab Emirates Abu Dhabi
|
|
||||||
AF Afghanistan Kabul
|
|
||||||
AG Antigua and Barbuda St. John's
|
|
||||||
AI Anguilla The Valley
|
|
||||||
AL Albania Tirana
|
|
||||||
AM Armenia Yerevan
|
|
||||||
AO Angola Luanda
|
|
||||||
AQ Antarctica
|
|
||||||
AR Argentina Buenos Aires
|
|
||||||
AS American Samoa Pago Pago
|
|
||||||
AT Austria Vienna
|
|
||||||
AU Australia Canberra
|
|
||||||
AW Aruba Oranjestad
|
|
||||||
AX Aland Islands Mariehamn
|
|
||||||
AZ Azerbaijan Baku
|
|
||||||
BA Bosnia and Herzegovina Sarajevo
|
|
||||||
BB Barbados Bridgetown
|
|
||||||
BD Bangladesh Dhaka
|
|
||||||
BE Belgium Brussels
|
|
||||||
BF Burkina Faso Ouagadougou
|
|
||||||
BG Bulgaria Sofia
|
|
||||||
BH Bahrain Manama
|
|
||||||
BI Burundi Gitega
|
|
||||||
BJ Benin Porto-Novo
|
|
||||||
BL Saint Barthelemy Gustavia
|
|
||||||
BM Bermuda Hamilton
|
|
||||||
BN Brunei Bandar Seri Begawan
|
|
||||||
BO Bolivia Sucre
|
|
||||||
BQ Bonaire, Saint Eustatius and Saba
|
|
||||||
BR Brazil Brasilia
|
|
||||||
BS Bahamas Nassau
|
|
||||||
BT Bhutan Thimphu
|
|
||||||
BV Bouvet Island
|
|
||||||
BW Botswana Gaborone
|
|
||||||
BY Belarus Minsk
|
|
||||||
BZ Belize Belmopan
|
|
||||||
CA Canada Ottawa
|
|
||||||
CC Cocos Islands West Island
|
|
||||||
CD Democratic Republic of the Congo Kinshasa
|
|
||||||
CF Central African Republic Bangui
|
|
||||||
CG Republic of the Congo Brazzaville
|
|
||||||
CH Switzerland Bern
|
|
||||||
CI Ivory Coast Yamoussoukro
|
|
||||||
CK Cook Islands Avarua
|
|
||||||
CL Chile Santiago
|
|
||||||
CM Cameroon Yaounde
|
|
||||||
CN China Beijing
|
|
||||||
CO Colombia Bogota
|
|
||||||
CR Costa Rica San Jose
|
|
||||||
CU Cuba Havana
|
|
||||||
CV Cabo Verde Praia
|
|
||||||
CW Curacao Willemstad
|
|
||||||
CX Christmas Island Flying Fish Cove
|
|
||||||
CY Cyprus Nicosia
|
|
||||||
CZ Czechia Prague
|
|
||||||
DE Germany Berlin
|
|
||||||
DJ Djibouti Djibouti
|
|
||||||
DK Denmark Copenhagen
|
|
||||||
DM Dominica Roseau
|
|
||||||
DO Dominican Republic Santo Domingo
|
|
||||||
DZ Algeria Algiers
|
|
||||||
EC Ecuador Quito
|
|
||||||
EE Estonia Tallinn
|
|
||||||
EG Egypt Cairo
|
|
||||||
EH Western Sahara El-Aaiun
|
|
||||||
ER Eritrea Asmara
|
|
||||||
ES Spain Madrid
|
|
||||||
ET Ethiopia Addis Ababa
|
|
||||||
FI Finland Helsinki
|
|
||||||
FJ Fiji Suva
|
|
||||||
FK Falkland Islands Stanley
|
|
||||||
FM Micronesia Palikir
|
|
||||||
FO Faroe Islands Torshavn
|
|
||||||
FR France Paris
|
|
||||||
GA Gabon Libreville
|
|
||||||
GB United Kingdom London
|
|
||||||
GD Grenada St. George's
|
|
||||||
GE Georgia Tbilisi
|
|
||||||
GF French Guiana Cayenne
|
|
||||||
GG Guernsey St Peter Port
|
|
||||||
GH Ghana Accra
|
|
||||||
GI Gibraltar Gibraltar
|
|
||||||
GL Greenland Nuuk
|
|
||||||
GM Gambia Banjul
|
|
||||||
GN Guinea Conakry
|
|
||||||
GP Guadeloupe Basse-Terre
|
|
||||||
GQ Equatorial Guinea Ciudad de la Paz
|
|
||||||
GR Greece Athens
|
|
||||||
GS South Georgia and the South Sandwich Islands Grytviken
|
|
||||||
GT Guatemala Guatemala City
|
|
||||||
GU Guam Hagatna
|
|
||||||
GW Guinea-Bissau Bissau
|
|
||||||
GY Guyana Georgetown
|
|
||||||
HK Hong Kong Hong Kong
|
|
||||||
HM Heard Island and McDonald Islands
|
|
||||||
HN Honduras Tegucigalpa
|
|
||||||
HR Croatia Zagreb
|
|
||||||
HT Haiti Port-au-Prince
|
|
||||||
HU Hungary Budapest
|
|
||||||
ID Indonesia Jakarta
|
|
||||||
IE Ireland Dublin
|
|
||||||
IL Israel Jerusalem
|
|
||||||
IM Isle of Man Douglas
|
|
||||||
IN India New Delhi
|
|
||||||
IO British Indian Ocean Territory Diego Garcia
|
|
||||||
IQ Iraq Baghdad
|
|
||||||
IR Iran Tehran
|
|
||||||
IS Iceland Reykjavik
|
|
||||||
IT Italy Rome
|
|
||||||
JE Jersey Saint Helier
|
|
||||||
JM Jamaica Kingston
|
|
||||||
JO Jordan Amman
|
|
||||||
JP Japan Tokyo
|
|
||||||
KE Kenya Nairobi
|
|
||||||
KG Kyrgyzstan Bishkek
|
|
||||||
KH Cambodia Phnom Penh
|
|
||||||
KI Kiribati Tarawa
|
|
||||||
KM Comoros Moroni
|
|
||||||
KN Saint Kitts and Nevis Basseterre
|
|
||||||
KP North Korea Pyongyang
|
|
||||||
KR South Korea Seoul
|
|
||||||
XK Kosovo Pristina
|
|
||||||
KW Kuwait Kuwait City
|
|
||||||
KY Cayman Islands George Town
|
|
||||||
KZ Kazakhstan Nur-Sultan
|
|
||||||
LA Laos Vientiane
|
|
||||||
LB Lebanon Beirut
|
|
||||||
LC Saint Lucia Castries
|
|
||||||
LI Liechtenstein Vaduz
|
|
||||||
LK Sri Lanka Colombo
|
|
||||||
LR Liberia Monrovia
|
|
||||||
LS Lesotho Maseru
|
|
||||||
LT Lithuania Vilnius
|
|
||||||
LU Luxembourg Luxembourg
|
|
||||||
LV Latvia Riga
|
|
||||||
LY Libya Tripoli
|
|
||||||
MA Morocco Rabat
|
|
||||||
MC Monaco Monaco
|
|
||||||
MD Moldova Chisinau
|
|
||||||
ME Montenegro Podgorica
|
|
||||||
MF Saint Martin Marigot
|
|
||||||
MG Madagascar Antananarivo
|
|
||||||
MH Marshall Islands Majuro
|
|
||||||
MK North Macedonia Skopje
|
|
||||||
ML Mali Bamako
|
|
||||||
MM Myanmar Nay Pyi Taw
|
|
||||||
MN Mongolia Ulaanbaatar
|
|
||||||
MO Macao Macao
|
|
||||||
MP Northern Mariana Islands Saipan
|
|
||||||
MQ Martinique Fort-de-France
|
|
||||||
MR Mauritania Nouakchott
|
|
||||||
MS Montserrat Plymouth
|
|
||||||
MT Malta Valletta
|
|
||||||
MU Mauritius Port Louis
|
|
||||||
MV Maldives Male
|
|
||||||
MW Malawi Lilongwe
|
|
||||||
MX Mexico Mexico City
|
|
||||||
MY Malaysia Kuala Lumpur
|
|
||||||
MZ Mozambique Maputo
|
|
||||||
NA Namibia Windhoek
|
|
||||||
NC New Caledonia Noumea
|
|
||||||
NE Niger Niamey
|
|
||||||
NF Norfolk Island Kingston
|
|
||||||
NG Nigeria Abuja
|
|
||||||
NI Nicaragua Managua
|
|
||||||
NL The Netherlands Amsterdam
|
|
||||||
NO Norway Oslo
|
|
||||||
NP Nepal Kathmandu
|
|
||||||
NR Nauru Yaren
|
|
||||||
NU Niue Alofi
|
|
||||||
NZ New Zealand Wellington
|
|
||||||
OM Oman Muscat
|
|
||||||
PA Panama Panama City
|
|
||||||
PE Peru Lima
|
|
||||||
PF French Polynesia Papeete
|
|
||||||
PG Papua New Guinea Port Moresby
|
|
||||||
PH Philippines Manila
|
|
||||||
PK Pakistan Islamabad
|
|
||||||
PL Poland Warsaw
|
|
||||||
PM Saint Pierre and Miquelon Saint-Pierre
|
|
||||||
PN Pitcairn Adamstown
|
|
||||||
PR Puerto Rico San Juan
|
|
||||||
PS Palestinian Territory East Jerusalem
|
|
||||||
PT Portugal Lisbon
|
|
||||||
PW Palau Melekeok
|
|
||||||
PY Paraguay Asuncion
|
|
||||||
QA Qatar Doha
|
|
||||||
RE Reunion Saint-Denis
|
|
||||||
RO Romania Bucharest
|
|
||||||
RS Serbia Belgrade
|
|
||||||
RU Russia Moscow
|
|
||||||
RW Rwanda Kigali
|
|
||||||
SA Saudi Arabia Riyadh
|
|
||||||
SB Solomon Islands Honiara
|
|
||||||
SC Seychelles Victoria
|
|
||||||
SD Sudan Khartoum
|
|
||||||
SS South Sudan Juba
|
|
||||||
SE Sweden Stockholm
|
|
||||||
SG Singapore Singapore
|
|
||||||
SH Saint Helena Jamestown
|
|
||||||
SI Slovenia Ljubljana
|
|
||||||
SJ Svalbard and Jan Mayen Longyearbyen
|
|
||||||
SK Slovakia Bratislava
|
|
||||||
SL Sierra Leone Freetown
|
|
||||||
SM San Marino San Marino
|
|
||||||
SN Senegal Dakar
|
|
||||||
SO Somalia Mogadishu
|
|
||||||
SR Suriname Paramaribo
|
|
||||||
ST Sao Tome and Principe Sao Tome
|
|
||||||
SV El Salvador San Salvador
|
|
||||||
SX Sint Maarten Philipsburg
|
|
||||||
SY Syria Damascus
|
|
||||||
SZ Eswatini Mbabane
|
|
||||||
TC Turks and Caicos Islands Cockburn Town
|
|
||||||
TD Chad N'Djamena
|
|
||||||
TF French Southern Territories Port-aux-Francais
|
|
||||||
TG Togo Lome
|
|
||||||
TH Thailand Bangkok
|
|
||||||
TJ Tajikistan Dushanbe
|
|
||||||
TK Tokelau
|
|
||||||
TL Timor Leste Dili
|
|
||||||
TM Turkmenistan Ashgabat
|
|
||||||
TN Tunisia Tunis
|
|
||||||
TO Tonga Nuku'alofa
|
|
||||||
TR Turkey Ankara
|
|
||||||
TT Trinidad and Tobago Port of Spain
|
|
||||||
TV Tuvalu Funafuti
|
|
||||||
TW Taiwan Taipei
|
|
||||||
TZ Tanzania Dodoma
|
|
||||||
UA Ukraine Kyiv
|
|
||||||
UG Uganda Kampala
|
|
||||||
UM United States Minor Outlying Islands
|
|
||||||
US United States Washington
|
|
||||||
UY Uruguay Montevideo
|
|
||||||
UZ Uzbekistan Tashkent
|
|
||||||
VA Vatican Vatican City
|
|
||||||
VC Saint Vincent and the Grenadines Kingstown
|
|
||||||
VE Venezuela Caracas
|
|
||||||
VG British Virgin Islands Road Town
|
|
||||||
VI U.S. Virgin Islands Charlotte Amalie
|
|
||||||
VN Vietnam Hanoi
|
|
||||||
VU Vanuatu Port Vila
|
|
||||||
WF Wallis and Futuna Mata Utu
|
|
||||||
WS Samoa Apia
|
|
||||||
YE Yemen Sanaa
|
|
||||||
YT Mayotte Mamoudzou
|
|
||||||
ZA South Africa Pretoria
|
|
||||||
ZM Zambia Lusaka
|
|
||||||
ZW Zimbabwe Harare
|
|
||||||
CS Serbia and Montenegro Belgrade
|
|
||||||
AN Netherlands Antilles Willemstad
|
|
||||||
|
|
|
@ -1,193 +0,0 @@
|
||||||
"""Offline GeoNames gazetteer — proximate geolocation for graded articles.
|
|
||||||
|
|
||||||
When a map-phase block names a place but gives no coordinates, resolve the
|
|
||||||
name against vendored GeoNames data (``data/``): cities15000 first, then
|
|
||||||
country -> capital. Fully offline: no paid API, no rate-limited Nominatim,
|
|
||||||
no network at runtime. Every resolution is labelled confidence "approx"
|
|
||||||
by the caller — a gazetteer point is a proximate guess, never an exact fix.
|
|
||||||
|
|
||||||
Matching is best-effort and conservative: normalised (case/diacritic-folded)
|
|
||||||
exact-name lookups with country/admin1 context disambiguation ("Paris,
|
|
||||||
Texas" vs "Paris, France"), highest population wins ties. A miss returns
|
|
||||||
None — the article simply gets no blip. Never invents a place.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import unicodedata
|
|
||||||
from functools import lru_cache
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
_DATA_DIR = Path(__file__).resolve().parent / "data"
|
|
||||||
|
|
||||||
# Common short forms the model writes that GeoNames spells out.
|
|
||||||
_COUNTRY_ALIASES = {
|
|
||||||
"usa": "US",
|
|
||||||
"u.s.a.": "US",
|
|
||||||
"u.s.": "US",
|
|
||||||
"us": "US",
|
|
||||||
"uk": "GB",
|
|
||||||
"u.k.": "GB",
|
|
||||||
"united states of america": "US",
|
|
||||||
"england": "GB",
|
|
||||||
"south korea": "KR",
|
|
||||||
"north korea": "KP",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _norm(text: str) -> str:
|
|
||||||
"""Casefold + strip diacritics + collapse whitespace for matching."""
|
|
||||||
text = unicodedata.normalize("NFKD", text)
|
|
||||||
text = "".join(ch for ch in text if not unicodedata.combining(ch))
|
|
||||||
return " ".join(text.casefold().split())
|
|
||||||
|
|
||||||
|
|
||||||
def _read_tsv(filename: str) -> list[list[str]]:
|
|
||||||
path = _DATA_DIR / filename
|
|
||||||
rows: list[list[str]] = []
|
|
||||||
try:
|
|
||||||
with open(path, encoding="utf-8") as fh:
|
|
||||||
for line in fh:
|
|
||||||
parts = line.rstrip("\n").split("\t")
|
|
||||||
if parts and parts[0]:
|
|
||||||
rows.append(parts)
|
|
||||||
except OSError:
|
|
||||||
return []
|
|
||||||
return rows
|
|
||||||
|
|
||||||
|
|
||||||
@lru_cache(maxsize=1)
|
|
||||||
def _city_index() -> dict[str, list[tuple[float, float, int, str, str]]]:
|
|
||||||
"""norm name -> [(lat, lon, population, country_code, admin1_code)]."""
|
|
||||||
index: dict[str, list[tuple[float, float, int, str, str]]] = {}
|
|
||||||
for parts in _read_tsv("cities15000.tsv"):
|
|
||||||
if len(parts) < 7:
|
|
||||||
continue
|
|
||||||
name, asciiname, lat, lon, pop, cc, admin1 = parts[:7]
|
|
||||||
try:
|
|
||||||
lat_f, lon_f, pop_i = float(lat), float(lon), int(pop)
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
if not (-90 <= lat_f <= 90 and -180 <= lon_f <= 180):
|
|
||||||
continue
|
|
||||||
entry = (lat_f, lon_f, pop_i, cc, admin1)
|
|
||||||
for key in {name, asciiname}:
|
|
||||||
key = _norm(key)
|
|
||||||
if key:
|
|
||||||
index.setdefault(key, []).append(entry)
|
|
||||||
return index
|
|
||||||
|
|
||||||
|
|
||||||
@lru_cache(maxsize=1)
|
|
||||||
def _country_index() -> dict[str, tuple[str, str]]:
|
|
||||||
"""norm country name/iso -> (iso_code, capital)."""
|
|
||||||
index: dict[str, tuple[str, str]] = {}
|
|
||||||
for parts in _read_tsv("countries.tsv"):
|
|
||||||
if len(parts) < 3:
|
|
||||||
continue
|
|
||||||
iso, name, capital = parts[:3]
|
|
||||||
value = (iso, capital)
|
|
||||||
index[_norm(name)] = value
|
|
||||||
index[iso.casefold()] = value
|
|
||||||
for alias, iso in _COUNTRY_ALIASES.items():
|
|
||||||
hit = index.get(iso.casefold())
|
|
||||||
if hit:
|
|
||||||
index[_norm(alias)] = hit
|
|
||||||
return index
|
|
||||||
|
|
||||||
|
|
||||||
@lru_cache(maxsize=1)
|
|
||||||
def _admin1_index() -> dict[str, list[tuple[str, str]]]:
|
|
||||||
"""norm division name -> [(country_code, admin1_code)]."""
|
|
||||||
index: dict[str, list[tuple[str, str]]] = {}
|
|
||||||
for parts in _read_tsv("admin1.tsv"):
|
|
||||||
if len(parts) < 3 or "." not in parts[0]:
|
|
||||||
continue
|
|
||||||
code, name, asciiname = parts[:3]
|
|
||||||
cc, _, a1 = code.partition(".")
|
|
||||||
for key in {name, asciiname}:
|
|
||||||
key = _norm(key)
|
|
||||||
if key:
|
|
||||||
index.setdefault(key, []).append((cc, a1))
|
|
||||||
return index
|
|
||||||
|
|
||||||
|
|
||||||
def _pick(entries: list[tuple[float, float, int, str, str]]) -> tuple[float, float]:
|
|
||||||
best = max(entries, key=lambda e: e[2])
|
|
||||||
return (best[0], best[1])
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_place(location_name) -> tuple[float, float] | None:
|
|
||||||
"""Proximate (lat, lon) for a model-written place name, else None.
|
|
||||||
|
|
||||||
Tries the full string, then the comma-leading part, with trailing
|
|
||||||
parts as country/admin1 context. Falls back to country -> capital.
|
|
||||||
"""
|
|
||||||
if not isinstance(location_name, str):
|
|
||||||
return None
|
|
||||||
text = location_name.strip()
|
|
||||||
if not text:
|
|
||||||
return None
|
|
||||||
parts = [p.strip() for p in text.split(",") if p.strip()]
|
|
||||||
if not parts:
|
|
||||||
return None
|
|
||||||
|
|
||||||
countries = _country_index()
|
|
||||||
admin1s = _admin1_index()
|
|
||||||
context_country: str | None = None
|
|
||||||
context_admin1: list[tuple[str, str]] = []
|
|
||||||
for part in parts[1:]:
|
|
||||||
key = _norm(part)
|
|
||||||
hit = countries.get(key)
|
|
||||||
if hit:
|
|
||||||
context_country = hit[0]
|
|
||||||
continue
|
|
||||||
context_admin1.extend(admin1s.get(key, []))
|
|
||||||
|
|
||||||
cities = _city_index()
|
|
||||||
for candidate in (text, parts[0]):
|
|
||||||
entries = cities.get(_norm(candidate))
|
|
||||||
if not entries:
|
|
||||||
continue
|
|
||||||
if context_admin1:
|
|
||||||
scoped = [
|
|
||||||
e for e in entries
|
|
||||||
if any(e[3] == cc and e[4] == a1 for cc, a1 in context_admin1)
|
|
||||||
]
|
|
||||||
if scoped:
|
|
||||||
return _pick(scoped)
|
|
||||||
if context_country:
|
|
||||||
scoped = [e for e in entries if e[3] == context_country]
|
|
||||||
if scoped:
|
|
||||||
return _pick(scoped)
|
|
||||||
return _pick(entries)
|
|
||||||
|
|
||||||
# Country-only location ("Ukraine"): resolve to the capital.
|
|
||||||
hit = countries.get(_norm(parts[0]))
|
|
||||||
if hit:
|
|
||||||
entries = cities.get(_norm(hit[1]))
|
|
||||||
if entries:
|
|
||||||
return _pick(entries)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def fill_block_geo(block: dict) -> dict:
|
|
||||||
"""Fill missing coords on a parsed map block from the gazetteer.
|
|
||||||
|
|
||||||
Blocks that already carry model coordinates are untouched. A resolved
|
|
||||||
place is labelled confidence "approx"; a miss leaves the block as-is
|
|
||||||
(name preserved, no coords) — never invents a place.
|
|
||||||
"""
|
|
||||||
if not isinstance(block, dict):
|
|
||||||
return block
|
|
||||||
if block.get("lat") is not None and block.get("lon") is not None:
|
|
||||||
return block
|
|
||||||
name = block.get("location_name")
|
|
||||||
if not name:
|
|
||||||
return block
|
|
||||||
coords = resolve_place(name)
|
|
||||||
if coords is None:
|
|
||||||
return block
|
|
||||||
block["lat"], block["lon"] = coords
|
|
||||||
block["location_confidence"] = "approx"
|
|
||||||
return block
|
|
||||||
|
|
@ -1,591 +0,0 @@
|
||||||
"""Pure parser for the news-summarizer map grading / reduce JSON / geo contract."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import difflib
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
|
|
||||||
_EMPTY = {"summary_en": "", "ticker": [], "map_items": []}
|
|
||||||
_KEEP = frozenset({"critical", "high"})
|
|
||||||
_RANK = {"critical": 0, "high": 1, "medium": 2, "low": 3}
|
|
||||||
_THINK_RE = re.compile(r"<think>.*?</think>", re.DOTALL)
|
|
||||||
_FENCE_RE = re.compile(r"```(?:json)?", re.IGNORECASE)
|
|
||||||
|
|
||||||
TICKER_HEADLINE_MAX = 140
|
|
||||||
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:
|
|
||||||
text = _THINK_RE.sub("", raw or "")
|
|
||||||
text = _FENCE_RE.sub("", text)
|
|
||||||
start = text.find("{")
|
|
||||||
end = text.rfind("}")
|
|
||||||
if start == -1 or end == -1 or end < start:
|
|
||||||
return dict(_EMPTY)
|
|
||||||
data = json.loads(text[start : end + 1])
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
return dict(_EMPTY)
|
|
||||||
summary = data.get("summary_en", "")
|
|
||||||
ticker = data.get("ticker", [])
|
|
||||||
map_items = data.get("map_items", [])
|
|
||||||
return {
|
|
||||||
"summary_en": summary if isinstance(summary, str) else "",
|
|
||||||
"ticker": ticker if isinstance(ticker, list) else [],
|
|
||||||
"map_items": map_items if isinstance(map_items, list) else [],
|
|
||||||
}
|
|
||||||
except Exception:
|
|
||||||
return dict(_EMPTY)
|
|
||||||
|
|
||||||
|
|
||||||
def clamp_coords(lat, lon) -> tuple[float, float] | None:
|
|
||||||
try:
|
|
||||||
lat_f = float(lat)
|
|
||||||
lon_f = float(lon)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return None
|
|
||||||
if not (-90 <= lat_f <= 90 and -180 <= lon_f <= 180):
|
|
||||||
return None
|
|
||||||
return (lat_f, lon_f)
|
|
||||||
|
|
||||||
|
|
||||||
def _trimmed_headline(row: dict, limit: int) -> str:
|
|
||||||
headline = row.get("headline") or ""
|
|
||||||
if not isinstance(headline, str):
|
|
||||||
headline = str(headline)
|
|
||||||
return headline.strip()[:limit]
|
|
||||||
|
|
||||||
|
|
||||||
def select_ticker(rows: list) -> list:
|
|
||||||
flagged = []
|
|
||||||
medium = []
|
|
||||||
low = []
|
|
||||||
for row in rows:
|
|
||||||
imp = row.get("importance")
|
|
||||||
if imp not in _RANK:
|
|
||||||
continue
|
|
||||||
headline = _trimmed_headline(row, TICKER_HEADLINE_MAX)
|
|
||||||
if not headline:
|
|
||||||
continue
|
|
||||||
item = dict(row)
|
|
||||||
item["headline"] = headline
|
|
||||||
if imp in _KEEP:
|
|
||||||
flagged.append(item)
|
|
||||||
elif imp == "medium":
|
|
||||||
medium.append(item)
|
|
||||||
else:
|
|
||||||
low.append(item)
|
|
||||||
if len(flagged) >= TICKER_CAP:
|
|
||||||
break
|
|
||||||
if flagged:
|
|
||||||
return flagged[:TICKER_CAP]
|
|
||||||
return (medium + low)[:TICKER_CAP]
|
|
||||||
|
|
||||||
|
|
||||||
def select_map(items: list) -> list:
|
|
||||||
out = []
|
|
||||||
for row in items:
|
|
||||||
if row.get("importance") not in _KEEP:
|
|
||||||
continue
|
|
||||||
headline = _trimmed_headline(row, MAP_HEADLINE_MAX)
|
|
||||||
if not headline:
|
|
||||||
continue
|
|
||||||
coords = clamp_coords(row.get("lat"), row.get("lon"))
|
|
||||||
if coords is None:
|
|
||||||
continue
|
|
||||||
item = dict(row)
|
|
||||||
item["headline"] = headline
|
|
||||||
item["lat"], item["lon"] = coords
|
|
||||||
out.append(item)
|
|
||||||
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
|
|
||||||
|
|
@ -1,57 +0,0 @@
|
||||||
"""HTTP client for the Nous inference chat completions API."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
_DEFAULT_UA = "osint-dashboard-news-summarizer"
|
|
||||||
_DEFAULT_BASE = "https://inference-api.nousresearch.com/v1"
|
|
||||||
_JSON_SYSTEM = (
|
|
||||||
"You are an OSINT executive briefer. Reply with a single complete JSON object. "
|
|
||||||
"Never truncate mid-sentence. If you run out of room, drop the lowest-priority item."
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def chat(prompt, *, api_key, model, base_url, json_mode=False) -> str:
|
|
||||||
resolved = (base_url or os.environ.get("NOUS_BASE_URL", _DEFAULT_BASE)).rstrip("/")
|
|
||||||
url = f"{resolved}/chat/completions"
|
|
||||||
headers = {
|
|
||||||
"Authorization": f"Bearer {api_key}",
|
|
||||||
"User-Agent": os.environ.get("OSINT_USER_AGENT") or _DEFAULT_UA,
|
|
||||||
}
|
|
||||||
max_tokens = 8192 if json_mode else 4096
|
|
||||||
timeout = 120.0 if json_mode else 60.0
|
|
||||||
messages = [{"role": "user", "content": prompt}]
|
|
||||||
if json_mode:
|
|
||||||
messages = [
|
|
||||||
{"role": "system", "content": _JSON_SYSTEM},
|
|
||||||
{"role": "user", "content": prompt},
|
|
||||||
]
|
|
||||||
payload = {
|
|
||||||
"model": model,
|
|
||||||
"messages": messages,
|
|
||||||
"temperature": 0.2,
|
|
||||||
"max_tokens": max_tokens,
|
|
||||||
}
|
|
||||||
if json_mode:
|
|
||||||
payload["response_format"] = {"type": "json_object"}
|
|
||||||
last_content = ""
|
|
||||||
try:
|
|
||||||
for attempt in range(2):
|
|
||||||
with httpx.Client(timeout=timeout) as client:
|
|
||||||
resp = client.post(url, headers=headers, json=payload)
|
|
||||||
if resp.status_code == 401 or resp.status_code >= 500:
|
|
||||||
return ""
|
|
||||||
data = resp.json()
|
|
||||||
choice = (data.get("choices") or [{}])[0]
|
|
||||||
last_content = (choice.get("message") or {}).get("content") or ""
|
|
||||||
finish = choice.get("finish_reason")
|
|
||||||
if finish == "length" and attempt == 0:
|
|
||||||
payload["max_tokens"] = min(int(payload["max_tokens"]) * 2, 16384)
|
|
||||||
continue
|
|
||||||
return last_content
|
|
||||||
return last_content
|
|
||||||
except Exception:
|
|
||||||
return ""
|
|
||||||
|
|
@ -1,2 +1,6 @@
|
||||||
|
# Database adapter for PostgreSQL (shared osint-db).
|
||||||
psycopg2-binary==2.9.11
|
psycopg2-binary==2.9.11
|
||||||
httpx==0.28.1
|
|
||||||
|
# Gemini LLM SDK (google-genai). yfinance is NOT a dependency: futures prices
|
||||||
|
# are gated behind INCLUDE_FUTURES=1 and lazy-imported (install it to enable).
|
||||||
|
google-genai
|
||||||
|
|
|
||||||
|
|
@ -1,130 +1,67 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Scheduler loop for the news summarizer.
|
"""Scheduler loop for the news summarizer — hourly summarize at minute :05.
|
||||||
|
|
||||||
15-minute analyst (NEWS_SUMMARIZE_INTERVAL_S, default 900s) plus a daily
|
Replaces the k8s CronJob (`5 * * * *`) with an in-compose loop. Runs once on
|
||||||
recap at 23:00 in TZ (default America/New_York) over the last 24 hours.
|
boot (catches up on any articles scraped since the last summary), then fires
|
||||||
|
at each :NEWS_SUMMARIZE_MINUTE wall-clock boundary.
|
||||||
|
|
||||||
Serial: a slow LLM pass never overlaps the next.
|
The loop is serial, so a slow LLM pass never overlaps the next run.
|
||||||
|
|
||||||
Env (all optional, 12-factor):
|
Env (all optional, 12-factor):
|
||||||
NEWS_SUMMARIZE_INTERVAL_S seconds between analyst runs (default 900)
|
NEWS_SUMMARIZE_MINUTE minute of the hour to fire (default 5)
|
||||||
NEWS_SUMMARIZE_RUN_ON_START "1" to summarize once immediately on boot (default 1)
|
NEWS_SUMMARIZE_RUN_ON_START "1" to summarize once immediately on boot (default 1)
|
||||||
NEWS_RECAP_HOUR / MINUTE wall-clock recap time (default 23:00)
|
GEMINI_API_KEY required to do real work; unset = idle
|
||||||
TZ IANA tz (default America/New_York)
|
|
||||||
NOUS_API_KEY optional in env; Keys UI / api_keys also works
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import datetime
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
from datetime import datetime, timedelta
|
|
||||||
from zoneinfo import ZoneInfo
|
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||||
logger = logging.getLogger("news.summarizer.scheduler")
|
logger = logging.getLogger("news.summarizer.scheduler")
|
||||||
|
|
||||||
INTERVAL_S = max(1, int(os.getenv("NEWS_SUMMARIZE_INTERVAL_S", "900")))
|
MINUTE = int(os.getenv("NEWS_SUMMARIZE_MINUTE", "5"))
|
||||||
RUN_ON_START = os.getenv("NEWS_SUMMARIZE_RUN_ON_START", "1").lower() in ("1", "true", "yes")
|
RUN_ON_START = os.getenv("NEWS_SUMMARIZE_RUN_ON_START", "1").lower() in ("1", "true", "yes")
|
||||||
DEFAULT_TZ = "America/New_York"
|
|
||||||
DEFAULT_RECAP_HOUR = 23
|
|
||||||
DEFAULT_RECAP_MINUTE = 0
|
|
||||||
|
|
||||||
|
|
||||||
def _tz() -> ZoneInfo:
|
def seconds_until_next(minute: int) -> float:
|
||||||
name = (os.getenv("TZ") or DEFAULT_TZ).strip() or DEFAULT_TZ
|
"""Seconds until the next occurrence of ``minute`` past the hour (local time)."""
|
||||||
return ZoneInfo(name)
|
now = datetime.datetime.now()
|
||||||
|
nxt = now.replace(minute=minute, second=0, microsecond=0) + datetime.timedelta(hours=1)
|
||||||
|
return (nxt - now).total_seconds()
|
||||||
|
|
||||||
|
|
||||||
def recap_hour_minute() -> tuple[int, int]:
|
def run_summarize() -> None:
|
||||||
hour = int(os.getenv("NEWS_RECAP_HOUR", str(DEFAULT_RECAP_HOUR)))
|
logger.info("summarize starting at %s", datetime.datetime.now().isoformat(timespec="seconds"))
|
||||||
minute = int(os.getenv("NEWS_RECAP_MINUTE", str(DEFAULT_RECAP_MINUTE)))
|
|
||||||
return hour, minute
|
|
||||||
|
|
||||||
|
|
||||||
def next_recap_datetime(
|
|
||||||
now: datetime, hour: int | None = None, minute: int | None = None
|
|
||||||
) -> datetime:
|
|
||||||
"""Next 23:00 (or hour/minute) strictly after *now* in now's timezone."""
|
|
||||||
if now.tzinfo is None:
|
|
||||||
now = now.replace(tzinfo=_tz())
|
|
||||||
env_h, env_m = recap_hour_minute()
|
|
||||||
hour = env_h if hour is None else hour
|
|
||||||
minute = env_m if minute is None else minute
|
|
||||||
candidate = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
|
||||||
if now >= candidate:
|
|
||||||
candidate += timedelta(days=1)
|
|
||||||
return candidate
|
|
||||||
|
|
||||||
|
|
||||||
def next_event(
|
|
||||||
now: datetime,
|
|
||||||
last_periodic: datetime | None,
|
|
||||||
interval_s: int,
|
|
||||||
hour: int = DEFAULT_RECAP_HOUR,
|
|
||||||
minute: int = DEFAULT_RECAP_MINUTE,
|
|
||||||
) -> tuple[datetime, str]:
|
|
||||||
"""Return (when, 'recap'|'interval') for the sooner of recap vs interval."""
|
|
||||||
recap_at = next_recap_datetime(now, hour=hour, minute=minute)
|
|
||||||
periodic_at = now if last_periodic is None else last_periodic + timedelta(seconds=interval_s)
|
|
||||||
if recap_at <= periodic_at:
|
|
||||||
return recap_at, "recap"
|
|
||||||
return periodic_at, "interval"
|
|
||||||
|
|
||||||
|
|
||||||
def run_summarize(*, recap: bool = False) -> None:
|
|
||||||
kind = "recap" if recap else "interval"
|
|
||||||
logger.info(
|
|
||||||
"%s starting at %s", kind, datetime.now().isoformat(timespec="seconds")
|
|
||||||
)
|
|
||||||
env = os.environ.copy()
|
|
||||||
if recap:
|
|
||||||
env["NEWS_RECAP"] = "1"
|
|
||||||
else:
|
|
||||||
env.pop("NEWS_RECAP", None)
|
|
||||||
try:
|
try:
|
||||||
proc = subprocess.run(
|
proc = subprocess.run([sys.executable, "summarizer.py"], cwd="/app")
|
||||||
[sys.executable, "summarizer.py"], cwd="/app", env=env
|
logger.info("summarize finished rc=%s", proc.returncode)
|
||||||
)
|
|
||||||
logger.info("%s finished rc=%s", kind, proc.returncode)
|
|
||||||
except Exception: # noqa: BLE001 — keep the loop alive across failures
|
except Exception: # noqa: BLE001 — keep the loop alive across failures
|
||||||
logger.exception("%s failed", kind)
|
logger.exception("summarize failed")
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
if not os.getenv("NOUS_API_KEY", "").strip():
|
if not os.getenv("GEMINI_API_KEY", "").strip():
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"NOUS_API_KEY unset in env — will read api_keys on each run; idle if both empty"
|
"GEMINI_API_KEY not set — summarizer will idle (set it in .env and "
|
||||||
|
"recreate the service to enable)"
|
||||||
)
|
)
|
||||||
tz = _tz()
|
|
||||||
hour, minute = recap_hour_minute()
|
|
||||||
logger.info(
|
logger.info(
|
||||||
"news summarizer loop starting (interval_s=%s, run_on_start=%s, recap=%02d:%02d %s)",
|
"news summarizer loop starting (minute=%s, run_on_start=%s)",
|
||||||
INTERVAL_S, RUN_ON_START, hour, minute, tz,
|
MINUTE, RUN_ON_START,
|
||||||
)
|
)
|
||||||
last_periodic: datetime | None = None
|
|
||||||
if RUN_ON_START:
|
if RUN_ON_START:
|
||||||
run_summarize(recap=False)
|
run_summarize()
|
||||||
last_periodic = datetime.now(tz)
|
|
||||||
while True:
|
while True:
|
||||||
now = datetime.now(tz)
|
delay = seconds_until_next(MINUTE)
|
||||||
when, kind = next_event(
|
logger.info("next summarize at :%02d (in %.0fs)", MINUTE, delay)
|
||||||
now, last_periodic, INTERVAL_S, hour=hour, minute=minute
|
time.sleep(delay)
|
||||||
)
|
run_summarize()
|
||||||
sleep_s = max(1, (when - now).total_seconds())
|
|
||||||
logger.info("next %s in %ss", kind, int(sleep_s))
|
|
||||||
time.sleep(sleep_s)
|
|
||||||
now = datetime.now(tz)
|
|
||||||
if kind == "recap":
|
|
||||||
run_summarize(recap=True)
|
|
||||||
# Recap covers the 15-min window; don't immediately fire interval.
|
|
||||||
last_periodic = now
|
|
||||||
else:
|
|
||||||
run_summarize(recap=False)
|
|
||||||
last_periodic = now
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
||||||
|
|
@ -1,31 +1,25 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""News summarizer — Nous map-reduce of scraped articles into brief/ticker/map.
|
"""News summarizer — LLM (Gemini) map-reduce summarization of scraped articles.
|
||||||
|
|
||||||
Reads articles scraped within the last SUMMARY_WINDOW_MINUTES from the shared `articles` table,
|
Reads articles scraped within the last hour from the shared `articles` table,
|
||||||
maps them with Nous (per-article English fact blocks), reduces to one JSON
|
summarizes them with Gemini (map phase per batch, reduce phase into one master
|
||||||
object (summary_en + ticker + map_items), and stores the brief in
|
summary), and stores the result in `article_summaries` — both tables live in
|
||||||
`article_summaries` plus flagged rows in `news_items`. Tables live in the
|
the EXISTING osint-db (created by alembic migration 003_news, idempotent).
|
||||||
EXISTING osint-db (alembic 003_news + 005_news_items, idempotent).
|
|
||||||
|
|
||||||
Everything is env-driven (12-factor). Secrets/config are resolved at the start
|
|
||||||
of each summarize_news() — env wins, else api_keys / app_settings:
|
|
||||||
|
|
||||||
|
Everything is env-driven (12-factor):
|
||||||
DB_HOST / DB_NAME / DB_USER / DB_PASSWORD / DB_PORT PostgreSQL (osint-db)
|
DB_HOST / DB_NAME / DB_USER / DB_PASSWORD / DB_PORT PostgreSQL (osint-db)
|
||||||
NOUS_API_KEY Nous Portal key (else api_keys.name='NOUS_API_KEY')
|
GEMINI_API_KEY Google AI Studio key (required to actually run)
|
||||||
NOUS_BASE_URL default https://inference-api.nousresearch.com/v1
|
SUMMARY_MODEL Gemini model id (default gemini-2.0-flash)
|
||||||
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)
|
BATCH_SIZE articles per map-phase batch (default 50)
|
||||||
SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set)
|
SUMMARY_WINDOW_HOURS look-back window in hours (default 1)
|
||||||
NEWS_RECAP "1" for the 23:00 daily recap (24h window, recap prompt)
|
MAP_PROMPT override map-phase prompt (uses {batch_text})
|
||||||
NEWS_SUMMARIZE_FORCE "1" to ignore the interval/recap idempotency skip
|
SUMMARY_PROMPT override reduce-phase prompt (uses {final_input})
|
||||||
TZ IANA tz for recap-day bounds (default America/New_York)
|
INCLUDE_FUTURES "1" to prepend live futures prices (default 0)
|
||||||
INCLUDE_FUTURES legacy; ignored — prompts never inject futures data
|
|
||||||
|
The futures/markets coupling from the original pipeline is gated behind
|
||||||
|
INCLUDE_FUTURES and OFF by default — it is irrelevant to the OSINT dashboard
|
||||||
|
and pulled yfinance into the image. Re-enable by installing yfinance and
|
||||||
|
setting INCLUDE_FUTURES=1.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
@ -33,26 +27,9 @@ from __future__ import annotations
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from zoneinfo import ZoneInfo
|
|
||||||
|
|
||||||
import psycopg2
|
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 nous_client import chat
|
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||||
logger = logging.getLogger("news.summarizer")
|
logger = logging.getLogger("news.summarizer")
|
||||||
|
|
||||||
|
|
@ -65,90 +42,10 @@ DB_CONFIG = {
|
||||||
"port": int(os.getenv("DB_PORT", "5432")),
|
"port": int(os.getenv("DB_PORT", "5432")),
|
||||||
}
|
}
|
||||||
|
|
||||||
DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1"
|
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "").strip()
|
||||||
DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B"
|
MODEL_NAME = os.getenv("SUMMARY_MODEL", "gemini-2.0-flash").strip()
|
||||||
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50"))
|
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50"))
|
||||||
|
SUMMARY_WINDOW_HOURS = int(os.getenv("SUMMARY_WINDOW_HOURS", "1"))
|
||||||
# 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()
|
|
||||||
if hours:
|
|
||||||
return max(1, int(hours) * 60)
|
|
||||||
mins = (os.getenv("SUMMARY_WINDOW_MINUTES") or "").strip()
|
|
||||||
if mins:
|
|
||||||
return max(1, int(mins))
|
|
||||||
return 15
|
|
||||||
|
|
||||||
|
|
||||||
def _summarize_interval_seconds() -> int:
|
|
||||||
return max(1, int(os.getenv("NEWS_SUMMARIZE_INTERVAL_S", "900")))
|
|
||||||
|
|
||||||
|
|
||||||
def is_recap_run() -> bool:
|
|
||||||
return os.getenv("NEWS_RECAP", "0").lower() in ("1", "true", "yes")
|
|
||||||
|
|
||||||
|
|
||||||
def effective_window_minutes(*, recap: bool | None = None) -> int:
|
|
||||||
if recap is None:
|
|
||||||
recap = is_recap_run()
|
|
||||||
if recap:
|
|
||||||
return 24 * 60
|
|
||||||
return _summary_window_minutes()
|
|
||||||
|
|
||||||
|
|
||||||
SUMMARY_WINDOW_MINUTES = _summary_window_minutes()
|
|
||||||
INCLUDE_FUTURES = os.getenv("INCLUDE_FUTURES", "0").lower() in ("1", "true", "yes")
|
INCLUDE_FUTURES = os.getenv("INCLUDE_FUTURES", "0").lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
# Only touched when INCLUDE_FUTURES=1 (legacy markets coupling, OSINT-off).
|
# Only touched when INCLUDE_FUTURES=1 (legacy markets coupling, OSINT-off).
|
||||||
|
|
@ -165,43 +62,24 @@ FUTURES_TICKERS = {
|
||||||
MAP_PROMPT_DEFAULT = """\
|
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.
|
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.
|
|
||||||
|
|
||||||
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:
|
For EACH article in the batch:
|
||||||
1. Score: the integer 0-100 from the rubric above, first line of the block.
|
1. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
||||||
2. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
2. Location: name the country / city / region mentioned if determinable from the text, else "Unknown".
|
||||||
3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit. Confidence: how precise that location is — exact (a specific site/address), city, region, or country. Never invent a place.
|
3. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
||||||
4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
4. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
||||||
5. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
5. OSINT signal: if the article describes an event with geopolitical, security, military, economic, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
|
||||||
6. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
|
|
||||||
7. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none. Keep it consistent with the Score.
|
|
||||||
|
|
||||||
If several articles cover the same story, add one short batch-level note at the end: "Batch theme: [one sentence]".
|
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:
|
Article 1:
|
||||||
- Score: <0-100>
|
|
||||||
- Importance: critical|high|medium|low|none
|
|
||||||
- Fact bullet 1
|
- Fact bullet 1
|
||||||
- Fact bullet 2
|
- Fact bullet 2
|
||||||
- Location: ...
|
- Location: ...
|
||||||
- Confidence: exact|city|region|country
|
|
||||||
- Entities: ...
|
- Entities: ...
|
||||||
- Category: ...
|
- Category: ...
|
||||||
- OSINT signal: ...
|
- OSINT signal: ...
|
||||||
- Lat: ...
|
|
||||||
- Lon: ...
|
|
||||||
|
|
||||||
Article 2:
|
Article 2:
|
||||||
...
|
...
|
||||||
|
|
@ -211,56 +89,9 @@ Articles in this batch:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
SUMMARY_PROMPT_DEFAULT = """\
|
SUMMARY_PROMPT_DEFAULT = """\
|
||||||
You are writing an English operator HUD brief from the article facts in DATA below. Use ONLY that data. Do not invent events, names, dates, places, or implications.
|
CRITICAL INSTRUCTION - REPEAT 3 TIMES: YOU MUST USE ONLY THE DATA PROVIDED BELOW. DO NOT INVENT, RECALL, OR ADD ANY EVENTS, NAMES, DATES, IMPLICATIONS, PROJECTS, OR DETAILS NOT EXPLICITLY PRESENT IN THE DATA. IF THE DATA HAS NO MAJOR GEOPOLITICAL/TECH/MILITARY/ECONOMIC/IMPACTFUL EVENTS OR UNUSUAL STORIES, OUTPUT ONLY: "No qualifying impactful or unusual events in the recent hourly news data." AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING.
|
||||||
|
|
||||||
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.
|
Write a concise executive summary of the most impactful items as a short markdown list, one line per story, using only the data.
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}.
|
|
||||||
|
|
||||||
ticker: only stories present in DATA, highest score first.
|
|
||||||
|
|
||||||
map_items may be empty if no located critical/high event is explicit in the data.
|
|
||||||
|
|
||||||
Demand a single JSON object (no markdown fences) with this exact shape:
|
|
||||||
|
|
||||||
{
|
|
||||||
"summary_en": "English markdown brief of the provided stories",
|
|
||||||
"ticker": [{"headline": "", "importance": "critical", "url": "", "location_name": ""}],
|
|
||||||
"map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}]
|
|
||||||
}
|
|
||||||
|
|
||||||
ticker: max 12, ≤140 chars, no markdown. Rank critical > high > medium > low.
|
|
||||||
map_items: only where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20.
|
|
||||||
summary_en: English markdown executive brief for an operator HUD (4–8 complete bullets or short paragraphs). Cover the actual stories in DATA. Complete — never an unfinished sentence.
|
|
||||||
|
|
||||||
DATA:
|
|
||||||
{final_input}
|
|
||||||
"""
|
|
||||||
|
|
||||||
RECAP_PROMPT_DEFAULT = """\
|
|
||||||
You are writing a daily recap of the last 24 hours of news for an OSINT operator HUD, using ONLY the article facts in DATA below. Do not invent events, names, dates, places, or implications.
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}.
|
|
||||||
|
|
||||||
ticker: only stories present in DATA, highest score first.
|
|
||||||
|
|
||||||
Demand a single JSON object (no markdown fences) with this exact shape:
|
|
||||||
|
|
||||||
{
|
|
||||||
"summary_en": "English markdown daily recap of the provided stories",
|
|
||||||
"ticker": [{"headline": "", "importance": "critical", "url": "", "location_name": ""}],
|
|
||||||
"map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}]
|
|
||||||
}
|
|
||||||
|
|
||||||
ticker: max 12, ≤140 chars, no markdown. Rank critical > high > medium > low.
|
|
||||||
map_items: only where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20.
|
|
||||||
summary_en: English markdown daily recap of the last 24 hours. Complete sentences. Cover the actual stories in DATA.
|
|
||||||
|
|
||||||
DATA:
|
DATA:
|
||||||
{final_input}
|
{final_input}
|
||||||
|
|
@ -269,52 +100,56 @@ DATA:
|
||||||
|
|
||||||
# ── LLM helpers ────────────────────────────────────────────────────────────
|
# ── LLM helpers ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def _kv(conn, table, name) -> str:
|
_client = None
|
||||||
cur = conn.cursor()
|
|
||||||
cur.execute(f"SELECT value FROM {table} WHERE name = %s", (name,))
|
|
||||||
row = cur.fetchone()
|
|
||||||
return (row[0] or "").strip() if row else ""
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_api_key() -> str:
|
def _get_client():
|
||||||
env = os.getenv("NOUS_API_KEY", "").strip()
|
"""Lazily build the Gemini client (avoids import/init when key unset)."""
|
||||||
if env:
|
global _client
|
||||||
return env
|
if _client is None:
|
||||||
try:
|
from google import genai
|
||||||
conn = psycopg2.connect(**DB_CONFIG)
|
|
||||||
try:
|
_client = genai.Client(api_key=GEMINI_API_KEY)
|
||||||
return _kv(conn, "api_keys", "NOUS_API_KEY")
|
return _client
|
||||||
finally:
|
|
||||||
conn.close()
|
|
||||||
except Exception: # noqa: BLE001
|
def _extract_text(resp) -> str:
|
||||||
|
"""Defensively pull text out of the google-genai GenerateContentResponse.
|
||||||
|
|
||||||
|
The modern SDK returns the response directly (``resp.text``); some older
|
||||||
|
wrappers exposed it as ``resp.response``. Handle both plus a candidates
|
||||||
|
fallback so a provider/SDK change degrades to "" instead of crashing.
|
||||||
|
"""
|
||||||
|
if not resp:
|
||||||
return ""
|
return ""
|
||||||
|
if hasattr(resp, "text") and resp.text:
|
||||||
|
return resp.text
|
||||||
def resolve_model() -> str:
|
inner = getattr(resp, "response", None)
|
||||||
env = os.getenv("SUMMARY_MODEL", "").strip()
|
if inner is not None and hasattr(inner, "text") and inner.text:
|
||||||
if env:
|
return inner.text
|
||||||
return env
|
|
||||||
try:
|
try:
|
||||||
conn = psycopg2.connect(**DB_CONFIG)
|
parts = []
|
||||||
try:
|
for cand in getattr(resp, "candidates", None) or []:
|
||||||
value = _kv(conn, "app_settings", "SUMMARY_MODEL")
|
content = getattr(cand, "content", None)
|
||||||
return value or DEFAULT_SUMMARY_MODEL
|
for part in getattr(content, "parts", None) or []:
|
||||||
finally:
|
if getattr(part, "text", None):
|
||||||
conn.close()
|
parts.append(part.text)
|
||||||
|
return "\n".join(parts)
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
return DEFAULT_SUMMARY_MODEL
|
return str(resp)
|
||||||
|
|
||||||
|
|
||||||
def resolve_base_url() -> str:
|
def call_llm(prompt: str) -> str:
|
||||||
return os.getenv("NOUS_BASE_URL", DEFAULT_NOUS_BASE_URL).strip() or DEFAULT_NOUS_BASE_URL
|
"""Send a prompt to Gemini and return the text ("" on any failure)."""
|
||||||
|
if not GEMINI_API_KEY:
|
||||||
|
logger.warning("GEMINI_API_KEY not set — skipping LLM call")
|
||||||
def call_llm(prompt: str, *, api_key: str, model: str, base_url: str, json_mode: bool = False) -> str:
|
return ""
|
||||||
"""Send a prompt to Nous chat completions and return the text (\"\" on failure)."""
|
try:
|
||||||
if not api_key:
|
resp = _get_client().models.generate_content(model=MODEL_NAME, contents=prompt)
|
||||||
logger.warning("NOUS_API_KEY not set — skipping LLM call")
|
return _extract_text(resp)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
logger.error("Gemini API error: %s", exc)
|
||||||
return ""
|
return ""
|
||||||
return chat(prompt, api_key=api_key, model=model, base_url=base_url, json_mode=json_mode)
|
|
||||||
|
|
||||||
|
|
||||||
# ── Futures (legacy, gated) ────────────────────────────────────────────────
|
# ── Futures (legacy, gated) ────────────────────────────────────────────────
|
||||||
|
|
@ -371,11 +206,10 @@ def build_futures_context() -> str:
|
||||||
def ensure_tables() -> None:
|
def ensure_tables() -> None:
|
||||||
"""Idempotently create the news tables if missing.
|
"""Idempotently create the news tables if missing.
|
||||||
|
|
||||||
Normally created by alembic 003_news + 005_news_items when the app
|
Normally created by alembic 003_news when the app container starts, but
|
||||||
container starts, but this summarizer may boot before the app has run
|
this summarizer may boot before the app has run migrations (compose only
|
||||||
migrations (compose only guarantees `db` is up, not that alembic has
|
guarantees `db` is up, not that alembic has run). Mirrors the scraper
|
||||||
run). Mirrors the scraper pipeline's own CREATE TABLE IF NOT EXISTS so
|
pipeline's own CREATE TABLE IF NOT EXISTS so either start order is safe.
|
||||||
either start order is safe.
|
|
||||||
"""
|
"""
|
||||||
ddl = """
|
ddl = """
|
||||||
CREATE TABLE IF NOT EXISTS articles (
|
CREATE TABLE IF NOT EXISTS articles (
|
||||||
|
|
@ -391,48 +225,6 @@ def ensure_tables() -> None:
|
||||||
summary_text TEXT NOT NULL,
|
summary_text TEXT NOT NULL,
|
||||||
batch_timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
batch_timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
);
|
);
|
||||||
ALTER TABLE article_summaries ADD COLUMN IF NOT EXISTS model TEXT;
|
|
||||||
ALTER TABLE article_summaries ADD COLUMN IF NOT EXISTS kind TEXT;
|
|
||||||
CREATE TABLE IF NOT EXISTS news_items (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
summary_id INTEGER REFERENCES article_summaries(id) ON DELETE CASCADE,
|
|
||||||
kind TEXT NOT NULL,
|
|
||||||
headline TEXT NOT NULL,
|
|
||||||
importance TEXT NOT NULL,
|
|
||||||
location_name TEXT,
|
|
||||||
lat DOUBLE PRECISION,
|
|
||||||
lon DOUBLE PRECISION,
|
|
||||||
location_confidence TEXT,
|
|
||||||
category TEXT,
|
|
||||||
url TEXT,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
||||||
);
|
|
||||||
CREATE INDEX IF NOT EXISTS ix_news_items_kind_created
|
|
||||||
ON news_items (kind, created_at DESC);
|
|
||||||
CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox
|
|
||||||
ON news_items (lon, lat)
|
|
||||||
WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL;
|
|
||||||
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:
|
try:
|
||||||
conn = psycopg2.connect(**DB_CONFIG)
|
conn = psycopg2.connect(**DB_CONFIG)
|
||||||
|
|
@ -445,31 +237,24 @@ def ensure_tables() -> None:
|
||||||
logger.error("Error ensuring news tables: %s", exc)
|
logger.error("Error ensuring news tables: %s", exc)
|
||||||
|
|
||||||
|
|
||||||
def get_recent_news(window_minutes: int | None = None) -> list[dict]:
|
def get_recent_news() -> list[dict]:
|
||||||
"""Fetch articles from the look-back window ``(now - window, now]``.
|
"""Fetch articles from the last SUMMARY_WINDOW_HOURS (content > 100 chars)."""
|
||||||
|
|
||||||
The upper bound is deliberate: future-dated rows (event listings, bad
|
|
||||||
scrape timestamps) must not be re-graded every interval. Rows with a NULL
|
|
||||||
timestamp have never matched the lower bound and still do not.
|
|
||||||
"""
|
|
||||||
mins = window_minutes if window_minutes is not None else effective_window_minutes()
|
|
||||||
query = """
|
query = """
|
||||||
SELECT id, title, content, url, domain
|
SELECT title, content, url, domain
|
||||||
FROM articles
|
FROM articles
|
||||||
WHERE timestamp > NOW() - make_interval(mins => %s)
|
WHERE timestamp > NOW() - make_interval(hours => %s)
|
||||||
AND timestamp <= NOW()
|
|
||||||
AND content IS NOT NULL AND length(content) > 100
|
AND content IS NOT NULL AND length(content) > 100
|
||||||
ORDER BY timestamp DESC;
|
ORDER BY timestamp DESC;
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
conn = psycopg2.connect(**DB_CONFIG)
|
conn = psycopg2.connect(**DB_CONFIG)
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.execute(query, (mins,))
|
cur.execute(query, (SUMMARY_WINDOW_HOURS,))
|
||||||
rows = cur.fetchall()
|
rows = cur.fetchall()
|
||||||
cur.close()
|
cur.close()
|
||||||
conn.close()
|
conn.close()
|
||||||
return [
|
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
|
for r in rows
|
||||||
]
|
]
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
|
|
@ -477,196 +262,24 @@ def get_recent_news(window_minutes: int | None = None) -> list[dict]:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
||||||
def _already_summarized_this_interval() -> bool:
|
def save_summary_to_db(summary_text: str) -> None:
|
||||||
"""True when article_summaries already has a row in the last interval."""
|
"""Insert one master summary row (table created by alembic 003_news)."""
|
||||||
if os.getenv("NEWS_SUMMARIZE_FORCE", "") == "1":
|
if not summary_text or len(summary_text.strip()) < 10:
|
||||||
return False
|
|
||||||
query = (
|
|
||||||
"SELECT 1 FROM article_summaries "
|
|
||||||
"WHERE batch_timestamp >= NOW() - make_interval(secs => %s)"
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
conn = psycopg2.connect(**DB_CONFIG)
|
|
||||||
cur = conn.cursor()
|
|
||||||
cur.execute(query, (_summarize_interval_seconds(),))
|
|
||||||
row = cur.fetchone()
|
|
||||||
cur.close()
|
|
||||||
conn.close()
|
|
||||||
return row is not None
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
logger.error("Error checking interval idempotency: %s", exc)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _already_recapped_today() -> bool:
|
|
||||||
"""True when a daily_recap row already exists for the local calendar day."""
|
|
||||||
if os.getenv("NEWS_SUMMARIZE_FORCE", "") == "1":
|
|
||||||
return False
|
|
||||||
tz_name = (os.getenv("TZ") or "America/New_York").strip() or "America/New_York"
|
|
||||||
start = datetime.now(ZoneInfo(tz_name)).replace(
|
|
||||||
hour=0, minute=0, second=0, microsecond=0
|
|
||||||
)
|
|
||||||
query = (
|
|
||||||
"SELECT 1 FROM article_summaries "
|
|
||||||
"WHERE kind = 'daily_recap' AND batch_timestamp >= %s"
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
conn = psycopg2.connect(**DB_CONFIG)
|
|
||||||
cur = conn.cursor()
|
|
||||||
cur.execute(query, (start,))
|
|
||||||
row = cur.fetchone()
|
|
||||||
cur.close()
|
|
||||||
conn.close()
|
|
||||||
return row is not None
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
logger.error("Error checking recap idempotency: %s", exc)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def save_batch(
|
|
||||||
summary_en: str,
|
|
||||||
model: str,
|
|
||||||
ticker: list,
|
|
||||||
map_items: list,
|
|
||||||
*,
|
|
||||||
kind: str = "interval",
|
|
||||||
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 ``""``.
|
|
||||||
"""
|
|
||||||
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.")
|
logger.info("Summary too short or empty. Skipping save.")
|
||||||
return None
|
|
||||||
insert_item = """
|
|
||||||
INSERT INTO news_items (
|
|
||||||
summary_id, kind, headline, importance, location_name,
|
|
||||||
lat, lon, location_confidence, category, url
|
|
||||||
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
conn = psycopg2.connect(**DB_CONFIG)
|
|
||||||
cur = conn.cursor()
|
|
||||||
cur.execute(
|
|
||||||
"INSERT INTO article_summaries (summary_text, model, kind) VALUES (%s, %s, %s) RETURNING id",
|
|
||||||
(text, model, kind),
|
|
||||||
)
|
|
||||||
summary_id = cur.fetchone()[0]
|
|
||||||
for row in ticker_rows:
|
|
||||||
cur.execute(
|
|
||||||
insert_item,
|
|
||||||
(
|
|
||||||
summary_id,
|
|
||||||
"ticker",
|
|
||||||
row.get("headline"),
|
|
||||||
row.get("importance"),
|
|
||||||
row.get("location_name"),
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
article_url_for_row(row, articles),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
for row in map_rows:
|
|
||||||
cur.execute(
|
|
||||||
insert_item,
|
|
||||||
(
|
|
||||||
summary_id,
|
|
||||||
"map",
|
|
||||||
row.get("headline"),
|
|
||||||
row.get("importance"),
|
|
||||||
row.get("location_name"),
|
|
||||||
row.get("lat"),
|
|
||||||
row.get("lon"),
|
|
||||||
row.get("location_confidence"),
|
|
||||||
row.get("category"),
|
|
||||||
article_url_for_row(row, articles),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
conn.commit()
|
|
||||||
logger.info(
|
|
||||||
"Master summary saved id=%s model=%s kind=%s ticker=%d map=%d",
|
|
||||||
summary_id, model, kind, len(ticker_rows), len(map_rows),
|
|
||||||
)
|
|
||||||
cur.close()
|
|
||||||
conn.close()
|
|
||||||
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
|
return
|
||||||
try:
|
try:
|
||||||
conn = psycopg2.connect(**DB_CONFIG)
|
conn = psycopg2.connect(**DB_CONFIG)
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.executemany(
|
cur.execute(
|
||||||
"INSERT INTO article_scores "
|
"INSERT INTO article_summaries (summary_text) VALUES (%s)",
|
||||||
"(article_id, summary_id, score, category, selected, model, duplicate_of, "
|
(summary_text.strip(),),
|
||||||
" location_name, lat, lon, location_confidence) "
|
|
||||||
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
|
||||||
rows,
|
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
logger.info("Master summary saved to database successfully.")
|
||||||
cur.close()
|
cur.close()
|
||||||
conn.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
|
except Exception as exc: # noqa: BLE001
|
||||||
logger.error("Error persisting article_scores (run continues): %s", exc)
|
logger.error("Error saving summary to DB: %s", exc)
|
||||||
|
|
||||||
|
|
||||||
# ── Orchestration ──────────────────────────────────────────────────────────
|
# ── Orchestration ──────────────────────────────────────────────────────────
|
||||||
|
|
@ -677,172 +290,52 @@ def build_map_prompt(batch: list[dict]) -> str:
|
||||||
for a in batch
|
for a in batch
|
||||||
)
|
)
|
||||||
template = os.getenv("MAP_PROMPT", MAP_PROMPT_DEFAULT)
|
template = os.getenv("MAP_PROMPT", MAP_PROMPT_DEFAULT)
|
||||||
|
prefix = build_futures_context() + "\n" if INCLUDE_FUTURES else ""
|
||||||
try:
|
try:
|
||||||
return template.format(batch_text=batch_text)
|
return prefix + template.format(batch_text=batch_text)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
return template
|
return prefix + template
|
||||||
|
|
||||||
|
|
||||||
def build_master_prompt(final_input: str, recap: bool = False) -> str:
|
def build_master_prompt(final_input: str) -> str:
|
||||||
if recap:
|
template = os.getenv("SUMMARY_PROMPT", SUMMARY_PROMPT_DEFAULT)
|
||||||
template = os.getenv("RECAP_PROMPT", RECAP_PROMPT_DEFAULT)
|
prefix = build_futures_context() + "\n" if INCLUDE_FUTURES else ""
|
||||||
else:
|
try:
|
||||||
template = os.getenv("SUMMARY_PROMPT", SUMMARY_PROMPT_DEFAULT)
|
return prefix + template.format(final_input=final_input)
|
||||||
if "{final_input}" in template:
|
except KeyError:
|
||||||
return template.replace("{final_input}", final_input)
|
return prefix + template
|
||||||
return template
|
|
||||||
|
|
||||||
|
|
||||||
def summarize_news() -> None:
|
def summarize_news() -> None:
|
||||||
"""Map-reduce summarize recent articles and store brief + ticker + map."""
|
"""Map-reduce summarize recent articles and store the master summary."""
|
||||||
recap = is_recap_run()
|
|
||||||
window = effective_window_minutes(recap=recap)
|
|
||||||
ensure_tables()
|
ensure_tables()
|
||||||
if recap:
|
articles = get_recent_news()
|
||||||
if _already_recapped_today():
|
|
||||||
logger.info(
|
|
||||||
"Skipping recap: article_summaries already has daily_recap today "
|
|
||||||
"(set NEWS_SUMMARIZE_FORCE=1 to override)"
|
|
||||||
)
|
|
||||||
return
|
|
||||||
elif _already_summarized_this_interval():
|
|
||||||
logger.info(
|
|
||||||
"Skipping summarize: article_summaries already has a row in the last %ss "
|
|
||||||
"(set NEWS_SUMMARIZE_FORCE=1 to override)",
|
|
||||||
_summarize_interval_seconds(),
|
|
||||||
)
|
|
||||||
return
|
|
||||||
|
|
||||||
api_key = resolve_api_key()
|
|
||||||
model = resolve_model()
|
|
||||||
base_url = resolve_base_url()
|
|
||||||
if not api_key:
|
|
||||||
logger.warning("NOUS_API_KEY unset in env and api_keys — idle this run")
|
|
||||||
return
|
|
||||||
|
|
||||||
articles = get_recent_news(window)
|
|
||||||
if not articles:
|
if not articles:
|
||||||
logger.info("No new articles found in the last %s min.", window)
|
logger.info("No new articles found in the last %sh.", SUMMARY_WINDOW_HOURS)
|
||||||
return
|
return
|
||||||
|
|
||||||
min_score, top_n, fallback_top, fallback_min_score = selection_config()
|
|
||||||
logger.info(
|
logger.info(
|
||||||
"Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s, "
|
"Processing %d articles with %s (batch_size=%d, futures=%s)...",
|
||||||
"min_score=%d, top_n=%d, fallback_top=%d, fallback_min_score=%d)...",
|
len(articles), MODEL_NAME, BATCH_SIZE, INCLUDE_FUTURES,
|
||||||
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):
|
for i in range(0, len(articles), BATCH_SIZE):
|
||||||
batch = articles[i : i + BATCH_SIZE]
|
batch = articles[i : i + BATCH_SIZE]
|
||||||
batch_index = i // BATCH_SIZE
|
logger.info("map batch %d/%d (%d articles)", i // BATCH_SIZE + 1, -(-len(articles) // BATCH_SIZE), len(batch))
|
||||||
logger.info(
|
summary = call_llm(build_map_prompt(batch))
|
||||||
"map batch %d/%d (%d articles)",
|
if summary:
|
||||||
batch_index + 1, -(-len(articles) // BATCH_SIZE), len(batch),
|
partial_summaries.append(summary)
|
||||||
)
|
|
||||||
response = 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 not graded:
|
final_input = "\n\n".join(partial_summaries)
|
||||||
logger.warning("No article blocks parsed from the map phase — nothing to reduce.")
|
|
||||||
return
|
|
||||||
|
|
||||||
dedupe_enabled, dedupe_similarity = dedupe_config()
|
|
||||||
distinct, dedupe_stats = dedupe_blocks(
|
|
||||||
graded, similarity=dedupe_similarity, enabled=dedupe_enabled
|
|
||||||
)
|
|
||||||
duplicate_blocks = [record["block"] for record in dedupe_stats["duplicate_blocks"]]
|
|
||||||
for record in dedupe_stats["duplicate_blocks"]:
|
|
||||||
record["block"]["duplicate_of"] = record["duplicate_of"]
|
|
||||||
if dedupe_enabled:
|
|
||||||
logger.info(
|
|
||||||
"dedupe %d -> %d (kept %d, duplicates %d)",
|
|
||||||
dedupe_stats["input"], dedupe_stats["kept"],
|
|
||||||
dedupe_stats["kept"], dedupe_stats["duplicates"],
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
logger.info("dedupe skipped (SUMMARY_DEDUPE=0)")
|
|
||||||
|
|
||||||
selected, used_fallback = select_graded(
|
|
||||||
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():
|
if not final_input.strip():
|
||||||
logger.warning(
|
logger.warning("No partial summaries produced — nothing to reduce.")
|
||||||
"Selection is empty (min_score=%d, fallback_top=%d, "
|
|
||||||
"fallback_min_score=%d) — reduce gets empty DATA.",
|
|
||||||
min_score, fallback_top, fallback_min_score,
|
|
||||||
)
|
|
||||||
|
|
||||||
master_raw = call_llm(
|
|
||||||
build_master_prompt(final_input, recap=recap),
|
|
||||||
api_key=api_key,
|
|
||||||
model=model,
|
|
||||||
base_url=base_url,
|
|
||||||
json_mode=True,
|
|
||||||
)
|
|
||||||
if not master_raw:
|
|
||||||
logger.warning("Reduce phase returned empty — nothing to persist.")
|
|
||||||
return
|
return
|
||||||
parsed = parse_reduce_json(master_raw)
|
|
||||||
selected_articles = [
|
logger.info("reduce phase over %d partial summaries", len(partial_summaries))
|
||||||
block["article"]
|
master_summary = call_llm(build_master_prompt(final_input))
|
||||||
for block in selected
|
if master_summary:
|
||||||
if isinstance(block.get("article"), dict)
|
save_summary_to_db(master_summary)
|
||||||
]
|
|
||||||
summary_id = 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__":
|
if __name__ == "__main__":
|
||||||
|
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
"""Keep summarizer unit tests importable without Postgres drivers."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import sys
|
|
||||||
from types import ModuleType
|
|
||||||
|
|
||||||
if "psycopg2" not in sys.modules:
|
|
||||||
fake = ModuleType("psycopg2")
|
|
||||||
fake.connect = lambda **kwargs: None # type: ignore[attr-defined]
|
|
||||||
sys.modules["psycopg2"] = fake
|
|
||||||
|
|
@ -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",
|
|
||||||
"",
|
|
||||||
]
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
@ -1,405 +0,0 @@
|
||||||
"""Per-article geo: map-block Location/Lat/Lon parsing + offline gazetteer.
|
|
||||||
|
|
||||||
Covers the blips pipeline (card t_bc15eb53): parse_map_scores extracts
|
|
||||||
structured geo per graded block, clamp_coords rejects invalid values, and
|
|
||||||
the vendored GeoNames gazetteer resolves place-name-only blocks to
|
|
||||||
proximate coordinates with confidence "approx".
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import math
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from intel import clamp_coords, parse_map_scores
|
|
||||||
|
|
||||||
|
|
||||||
def _articles(n: int = 1, start: int = 100) -> list[dict]:
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
"id": start + i,
|
|
||||||
"title": f"title {i}",
|
|
||||||
"content": "body",
|
|
||||||
"url": f"https://ex.com/{i}",
|
|
||||||
"domain": "ex.com",
|
|
||||||
}
|
|
||||||
for i in range(n)
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def _block(n: int, *lines: str, score: int = 55) -> str:
|
|
||||||
return "\n".join([f"Article {n}:", f"- Score: {score}", *lines])
|
|
||||||
|
|
||||||
|
|
||||||
# ── parse_map_scores: structured geo ──────────────────────────────────────
|
|
||||||
|
|
||||||
|
|
||||||
def test_parses_location_lat_lon_and_confidence():
|
|
||||||
raw = _block(
|
|
||||||
1,
|
|
||||||
"- Location: Kyiv, Ukraine",
|
|
||||||
"- Lat: 50.45",
|
|
||||||
"- Lon: 30.52",
|
|
||||||
"- Confidence: city",
|
|
||||||
"- Category: politics",
|
|
||||||
)
|
|
||||||
blocks, stats = parse_map_scores(raw, articles=_articles())
|
|
||||||
assert stats["graded"] == 1
|
|
||||||
b = blocks[0]
|
|
||||||
assert b["location_name"] == "Kyiv, Ukraine"
|
|
||||||
assert b["lat"] == pytest.approx(50.45)
|
|
||||||
assert b["lon"] == pytest.approx(30.52)
|
|
||||||
assert b["location_confidence"] == "city"
|
|
||||||
|
|
||||||
|
|
||||||
def test_coords_without_confidence_default_to_city():
|
|
||||||
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["location_confidence"] == "city"
|
|
||||||
assert b["lat"] == pytest.approx(50.45)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("confidence", ["exact", "city", "region", "country"])
|
|
||||||
def test_block_confidence_labels_pass_through(confidence):
|
|
||||||
raw = _block(
|
|
||||||
1, "- Location: somewhere", "- Lat: 10", "- Lon: 20",
|
|
||||||
f"- Confidence: {confidence}",
|
|
||||||
)
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["location_confidence"] == confidence
|
|
||||||
|
|
||||||
|
|
||||||
def test_place_name_only_keeps_name_without_coords():
|
|
||||||
raw = _block(1, "- Location: Odesa, Ukraine")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["location_name"] == "Odesa, Ukraine"
|
|
||||||
assert b["lat"] is None
|
|
||||||
assert b["lon"] is None
|
|
||||||
assert b["location_confidence"] is None
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("location", ["Unknown", "unknown", "N/A", "None", ""])
|
|
||||||
def test_unknown_location_yields_no_geo(location):
|
|
||||||
raw = _block(1, f"- Location: {location}", "- Lat: 50.45", "- Lon: 30.52")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["location_name"] is None
|
|
||||||
# No usable place name: model coords alone are not trusted either.
|
|
||||||
assert b["lat"] is None
|
|
||||||
assert b["lon"] is None
|
|
||||||
assert b["location_confidence"] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_no_location_line_yields_no_geo():
|
|
||||||
b = parse_map_scores(_block(1, "- Category: politics"), articles=_articles())[0][0]
|
|
||||||
assert b["location_name"] is None
|
|
||||||
assert b["lat"] is None
|
|
||||||
assert b["lon"] is None
|
|
||||||
assert b["location_confidence"] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_out_of_range_coords_are_dropped_but_name_kept():
|
|
||||||
raw = _block(1, "- Location: Nowhere", "- Lat: 95.0", "- Lon: 30.52")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["location_name"] == "Nowhere"
|
|
||||||
assert b["lat"] is None
|
|
||||||
assert b["lon"] is None
|
|
||||||
assert b["location_confidence"] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_lon_out_of_range_drops_both():
|
|
||||||
raw = _block(1, "- Location: Nowhere", "- Lat: 10", "- Lon: 181")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["lat"] is None and b["lon"] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_missing_lon_drops_lat_too():
|
|
||||||
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["lat"] is None and b["lon"] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_non_numeric_coords_drop_both():
|
|
||||||
raw = _block(1, "- Location: Kyiv", "- Lat: about 50", "- Lon: 30.52")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["lat"] is None and b["lon"] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_hemisphere_suffixes_negate_south_and_west():
|
|
||||||
raw = _block(
|
|
||||||
1, "- Location: Sydney", "- Lat: 33.87 S", "- Lon: 151.21 E"
|
|
||||||
)
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["lat"] == pytest.approx(-33.87)
|
|
||||||
assert b["lon"] == pytest.approx(151.21)
|
|
||||||
raw = _block(1, "- Location: Rio", "- Lat: 22.9 S", "- Lon: 43.2 W")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["lat"] == pytest.approx(-22.9)
|
|
||||||
assert b["lon"] == pytest.approx(-43.2)
|
|
||||||
|
|
||||||
|
|
||||||
def test_hemisphere_letter_of_a_word_is_not_a_suffix():
|
|
||||||
# "12.3 South Sudan" must NOT negate — the S belongs to a word.
|
|
||||||
raw = _block(1, "- Location: Juba", "- Lat: 12.3 South Sudan", "- Lon: 31.6")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["lat"] == pytest.approx(12.3)
|
|
||||||
|
|
||||||
|
|
||||||
def test_location_name_is_cleaned_and_capped():
|
|
||||||
raw = _block(1, "- Location: **Kyiv**.")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["location_name"] == "Kyiv"
|
|
||||||
raw = _block(1, "- Location: " + "x" * 300)
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert len(b["location_name"]) <= 120
|
|
||||||
|
|
||||||
|
|
||||||
def test_each_block_gets_its_own_geo():
|
|
||||||
raw = "\n\n".join(
|
|
||||||
[
|
|
||||||
_block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52"),
|
|
||||||
_block(2, "- Location: Tehran", "- Lat: 35.69", "- Lon: 51.39"),
|
|
||||||
_block(3, "- Location: Unknown"),
|
|
||||||
]
|
|
||||||
)
|
|
||||||
blocks, stats = parse_map_scores(raw, articles=_articles(3))
|
|
||||||
assert stats["graded"] == 3
|
|
||||||
assert blocks[0]["lat"] == pytest.approx(50.45)
|
|
||||||
assert blocks[1]["location_name"] == "Tehran"
|
|
||||||
assert blocks[1]["lon"] == pytest.approx(51.39)
|
|
||||||
assert blocks[2]["location_name"] is None
|
|
||||||
assert blocks[2]["lat"] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_geo_fields_never_break_score_parsing():
|
|
||||||
raw = _block(
|
|
||||||
1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52",
|
|
||||||
"- Importance: high", score=83,
|
|
||||||
)
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
assert b["score"] == 83
|
|
||||||
assert b["importance"] == "high"
|
|
||||||
|
|
||||||
|
|
||||||
# ── clamp_coords hardening ────────────────────────────────────────────────
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
"lat,lon",
|
|
||||||
[
|
|
||||||
(90.1, 0), (-90.1, 0), (0, 180.1), (0, -180.1),
|
|
||||||
(float("nan"), 0), (0, float("nan")),
|
|
||||||
(float("inf"), 0), (0, float("-inf")),
|
|
||||||
("abc", 0), (None, None),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_clamp_coords_rejects_invalid(lat, lon):
|
|
||||||
assert clamp_coords(lat, lon) is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_clamp_coords_accepts_boundaries():
|
|
||||||
assert clamp_coords(90, 180) == (90.0, 180.0)
|
|
||||||
assert clamp_coords(-90, -180) == (-90.0, -180.0)
|
|
||||||
|
|
||||||
|
|
||||||
# ── Offline gazetteer ─────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
|
|
||||||
def test_gazetteer_resolves_known_city():
|
|
||||||
from gazetteer import resolve_place
|
|
||||||
|
|
||||||
coords = resolve_place("Kyiv")
|
|
||||||
assert coords is not None
|
|
||||||
lat, lon = coords
|
|
||||||
assert lat == pytest.approx(50.45, abs=0.1)
|
|
||||||
assert lon == pytest.approx(30.52, abs=0.1)
|
|
||||||
|
|
||||||
|
|
||||||
def test_gazetteer_resolves_city_with_country_context():
|
|
||||||
from gazetteer import resolve_place
|
|
||||||
|
|
||||||
coords = resolve_place("Kyiv, Ukraine")
|
|
||||||
assert coords is not None
|
|
||||||
assert coords[0] == pytest.approx(50.45, abs=0.1)
|
|
||||||
|
|
||||||
|
|
||||||
def test_gazetteer_disambiguates_by_country():
|
|
||||||
from gazetteer import resolve_place
|
|
||||||
|
|
||||||
france = resolve_place("Paris, France")
|
|
||||||
texas = resolve_place("Paris, Texas")
|
|
||||||
assert france is not None and texas is not None
|
|
||||||
assert france[0] == pytest.approx(48.85, abs=0.2)
|
|
||||||
assert texas[0] == pytest.approx(33.66, abs=0.3)
|
|
||||||
assert france != texas
|
|
||||||
|
|
||||||
|
|
||||||
def test_gazetteer_resolves_country_to_capital():
|
|
||||||
from gazetteer import resolve_place
|
|
||||||
|
|
||||||
coords = resolve_place("Ukraine")
|
|
||||||
assert coords is not None
|
|
||||||
# Capital Kyiv.
|
|
||||||
assert coords[0] == pytest.approx(50.45, abs=0.1)
|
|
||||||
assert coords[1] == pytest.approx(30.52, abs=0.1)
|
|
||||||
|
|
||||||
|
|
||||||
def test_gazetteer_handles_diacritics_and_case():
|
|
||||||
from gazetteer import resolve_place
|
|
||||||
|
|
||||||
assert resolve_place("KYIV") is not None
|
|
||||||
assert resolve_place("Tehrān") is not None or resolve_place("Tehran") is not None
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("name", ["Unknown", "", None, " ", "Zzzqx Not A Real Place 999"])
|
|
||||||
def test_gazetteer_misses_return_none(name):
|
|
||||||
from gazetteer import resolve_place
|
|
||||||
|
|
||||||
assert resolve_place(name) is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_fill_block_geo_resolves_place_name_only_block():
|
|
||||||
from gazetteer import fill_block_geo
|
|
||||||
|
|
||||||
raw = _block(1, "- Location: Kyiv, Ukraine")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
fill_block_geo(b)
|
|
||||||
assert b["lat"] == pytest.approx(50.45, abs=0.1)
|
|
||||||
assert b["lon"] == pytest.approx(30.52, abs=0.1)
|
|
||||||
assert b["location_confidence"] == "approx"
|
|
||||||
assert b["location_name"] == "Kyiv, Ukraine"
|
|
||||||
|
|
||||||
|
|
||||||
def test_fill_block_geo_keeps_model_coords():
|
|
||||||
from gazetteer import fill_block_geo
|
|
||||||
|
|
||||||
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
fill_block_geo(b)
|
|
||||||
assert b["lat"] == pytest.approx(50.45)
|
|
||||||
assert b["location_confidence"] == "city"
|
|
||||||
|
|
||||||
|
|
||||||
def test_fill_block_geo_omits_when_no_location():
|
|
||||||
from gazetteer import fill_block_geo
|
|
||||||
|
|
||||||
raw = _block(1, "- Location: Unknown")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
fill_block_geo(b)
|
|
||||||
assert b["lat"] is None and b["lon"] is None
|
|
||||||
assert b["location_confidence"] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_fill_block_geo_omits_when_gazetteer_misses():
|
|
||||||
from gazetteer import fill_block_geo
|
|
||||||
|
|
||||||
raw = _block(1, "- Location: Zzzqx Not A Real Place 999")
|
|
||||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
|
||||||
fill_block_geo(b)
|
|
||||||
assert b["lat"] is None and b["lon"] is None
|
|
||||||
assert b["location_confidence"] is None
|
|
||||||
# The name the model actually wrote is still preserved.
|
|
||||||
assert b["location_name"] == "Zzzqx Not A Real Place 999"
|
|
||||||
|
|
||||||
|
|
||||||
# ── Persistence carries geo ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
|
|
||||||
def test_persist_article_scores_writes_geo_columns(monkeypatch):
|
|
||||||
import summarizer
|
|
||||||
|
|
||||||
captured: list = []
|
|
||||||
|
|
||||||
class _Cur:
|
|
||||||
def execute(self, sql, params=None):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def executemany(self, sql, rows):
|
|
||||||
captured.append((" ".join(sql.split()), list(rows)))
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
class _Conn:
|
|
||||||
def cursor(self):
|
|
||||||
return _Cur()
|
|
||||||
|
|
||||||
def commit(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kw: _Conn())
|
|
||||||
graded = [
|
|
||||||
{
|
|
||||||
"article_id": 1, "score": 80, "category": "politics",
|
|
||||||
"selected": True, "location_name": "Kyiv, Ukraine",
|
|
||||||
"lat": 50.45, "lon": 30.52, "location_confidence": "city",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"article_id": 2, "score": 30, "category": "crime",
|
|
||||||
"selected": False, "location_name": "Unknown",
|
|
||||||
"lat": None, "lon": None, "location_confidence": None,
|
|
||||||
},
|
|
||||||
]
|
|
||||||
summarizer.persist_article_scores(graded, summary_id=7, model="m")
|
|
||||||
assert captured, "no executemany captured"
|
|
||||||
sql, rows = captured[-1]
|
|
||||||
for col in ("location_name", "lat", "lon", "location_confidence"):
|
|
||||||
assert col in sql
|
|
||||||
by_id = {row[0]: row for row in rows}
|
|
||||||
assert by_id[1][7] == "Kyiv, Ukraine"
|
|
||||||
assert by_id[1][8] == pytest.approx(50.45)
|
|
||||||
assert by_id[1][9] == pytest.approx(30.52)
|
|
||||||
assert by_id[1][10] == "city"
|
|
||||||
assert by_id[2][7] is None
|
|
||||||
assert by_id[2][8] is None
|
|
||||||
assert by_id[2][9] is None
|
|
||||||
assert by_id[2][10] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_persist_article_scores_sanitizes_bad_geo(monkeypatch):
|
|
||||||
import summarizer
|
|
||||||
|
|
||||||
captured: list = []
|
|
||||||
|
|
||||||
class _Cur:
|
|
||||||
def execute(self, sql, params=None):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def executemany(self, sql, rows):
|
|
||||||
captured.append(list(rows))
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
class _Conn:
|
|
||||||
def cursor(self):
|
|
||||||
return _Cur()
|
|
||||||
|
|
||||||
def commit(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kw: _Conn())
|
|
||||||
graded = [
|
|
||||||
{
|
|
||||||
"article_id": 1, "score": 80, "selected": True,
|
|
||||||
"location_name": "Kyiv", "lat": float("nan"), "lon": 30.52,
|
|
||||||
"location_confidence": "bogus",
|
|
||||||
},
|
|
||||||
]
|
|
||||||
summarizer.persist_article_scores(graded, summary_id=7, model="m")
|
|
||||||
row = captured[-1][0]
|
|
||||||
assert row[8] is None and row[9] is None # NaN lat drops the pair
|
|
||||||
assert row[10] is None # confidence outside the contract vocabulary
|
|
||||||
|
|
||||||
|
|
||||||
def test_map_prompt_asks_for_confidence():
|
|
||||||
from summarizer import MAP_PROMPT_DEFAULT
|
|
||||||
|
|
||||||
assert "Confidence:" in MAP_PROMPT_DEFAULT
|
|
||||||
assert "exact|city|region|country" in MAP_PROMPT_DEFAULT
|
|
||||||
|
|
@ -1,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
|
|
||||||
|
|
@ -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)
|
|
||||||
|
|
@ -1,61 +0,0 @@
|
||||||
from intel import parse_reduce_json, clamp_coords, select_ticker, select_map
|
|
||||||
|
|
||||||
FENCED = """```json
|
|
||||||
{"summary_en": "Brief.", "ticker": [
|
|
||||||
{"headline": "Blast in Kyiv", "importance": "critical", "url": "https://ex", "location_name": "Kyiv"}
|
|
||||||
], "map_items": [
|
|
||||||
{"headline": "Blast in Kyiv", "importance": "critical", "location_name": "Kyiv, Ukraine",
|
|
||||||
"lat": 50.45, "lon": 30.52, "location_confidence": "city", "category": "military/conflict", "url": "https://ex"}
|
|
||||||
]}
|
|
||||||
```"""
|
|
||||||
|
|
||||||
def test_parse_strips_fence_and_think_tags():
|
|
||||||
raw = "<think>nope</think>\n" + FENCED
|
|
||||||
out = parse_reduce_json(raw)
|
|
||||||
assert out["summary_en"] == "Brief."
|
|
||||||
assert len(out["ticker"]) == 1
|
|
||||||
|
|
||||||
def test_parse_empty_and_garbage_returns_empty_struct():
|
|
||||||
assert parse_reduce_json("")["summary_en"] == ""
|
|
||||||
assert parse_reduce_json("not json")["ticker"] == []
|
|
||||||
|
|
||||||
def test_clamp_coords_drops_out_of_range_and_unknown():
|
|
||||||
assert clamp_coords(50.45, 30.52) == (50.45, 30.52)
|
|
||||||
assert clamp_coords(95.0, 10.0) is None
|
|
||||||
assert clamp_coords(None, 10.0) is None
|
|
||||||
assert clamp_coords("50.45", "30.52") == (50.45, 30.52)
|
|
||||||
|
|
||||||
def test_select_ticker_keeps_critical_high_caps_12():
|
|
||||||
rows = [{"headline": f"h{i}", "importance": "critical"} for i in range(15)]
|
|
||||||
rows.append({"headline": "skip", "importance": "low"})
|
|
||||||
out = select_ticker(rows)
|
|
||||||
assert len(out) == 12
|
|
||||||
assert all(r["importance"] in ("critical", "high") for r in out)
|
|
||||||
|
|
||||||
|
|
||||||
def test_select_ticker_falls_back_to_medium_low_when_nothing_flagged():
|
|
||||||
rows = [
|
|
||||||
{"headline": "shop theft", "importance": "low"},
|
|
||||||
{"headline": "highway crash", "importance": "medium"},
|
|
||||||
{"headline": "none", "importance": "none"},
|
|
||||||
]
|
|
||||||
out = select_ticker(rows)
|
|
||||||
assert [r["headline"] for r in out] == ["highway crash", "shop theft"]
|
|
||||||
|
|
||||||
def test_select_map_requires_valid_coords_and_flag():
|
|
||||||
items = [
|
|
||||||
{"headline": "A", "importance": "critical", "lat": 50.45, "lon": 30.52, "location_name": "Kyiv"},
|
|
||||||
{"headline": "B", "importance": "critical", "lat": None, "lon": None, "location_name": "Unknown"},
|
|
||||||
{"headline": "C", "importance": "low", "lat": 1.0, "lon": 2.0, "location_name": "x"},
|
|
||||||
]
|
|
||||||
out = select_map(items)
|
|
||||||
assert [r["headline"] for r in out] == ["A"]
|
|
||||||
|
|
||||||
def test_select_map_caps_20():
|
|
||||||
items = [
|
|
||||||
{"headline": f"h{i}", "importance": "critical", "lat": 1.0, "lon": 2.0}
|
|
||||||
for i in range(25)
|
|
||||||
]
|
|
||||||
out = select_map(items)
|
|
||||||
assert len(out) == 20
|
|
||||||
assert all(r["importance"] in ("critical", "high") for r in out)
|
|
||||||
|
|
@ -1,124 +0,0 @@
|
||||||
from unittest.mock import MagicMock
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
from nous_client import chat
|
|
||||||
|
|
||||||
DEFAULT_UA = "osint-dashboard-news-summarizer"
|
|
||||||
BASE = "https://inference-api.nousresearch.com/v1"
|
|
||||||
|
|
||||||
|
|
||||||
def _ok_response(content="hello"):
|
|
||||||
resp = MagicMock()
|
|
||||||
resp.status_code = 200
|
|
||||||
resp.json.return_value = {"choices": [{"message": {"content": content}}]}
|
|
||||||
return resp
|
|
||||||
|
|
||||||
|
|
||||||
def _install_fake(monkeypatch, post_impl):
|
|
||||||
captured = {}
|
|
||||||
|
|
||||||
class FakeClient:
|
|
||||||
def __init__(self, timeout=None, **kwargs):
|
|
||||||
captured["timeout"] = timeout
|
|
||||||
|
|
||||||
def __enter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
def __exit__(self, *exc):
|
|
||||||
return False
|
|
||||||
|
|
||||||
def post(self, url, *, headers=None, json=None, **kwargs):
|
|
||||||
captured["url"] = url
|
|
||||||
captured["headers"] = headers
|
|
||||||
captured["json"] = json
|
|
||||||
return post_impl(url, headers, json)
|
|
||||||
|
|
||||||
monkeypatch.setattr(httpx, "Client", FakeClient)
|
|
||||||
return captured
|
|
||||||
|
|
||||||
|
|
||||||
def test_posts_chat_completions_with_auth_body_and_returns_content(monkeypatch):
|
|
||||||
captured = _install_fake(monkeypatch, lambda *a: _ok_response("the-content"))
|
|
||||||
out = chat(
|
|
||||||
"summarize this",
|
|
||||||
api_key="secret-key",
|
|
||||||
model="hermes-3",
|
|
||||||
base_url=BASE,
|
|
||||||
)
|
|
||||||
assert out == "the-content"
|
|
||||||
assert captured["url"] == f"{BASE}/chat/completions"
|
|
||||||
assert captured["headers"]["Authorization"] == "Bearer secret-key"
|
|
||||||
assert captured["headers"]["User-Agent"] == DEFAULT_UA
|
|
||||||
assert captured["json"]["model"] == "hermes-3"
|
|
||||||
assert captured["json"]["messages"] == [{"role": "user", "content": "summarize this"}]
|
|
||||||
assert captured["json"]["temperature"] == 0.2
|
|
||||||
assert captured["json"]["max_tokens"] == 4096
|
|
||||||
assert "response_format" not in captured["json"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_user_agent_equals_osint_user_agent_env(monkeypatch):
|
|
||||||
monkeypatch.setenv("OSINT_USER_AGENT", "custom-ua/2.0")
|
|
||||||
captured = _install_fake(monkeypatch, lambda *a: _ok_response("ok"))
|
|
||||||
chat("p", api_key="k", model="m", base_url=BASE)
|
|
||||||
assert captured["headers"]["User-Agent"] == "custom-ua/2.0"
|
|
||||||
|
|
||||||
|
|
||||||
def test_json_mode_sets_response_format(monkeypatch):
|
|
||||||
captured = _install_fake(monkeypatch, lambda *a: _ok_response("{}"))
|
|
||||||
chat("p", api_key="k", model="m", base_url=BASE, json_mode=True)
|
|
||||||
assert captured["json"]["response_format"] == {"type": "json_object"}
|
|
||||||
assert captured["json"]["max_tokens"] >= 8192
|
|
||||||
roles = [m["role"] for m in captured["json"]["messages"]]
|
|
||||||
assert "system" in roles
|
|
||||||
assert "user" in roles
|
|
||||||
|
|
||||||
|
|
||||||
def test_retries_once_when_finish_reason_is_length(monkeypatch):
|
|
||||||
calls = {"n": 0}
|
|
||||||
|
|
||||||
def post_impl(*a):
|
|
||||||
calls["n"] += 1
|
|
||||||
if calls["n"] == 1:
|
|
||||||
resp = MagicMock()
|
|
||||||
resp.status_code = 200
|
|
||||||
resp.json.return_value = {
|
|
||||||
"choices": [{
|
|
||||||
"message": {"content": "{\"summary_en\": \"cut off"},
|
|
||||||
"finish_reason": "length",
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
return resp
|
|
||||||
return _ok_response('{"summary_en": "complete brief."}')
|
|
||||||
|
|
||||||
_install_fake(monkeypatch, post_impl)
|
|
||||||
out = chat("p", api_key="k", model="m", base_url=BASE, json_mode=True)
|
|
||||||
assert calls["n"] == 2
|
|
||||||
assert "complete brief" in out
|
|
||||||
|
|
||||||
|
|
||||||
def test_401_returns_empty_string(monkeypatch):
|
|
||||||
def post_impl(*a):
|
|
||||||
resp = MagicMock()
|
|
||||||
resp.status_code = 401
|
|
||||||
return resp
|
|
||||||
|
|
||||||
_install_fake(monkeypatch, post_impl)
|
|
||||||
assert chat("p", api_key="bad", model="m", base_url=BASE) == ""
|
|
||||||
|
|
||||||
|
|
||||||
def test_5xx_returns_empty_string(monkeypatch):
|
|
||||||
def post_impl(*a):
|
|
||||||
resp = MagicMock()
|
|
||||||
resp.status_code = 503
|
|
||||||
return resp
|
|
||||||
|
|
||||||
_install_fake(monkeypatch, post_impl)
|
|
||||||
assert chat("p", api_key="k", model="m", base_url=BASE) == ""
|
|
||||||
|
|
||||||
|
|
||||||
def test_timeout_returns_empty_string(monkeypatch):
|
|
||||||
def post_impl(*a):
|
|
||||||
raise httpx.TimeoutException("timed out")
|
|
||||||
|
|
||||||
_install_fake(monkeypatch, post_impl)
|
|
||||||
assert chat("p", api_key="k", model="m", base_url=BASE) == ""
|
|
||||||
|
|
@ -1,90 +0,0 @@
|
||||||
"""Default prompts: breaking news, ignore futures/market tape."""
|
|
||||||
|
|
||||||
from summarizer import MAP_PROMPT_DEFAULT, RECAP_PROMPT_DEFAULT, SUMMARY_PROMPT_DEFAULT
|
|
||||||
|
|
||||||
|
|
||||||
def _assert_breaking_not_futures(prompt: str) -> None:
|
|
||||||
p = prompt.lower()
|
|
||||||
assert "breaking" in p
|
|
||||||
assert "futures" in p
|
|
||||||
assert "ignore" in p or "do not" in p or "not" in p
|
|
||||||
assert "es=f" not in p
|
|
||||||
assert "yfinance" not in p
|
|
||||||
|
|
||||||
|
|
||||||
def test_map_prompt_focuses_on_breaking_news_not_futures():
|
|
||||||
_assert_breaking_not_futures(MAP_PROMPT_DEFAULT)
|
|
||||||
|
|
||||||
|
|
||||||
def test_summary_prompt_focuses_on_breaking_news_not_futures():
|
|
||||||
_assert_breaking_not_futures(SUMMARY_PROMPT_DEFAULT)
|
|
||||||
p = SUMMARY_PROMPT_DEFAULT.lower()
|
|
||||||
assert "commodity" in p or "market" in p
|
|
||||||
|
|
||||||
|
|
||||||
def test_map_prompt_has_the_grading_rubric_and_score_first_block():
|
|
||||||
p = MAP_PROMPT_DEFAULT
|
|
||||||
assert "- Score: <0-100>" in p
|
|
||||||
assert "Importance: critical|high|medium|low|none" in p
|
|
||||||
for band in (
|
|
||||||
"90–100",
|
|
||||||
"70–89",
|
|
||||||
"40–69",
|
|
||||||
"10–39",
|
|
||||||
"0–9",
|
|
||||||
"event-calendar/schedule listings",
|
|
||||||
):
|
|
||||||
assert band in p
|
|
||||||
# Score must be the first line of the per-article output block.
|
|
||||||
block = p.split("Article 1:", 1)[1]
|
|
||||||
first_lines = [line.strip() for line in block.splitlines() if line.strip()]
|
|
||||||
assert first_lines[0].startswith("- Score:")
|
|
||||||
|
|
||||||
|
|
||||||
def test_reduce_prompts_do_not_demand_filler():
|
|
||||||
for prompt in (SUMMARY_PROMPT_DEFAULT, RECAP_PROMPT_DEFAULT):
|
|
||||||
p = prompt.lower()
|
|
||||||
assert "fill the brief with minor incidents" not in p
|
|
||||||
assert "fill the recap with minor incidents" not in p
|
|
||||||
assert "fill ticker with medium then low" not in p
|
|
||||||
assert "pre-filtered by score" in p
|
|
||||||
assert "never promote an item above its score" in p
|
|
||||||
assert "No significant developments in this window." in prompt
|
|
||||||
|
|
||||||
|
|
||||||
def test_summary_prompt_ranks_by_score_and_stays_complete():
|
|
||||||
p = SUMMARY_PROMPT_DEFAULT.lower()
|
|
||||||
assert "critical" in p
|
|
||||||
assert "highest-scoring" in p
|
|
||||||
assert "pre-filtered" in p
|
|
||||||
assert "complete" in p or "truncat" in p or "mid-sentence" in p
|
|
||||||
|
|
||||||
|
|
||||||
def test_summary_prompt_does_not_bail_out_with_canned_empty_brief():
|
|
||||||
p = SUMMARY_PROMPT_DEFAULT
|
|
||||||
assert "AND STOP" not in p
|
|
||||||
assert "REPEAT 3 TIMES" not in p
|
|
||||||
assert "No qualifying" not in p
|
|
||||||
assert "no-qualifying" not in p.lower()
|
|
||||||
low = p.lower()
|
|
||||||
assert "always" in low
|
|
||||||
assert "recap" in low or "summar" in low
|
|
||||||
|
|
||||||
|
|
||||||
def test_recap_prompt_does_not_bail_out_with_canned_empty_brief():
|
|
||||||
p = RECAP_PROMPT_DEFAULT
|
|
||||||
assert "AND STOP" not in p
|
|
||||||
assert "No qualifying" not in p
|
|
||||||
assert "no-qualifying" not in p.lower()
|
|
||||||
low = p.lower()
|
|
||||||
assert "always" in low
|
|
||||||
assert "daily" in low
|
|
||||||
assert "24" in low
|
|
||||||
|
|
||||||
p = RECAP_PROMPT_DEFAULT.lower()
|
|
||||||
_assert_breaking_not_futures(RECAP_PROMPT_DEFAULT)
|
|
||||||
assert "daily" in p
|
|
||||||
assert "24" in p
|
|
||||||
assert "summary_en" in p
|
|
||||||
assert "ticker" in p
|
|
||||||
assert "map_items" in p
|
|
||||||
|
|
@ -1,42 +0,0 @@
|
||||||
"""Wall-clock scheduling: 15-min analyst + 23:00 America/New_York recap."""
|
|
||||||
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
from zoneinfo import ZoneInfo
|
|
||||||
|
|
||||||
from run_news_summarizer import next_event, next_recap_datetime
|
|
||||||
|
|
||||||
TZ = ZoneInfo("America/New_York")
|
|
||||||
|
|
||||||
|
|
||||||
def test_next_recap_is_11pm_same_day_before_2300():
|
|
||||||
now = datetime(2026, 8, 28, 15, 4, tzinfo=TZ)
|
|
||||||
got = next_recap_datetime(now)
|
|
||||||
assert got == datetime(2026, 8, 28, 23, 0, tzinfo=TZ)
|
|
||||||
|
|
||||||
|
|
||||||
def test_next_recap_is_11pm_next_day_at_or_after_2300():
|
|
||||||
now = datetime(2026, 8, 28, 23, 0, tzinfo=TZ)
|
|
||||||
got = next_recap_datetime(now)
|
|
||||||
assert got == datetime(2026, 8, 29, 23, 0, tzinfo=TZ)
|
|
||||||
|
|
||||||
|
|
||||||
def test_next_recap_honors_custom_hour():
|
|
||||||
now = datetime(2026, 8, 28, 10, 0, tzinfo=TZ)
|
|
||||||
got = next_recap_datetime(now, hour=22, minute=30)
|
|
||||||
assert got == datetime(2026, 8, 28, 22, 30, tzinfo=TZ)
|
|
||||||
|
|
||||||
|
|
||||||
def test_next_event_picks_recap_when_sooner_than_interval():
|
|
||||||
now = datetime(2026, 8, 28, 22, 50, tzinfo=TZ)
|
|
||||||
last_periodic = now - timedelta(seconds=100)
|
|
||||||
when, kind = next_event(now, last_periodic=last_periodic, interval_s=900)
|
|
||||||
assert kind == "recap"
|
|
||||||
assert when == datetime(2026, 8, 28, 23, 0, tzinfo=TZ)
|
|
||||||
|
|
||||||
|
|
||||||
def test_next_event_picks_interval_when_recap_is_hours_away():
|
|
||||||
now = datetime(2026, 8, 28, 10, 0, tzinfo=TZ)
|
|
||||||
last_periodic = now
|
|
||||||
when, kind = next_event(now, last_periodic=last_periodic, interval_s=900)
|
|
||||||
assert kind == "interval"
|
|
||||||
assert when == now + timedelta(seconds=900)
|
|
||||||
|
|
@ -1,215 +0,0 @@
|
||||||
"""Summarizer window, recap flag, no futures injection, and grading env knobs."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
import summarizer
|
|
||||||
from summarizer import (
|
|
||||||
build_map_prompt,
|
|
||||||
build_master_prompt,
|
|
||||||
effective_window_minutes,
|
|
||||||
get_recent_news,
|
|
||||||
is_recap_run,
|
|
||||||
selection_config,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def test_interval_window_defaults_to_15_minutes(monkeypatch):
|
|
||||||
monkeypatch.delenv("NEWS_RECAP", raising=False)
|
|
||||||
monkeypatch.delenv("SUMMARY_WINDOW_HOURS", raising=False)
|
|
||||||
monkeypatch.setenv("SUMMARY_WINDOW_MINUTES", "15")
|
|
||||||
assert is_recap_run() is False
|
|
||||||
assert effective_window_minutes() == 15
|
|
||||||
|
|
||||||
|
|
||||||
def test_recap_window_is_24_hours(monkeypatch):
|
|
||||||
monkeypatch.setenv("NEWS_RECAP", "1")
|
|
||||||
monkeypatch.setenv("SUMMARY_WINDOW_MINUTES", "15")
|
|
||||||
assert is_recap_run() is True
|
|
||||||
assert effective_window_minutes() == 24 * 60
|
|
||||||
|
|
||||||
|
|
||||||
def test_build_map_prompt_does_not_inject_futures():
|
|
||||||
prompt = build_map_prompt(
|
|
||||||
[{"title": "Blast", "domain": "ex.com", "url": "https://ex.com/1", "content": "x" * 120}]
|
|
||||||
)
|
|
||||||
assert "FUTURES PRICES" not in prompt
|
|
||||||
assert "ES=F" not in prompt
|
|
||||||
assert "Blast" in prompt
|
|
||||||
|
|
||||||
|
|
||||||
def test_build_master_prompt_interval_uses_summary_not_recap():
|
|
||||||
prompt = build_master_prompt("partial facts", recap=False)
|
|
||||||
assert "partial facts" in prompt
|
|
||||||
assert "daily recap" not in prompt.lower()
|
|
||||||
|
|
||||||
|
|
||||||
def test_build_master_prompt_recap_uses_daily_template():
|
|
||||||
prompt = build_master_prompt("partial facts", recap=True)
|
|
||||||
assert "partial facts" in prompt
|
|
||||||
assert "daily recap" in prompt.lower()
|
|
||||||
assert "24" in prompt
|
|
||||||
|
|
||||||
|
|
||||||
# ── 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
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
[pytest]
|
|
||||||
testpaths = tests
|
|
||||||
python_files = test_*.py
|
|
||||||
|
|
@ -1,74 +0,0 @@
|
||||||
#!/usr/bin/env bash
|
|
||||||
# Recreate selected OSINT compose services WITHOUT bouncing Postgres.
|
|
||||||
#
|
|
||||||
# The old path was `compose down` + up, which stopped osint-db on every merge
|
|
||||||
# even when Dockerfile.pg did not change. Name-pinned leftovers are still
|
|
||||||
# removed, but only for the services we are actually replacing.
|
|
||||||
#
|
|
||||||
# Usage: scripts/compose-reup.sh [compose-service ...]
|
|
||||||
# (default: app ingester camera-service news-scraper news-summarizer)
|
|
||||||
# Env: COMPOSE_PROJECT_NAME (default osint-dashboard)
|
|
||||||
# COMPOSE_PROFILES (default ingest)
|
|
||||||
# FORCE_RECREATE_DB=1 also recreate db
|
|
||||||
set -euo pipefail
|
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
|
||||||
cd "$ROOT"
|
|
||||||
|
|
||||||
export COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-osint-dashboard}"
|
|
||||||
PROFILE="${COMPOSE_PROFILES:-ingest}"
|
|
||||||
|
|
||||||
DEFAULT_SVCS=(app ingester camera-service news-scraper news-summarizer)
|
|
||||||
if [ "$#" -gt 0 ]; then
|
|
||||||
SVCS=("$@")
|
|
||||||
else
|
|
||||||
SVCS=("${DEFAULT_SVCS[@]}")
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [ "${FORCE_RECREATE_DB:-0}" = "1" ]; then
|
|
||||||
SVCS+=(db)
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Never recreate db unless it was requested.
|
|
||||||
FILTERED=()
|
|
||||||
for svc in "${SVCS[@]}"; do
|
|
||||||
if [ "$svc" = "db" ] && [ "${FORCE_RECREATE_DB:-0}" != "1" ]; then
|
|
||||||
echo "compose-reup: skipping db (set FORCE_RECREATE_DB=1 to bounce Postgres)"
|
|
||||||
continue
|
|
||||||
fi
|
|
||||||
FILTERED+=("$svc")
|
|
||||||
done
|
|
||||||
SVCS=("${FILTERED[@]}")
|
|
||||||
|
|
||||||
declare -A CONTAINER_NAME=(
|
|
||||||
[app]=osint-dashboard
|
|
||||||
[ingester]=osint-ingester
|
|
||||||
[camera-service]=osint-camera-scraper
|
|
||||||
[news-scraper]=osint-news-scraper
|
|
||||||
[news-summarizer]=osint-news-summarizer
|
|
||||||
[db]=osint-db
|
|
||||||
[nats]=osint-nats
|
|
||||||
[titiler]=osint-titiler
|
|
||||||
)
|
|
||||||
|
|
||||||
echo "compose-reup: project=${COMPOSE_PROJECT_NAME} profile=${PROFILE} dir=${ROOT}"
|
|
||||||
echo "compose-reup: recreate=${SVCS[*]:-none}"
|
|
||||||
|
|
||||||
# Keep data-plane containers running (db / nats / titiler).
|
|
||||||
docker compose --profile "${PROFILE}" up -d --no-build --no-recreate db nats titiler || true
|
|
||||||
|
|
||||||
if [ "${#SVCS[@]}" -eq 0 ]; then
|
|
||||||
docker compose --profile "${PROFILE}" ps
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
for svc in "${SVCS[@]}"; do
|
|
||||||
c="${CONTAINER_NAME[$svc]:-}"
|
|
||||||
if [ -n "$c" ] && docker inspect "$c" >/dev/null 2>&1; then
|
|
||||||
echo "compose-reup: replacing ${c}"
|
|
||||||
docker rm -f "$c" >/dev/null
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
docker compose --profile "${PROFILE}" up -d --no-build --no-deps "${SVCS[@]}"
|
|
||||||
docker compose --profile "${PROFILE}" ps
|
|
||||||
|
|
@ -30,38 +30,11 @@ os.environ.setdefault("DB_NAME", "osint_data")
|
||||||
# reused across loops, so force a NullPool (new connection per session).
|
# reused across loops, so force a NullPool (new connection per session).
|
||||||
os.environ.setdefault("DB_NULL_POOL", "1")
|
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
|
import asyncpg # noqa: E402
|
||||||
|
|
||||||
pytestmark = []
|
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:
|
def _db_reachable() -> bool:
|
||||||
try:
|
try:
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
|
||||||
|
|
@ -1,62 +0,0 @@
|
||||||
"""Tests for the idle ADS-B watch sweep.
|
|
||||||
|
|
||||||
Regression: the refresh loop only persisted aircraft for *connected browser
|
|
||||||
viewports*, so ``aircraft_positions`` went silent for a day whenever nobody had
|
|
||||||
the map open (observed 2026-11-20 04:58 -> 2026-11-21). When no viewport is
|
|
||||||
registered the loop must sweep the chokepoint presets instead.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
from chokepoints import chokepoints
|
|
||||||
from live_layers import bbox_center_radius_nm, parse_bbox
|
|
||||||
from main import _adsb_watch_boxes, _adsb_refresh_loop
|
|
||||||
from ws_manager import manager
|
|
||||||
|
|
||||||
|
|
||||||
def test_watch_boxes_cover_every_chokepoint() -> None:
|
|
||||||
boxes = _adsb_watch_boxes()
|
|
||||||
assert len(boxes) == len(chokepoints())
|
|
||||||
for box in boxes:
|
|
||||||
minlon, minlat, maxlon, maxlat = box
|
|
||||||
# Preset catalog order is minlat,minlon,maxlat,maxlon: a lon/lat swap
|
|
||||||
# would put e.g. Hormuz at lat 56 lon 26.
|
|
||||||
assert -90 <= minlat < maxlat <= 90
|
|
||||||
assert -180 <= minlon < maxlon <= 180
|
|
||||||
# ADSB.lol 403s any dist > 250 nm; live_layer clamps to 150 nm.
|
|
||||||
assert bbox_center_radius_nm(minlon, minlat, maxlon, maxlat)[2] <= 150
|
|
||||||
|
|
||||||
|
|
||||||
def test_watch_box_order_matches_catalog() -> None:
|
|
||||||
hormuz = next(p for p in chokepoints() if p["id"] == "hormuz")
|
|
||||||
minlat, minlon, maxlat, maxlon = (float(v) for v in hormuz["bbox"].split(","))
|
|
||||||
assert (minlon, minlat, maxlon, maxlat) in _adsb_watch_boxes()
|
|
||||||
# parse_bbox (the app's viewport order) agrees with the converted box.
|
|
||||||
assert parse_bbox(f"{minlon},{minlat},{maxlon},{maxlat}") == (minlon, minlat, maxlon, maxlat)
|
|
||||||
|
|
||||||
|
|
||||||
def test_idle_loop_polls_watch_boxes(monkeypatch) -> None:
|
|
||||||
"""With no client viewport the loop must call fetch_aircraft(persist=True)."""
|
|
||||||
calls: list[tuple[str, bool]] = []
|
|
||||||
|
|
||||||
async def fake_fetch(bbox: str, limit: int = 2000, persist: bool = False):
|
|
||||||
calls.append((bbox, persist))
|
|
||||||
return []
|
|
||||||
|
|
||||||
monkeypatch.setattr("live_layers.fetch_aircraft", fake_fetch)
|
|
||||||
assert manager.viewports() == []
|
|
||||||
|
|
||||||
async def run() -> None:
|
|
||||||
try:
|
|
||||||
await asyncio.wait_for(_adsb_refresh_loop(), 0.5)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
asyncio.run(run())
|
|
||||||
assert calls, "idle loop persisted nothing"
|
|
||||||
assert all(persist for _, persist in calls)
|
|
||||||
assert {bbox for bbox, _ in calls} == {
|
|
||||||
f"{b[0]},{b[1]},{b[2]},{b[3]}" for b in _adsb_watch_boxes()
|
|
||||||
}
|
|
||||||
|
|
@ -1,57 +0,0 @@
|
||||||
"""Aircraft popup enrichment + emergency/MIL layer contract (static HTML)."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
|
||||||
HTML = (ROOT / "app/static/index.html").read_text()
|
|
||||||
|
|
||||||
|
|
||||||
def _fn(name: str, nxt: str) -> str:
|
|
||||||
return HTML.split(f"function {name}", 1)[1].split(f"function {nxt}", 1)[0]
|
|
||||||
|
|
||||||
|
|
||||||
def test_popup_has_required_adsb_fields_and_photo():
|
|
||||||
js = _fn("pointPopup", "loadPlanePhoto")
|
|
||||||
for field in ("callsign", "hex", "registration", "type", "alt", "gs", "squawk"):
|
|
||||||
assert f"add('{field}'" in js
|
|
||||||
assert "class=\"ps-photo\"" in js or "class='ps-photo'" in js
|
|
||||||
assert "wikipedia" not in js.lower()
|
|
||||||
assert "ceo" not in js.lower()
|
|
||||||
|
|
||||||
|
|
||||||
def test_emergency_badge_and_squawk_codes():
|
|
||||||
assert "role-badge emergency" in HTML
|
|
||||||
assert "hdg-emerg" in HTML
|
|
||||||
assert "EMERG_SQUAWK" in HTML
|
|
||||||
assert "['7700', '7600', '7500']" in HTML
|
|
||||||
emerg = HTML.split("function acIsEmergency", 1)[1].split("function acVisible", 1)[0]
|
|
||||||
assert "EMERG_SQUAWK.has(sq)" in emerg
|
|
||||||
color = HTML.split("function acColor", 1)[1].split("function connectLiveWs", 1)[0]
|
|
||||||
assert "acIsEmergency(p)" in color
|
|
||||||
assert "#ff5d5d" in color
|
|
||||||
|
|
||||||
|
|
||||||
def test_mil_toggle_hidden_until_role_flag_and_never_hits_adsb_lol():
|
|
||||||
assert 'id="lp-ac-mil-row"' in HTML
|
|
||||||
assert 'id="lp-ac-mil-on"' in HTML
|
|
||||||
row = HTML.split('id="lp-ac-mil-row"', 1)[1].split(">", 1)[0]
|
|
||||||
assert "hidden" in row
|
|
||||||
on = HTML.split('id="lp-ac-mil-on"', 1)[1].split(">", 1)[0]
|
|
||||||
assert "checked" not in on
|
|
||||||
load = HTML.split("async function loadAircraft", 1)[1].split("async function toggleTrains", 1)[0]
|
|
||||||
assert "/api/aircraft?bbox=" in load
|
|
||||||
assert "api.adsb.lol" not in load
|
|
||||||
assert "noteMilSupport" in load
|
|
||||||
assert "acMilOn" in load
|
|
||||||
note = HTML.split("function noteMilSupport", 1)[1].split("function acColor", 1)[0]
|
|
||||||
assert "extra.role" in note
|
|
||||||
assert "lp-ac-mil-row" in note
|
|
||||||
assert "hidden = false" in note
|
|
||||||
|
|
||||||
|
|
||||||
def test_planespotters_lazy_photo_still_wired():
|
|
||||||
assert "function loadPlanePhoto" in HTML
|
|
||||||
assert "/api/aircraft/photo?" in HTML
|
|
||||||
assert "map.on('popupopen', (e) => { loadPlanePhoto(e.popup); });" in HTML
|
|
||||||
|
|
@ -7,22 +7,18 @@ import httpx
|
||||||
from live_layers import overlay_catalog
|
from live_layers import overlay_catalog
|
||||||
from main import app
|
from main import app
|
||||||
|
|
||||||
from conftest import admin_cookies
|
|
||||||
|
|
||||||
BASE = "http://test"
|
BASE = "http://test"
|
||||||
|
|
||||||
|
|
||||||
async def _get(path: str) -> httpx.Response:
|
async def _get(path: str) -> httpx.Response:
|
||||||
transport = httpx.ASGITransport(app=app)
|
transport = httpx.ASGITransport(app=app)
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||||||
client.cookies.update(admin_cookies())
|
|
||||||
return await client.get(path)
|
return await client.get(path)
|
||||||
|
|
||||||
|
|
||||||
async def _post(path: str, payload: dict | None) -> httpx.Response:
|
async def _post(path: str, payload: dict | None) -> httpx.Response:
|
||||||
transport = httpx.ASGITransport(app=app)
|
transport = httpx.ASGITransport(app=app)
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||||||
client.cookies.update(admin_cookies())
|
|
||||||
return await client.post(path, json=payload)
|
return await client.post(path, json=payload)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -79,35 +75,3 @@ def test_vessels_subscribe_rejects_bad_bbox():
|
||||||
assert resp.status_code == 422, bad
|
assert resp.status_code == 422, bad
|
||||||
# Explicit null bbox is the "reset to env default" path (still 200).
|
# Explicit null bbox is the "reset to env default" path (still 200).
|
||||||
assert asyncio.run(_post("/api/vessels/subscribe", {"bbox": None})).status_code == 200
|
assert asyncio.run(_post("/api/vessels/subscribe", {"bbox": None})).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
def test_aircraft_photo_requires_hex_or_reg():
|
|
||||||
assert asyncio.run(_get("/api/aircraft/photo")).status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_aircraft_photo_rejects_bad_hex():
|
|
||||||
# hex must be exactly 6 hex chars
|
|
||||||
resp = asyncio.run(_get("/api/aircraft/photo?hex=xyz1234"))
|
|
||||||
assert resp.status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_aircraft_photo_returns_photo(monkeypatch):
|
|
||||||
async def fake(hex_code=None, reg=None):
|
|
||||||
return {"id": "1", "src": "https://t.plnspttrs.net/a_280.jpg",
|
|
||||||
"link": "https://www.planespotters.net/photo/1/x", "photographer": "A"}
|
|
||||||
|
|
||||||
monkeypatch.setattr("main.fetch_planespotters_photo", fake)
|
|
||||||
resp = asyncio.run(_get("/api/aircraft/photo?hex=e8027e"))
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert body["src"].startswith("https://t.plnspttrs.net/")
|
|
||||||
assert "max-age" in (resp.headers.get("cache-control") or "").lower()
|
|
||||||
|
|
||||||
|
|
||||||
def test_aircraft_photo_404_when_no_photo(monkeypatch):
|
|
||||||
async def fake(hex_code=None, reg=None):
|
|
||||||
return None
|
|
||||||
|
|
||||||
monkeypatch.setattr("main.fetch_planespotters_photo", fake)
|
|
||||||
resp = asyncio.run(_get("/api/aircraft/photo?reg=D-ABCD"))
|
|
||||||
assert resp.status_code == 404
|
|
||||||
|
|
|
||||||
|
|
@ -1,16 +1,16 @@
|
||||||
"""Integration tests for the news pipeline API (GET /api/news + summaries + intel).
|
"""Integration tests for the news pipeline API (GET /api/news + summaries).
|
||||||
|
|
||||||
DB-backed: marked `requires_db` and auto-skip when the test database is
|
DB-backed: marked `requires_db` and auto-skip when the test database is
|
||||||
unreachable (see tests/conftest.py). Seeding writes directly to the shared
|
unreachable (see tests/conftest.py). Seeding writes directly to the shared
|
||||||
`articles` / `article_summaries` / `news_items` tables, exactly as the scraper
|
`articles` / `article_summaries` tables, exactly as the scraper + summarizer
|
||||||
+ summarizer services would.
|
services would.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import os
|
import os
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
import asyncpg
|
import asyncpg
|
||||||
import httpx
|
import httpx
|
||||||
|
|
@ -37,9 +37,7 @@ def _truncate() -> None:
|
||||||
async def run():
|
async def run():
|
||||||
conn = await asyncpg.connect(**_conn_kwargs())
|
conn = await asyncpg.connect(**_conn_kwargs())
|
||||||
try:
|
try:
|
||||||
await conn.execute(
|
await conn.execute("TRUNCATE articles, article_summaries")
|
||||||
"TRUNCATE articles, article_summaries, news_items CASCADE"
|
|
||||||
)
|
|
||||||
finally:
|
finally:
|
||||||
await conn.close()
|
await conn.close()
|
||||||
|
|
||||||
|
|
@ -68,45 +66,14 @@ def _seed_article(title: str, url: str, domain: str, ts: str, content: str = "bo
|
||||||
asyncio.run(run())
|
asyncio.run(run())
|
||||||
|
|
||||||
|
|
||||||
def _seed_summary(text: str, ts: str, model: str | None = None, kind: str | None = None) -> int:
|
def _seed_summary(text: str, ts: str) -> None:
|
||||||
async def run() -> int:
|
|
||||||
conn = await asyncpg.connect(**_conn_kwargs())
|
|
||||||
try:
|
|
||||||
row = await conn.fetchrow(
|
|
||||||
"INSERT INTO article_summaries (summary_text, batch_timestamp, model, kind) "
|
|
||||||
"VALUES ($1, $2, $3, $4) RETURNING id",
|
|
||||||
text, datetime.fromisoformat(ts), model, kind,
|
|
||||||
)
|
|
||||||
return int(row["id"])
|
|
||||||
finally:
|
|
||||||
await conn.close()
|
|
||||||
|
|
||||||
return asyncio.run(run())
|
|
||||||
|
|
||||||
|
|
||||||
def _seed_news_item(
|
|
||||||
summary_id: int,
|
|
||||||
kind: str,
|
|
||||||
headline: str,
|
|
||||||
importance: str,
|
|
||||||
*,
|
|
||||||
location_name: str | None = None,
|
|
||||||
lat: float | None = None,
|
|
||||||
lon: float | None = None,
|
|
||||||
location_confidence: str | None = None,
|
|
||||||
category: str | None = None,
|
|
||||||
url: str | None = None,
|
|
||||||
) -> None:
|
|
||||||
async def run():
|
async def run():
|
||||||
conn = await asyncpg.connect(**_conn_kwargs())
|
conn = await asyncpg.connect(**_conn_kwargs())
|
||||||
try:
|
try:
|
||||||
await conn.execute(
|
await conn.execute(
|
||||||
"INSERT INTO news_items "
|
"INSERT INTO article_summaries (summary_text, batch_timestamp) "
|
||||||
"(summary_id, kind, headline, importance, location_name, "
|
"VALUES ($1, $2)",
|
||||||
" lat, lon, location_confidence, category, url) "
|
text, datetime.fromisoformat(ts),
|
||||||
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
|
|
||||||
summary_id, kind, headline, importance, location_name,
|
|
||||||
lat, lon, location_confidence, category, url,
|
|
||||||
)
|
)
|
||||||
finally:
|
finally:
|
||||||
await conn.close()
|
await conn.close()
|
||||||
|
|
@ -157,70 +124,6 @@ def test_api_news_since_filter(clean_news):
|
||||||
assert body[0]["title"] == "after"
|
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
|
@requires_db
|
||||||
def test_api_news_summaries_contract(clean_news):
|
def test_api_news_summaries_contract(clean_news):
|
||||||
_seed_summary("master summary markdown…", "2026-08-24T18:05:00+00:00")
|
_seed_summary("master summary markdown…", "2026-08-24T18:05:00+00:00")
|
||||||
|
|
@ -228,101 +131,12 @@ def test_api_news_summaries_contract(clean_news):
|
||||||
assert isinstance(body, list)
|
assert isinstance(body, list)
|
||||||
assert len(body) == 1
|
assert len(body) == 1
|
||||||
s = body[0]
|
s = body[0]
|
||||||
assert set(s.keys()) == {"id", "summary_text", "batch_timestamp", "model", "kind"}
|
assert set(s.keys()) == {"id", "summary_text", "batch_timestamp"}
|
||||||
assert s["summary_text"] == "master summary markdown…"
|
assert s["summary_text"] == "master summary markdown…"
|
||||||
assert s["batch_timestamp"].startswith("2026-08-24T18:05")
|
assert s["batch_timestamp"].startswith("2026-08-24T18:05")
|
||||||
assert s["kind"] is None
|
|
||||||
|
|
||||||
|
|
||||||
@requires_db
|
|
||||||
def test_api_news_summaries_kind_filter(clean_news):
|
|
||||||
_seed_summary("interval brief", "2026-08-28T22:05:00+00:00", kind="interval")
|
|
||||||
_seed_summary("daily recap", "2026-08-28T03:00:00+00:00", kind="daily_recap")
|
|
||||||
recap = _get("/api/news/summaries?kind=daily_recap").json()
|
|
||||||
assert len(recap) == 1
|
|
||||||
assert recap[0]["summary_text"] == "daily recap"
|
|
||||||
assert recap[0]["kind"] == "daily_recap"
|
|
||||||
assert _get("/api/news/summaries?kind=nope").status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
@requires_db
|
@requires_db
|
||||||
def test_api_news_empty(clean_news):
|
def test_api_news_empty(clean_news):
|
||||||
assert _get("/api/news").json() == []
|
assert _get("/api/news").json() == []
|
||||||
assert _get("/api/news/summaries").json() == []
|
assert _get("/api/news/summaries").json() == []
|
||||||
assert _get("/api/news/ticker").json() == []
|
|
||||||
assert _get("/api/news/map").json() == []
|
|
||||||
|
|
||||||
|
|
||||||
TICKER_KEYS = {"id", "headline", "importance", "location_name", "url", "created_at"}
|
|
||||||
MAP_KEYS = {
|
|
||||||
"id", "headline", "importance", "location_name", "lat", "lon",
|
|
||||||
"location_confidence", "category", "url", "created_at",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _seed_flagged_items() -> None:
|
|
||||||
sid = _seed_summary("batch brief", "2026-08-27T18:05:00+00:00", "Hermes-4.3-36B")
|
|
||||||
_seed_news_item(
|
|
||||||
sid, "ticker", "Critical ticker", "critical",
|
|
||||||
location_name="Kyiv", url="https://example.com/ticker",
|
|
||||||
)
|
|
||||||
_seed_news_item(
|
|
||||||
sid, "ticker", "Low ticker", "low",
|
|
||||||
location_name="Somewhere", url="https://example.com/low",
|
|
||||||
)
|
|
||||||
_seed_news_item(
|
|
||||||
sid, "map", "Critical map", "critical",
|
|
||||||
location_name="Taipei", lat=25.03, lon=121.56,
|
|
||||||
location_confidence="high", category="conflict",
|
|
||||||
url="https://example.com/map",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@requires_db
|
|
||||||
def test_api_news_ticker_returns_only_flagged(clean_news):
|
|
||||||
_seed_flagged_items()
|
|
||||||
resp = _get("/api/news/ticker")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert isinstance(body, list)
|
|
||||||
assert len(body) == 1
|
|
||||||
item = body[0]
|
|
||||||
assert set(item.keys()) == TICKER_KEYS
|
|
||||||
assert item["headline"] == "Critical ticker"
|
|
||||||
assert item["importance"] == "critical"
|
|
||||||
assert item["location_name"] == "Kyiv"
|
|
||||||
assert item["url"] == "https://example.com/ticker"
|
|
||||||
|
|
||||||
|
|
||||||
@requires_db
|
|
||||||
def test_api_news_ticker_falls_back_to_lesser_when_nothing_flagged(clean_news):
|
|
||||||
sid = _seed_summary("quiet brief", "2026-08-27T18:05:00+00:00", "Hermes-4.3-36B")
|
|
||||||
_seed_news_item(
|
|
||||||
sid, "ticker", "Shop theft downtown", "low",
|
|
||||||
location_name="Raleigh", url="https://example.com/theft",
|
|
||||||
)
|
|
||||||
resp = _get("/api/news/ticker")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert len(body) == 1
|
|
||||||
assert body[0]["headline"] == "Shop theft downtown"
|
|
||||||
assert body[0]["importance"] == "low"
|
|
||||||
|
|
||||||
|
|
||||||
@requires_db
|
|
||||||
def test_api_news_map_returns_only_flagged_with_coords(clean_news):
|
|
||||||
_seed_flagged_items()
|
|
||||||
resp = _get("/api/news/map")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert isinstance(body, list)
|
|
||||||
assert len(body) == 1
|
|
||||||
item = body[0]
|
|
||||||
assert set(item.keys()) == MAP_KEYS
|
|
||||||
assert item["headline"] == "Critical map"
|
|
||||||
assert item["importance"] == "critical"
|
|
||||||
assert item["lat"] == 25.03
|
|
||||||
assert item["lon"] == 121.56
|
|
||||||
assert item["location_confidence"] == "high"
|
|
||||||
assert item["category"] == "conflict"
|
|
||||||
assert _get("/api/news/map?bbox=1,2,3").status_code == 422
|
|
||||||
|
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
@ -1,127 +0,0 @@
|
||||||
"""GET /api/place — Nominatim reverse proxy (60s cache, 500 keys, 1 req/s)."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from main import app
|
|
||||||
from place import cache_key, place_cache, slim_place
|
|
||||||
|
|
||||||
BASE = "http://test"
|
|
||||||
|
|
||||||
SAMPLE = {
|
|
||||||
"display_name": "Raleigh, Wake County, North Carolina, United States",
|
|
||||||
"name": "Raleigh",
|
|
||||||
"osm_type": "relation",
|
|
||||||
"osm_id": 123,
|
|
||||||
"address": {
|
|
||||||
"city": "Raleigh",
|
|
||||||
"state": "North Carolina",
|
|
||||||
"country": "United States",
|
|
||||||
"country_code": "us",
|
|
||||||
"tourism": "ignore-me",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class _FakeResp:
|
|
||||||
def __init__(self, payload, status=200):
|
|
||||||
self._payload = payload
|
|
||||||
self.status_code = status
|
|
||||||
|
|
||||||
def raise_for_status(self):
|
|
||||||
if self.status_code >= 400:
|
|
||||||
req = httpx.Request("GET", "https://nominatim.openstreetmap.org/reverse")
|
|
||||||
raise httpx.HTTPStatusError(
|
|
||||||
"upstream", request=req,
|
|
||||||
response=httpx.Response(self.status_code, request=req),
|
|
||||||
)
|
|
||||||
|
|
||||||
def json(self):
|
|
||||||
return self._payload
|
|
||||||
|
|
||||||
|
|
||||||
class _FakeNominatim:
|
|
||||||
calls: list[dict] = []
|
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def __aenter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
async def __aexit__(self, *args):
|
|
||||||
return False
|
|
||||||
|
|
||||||
async def get(self, url, params=None, headers=None):
|
|
||||||
_FakeNominatim.calls.append({"url": url, "params": params, "headers": headers})
|
|
||||||
return _FakeResp(SAMPLE)
|
|
||||||
|
|
||||||
|
|
||||||
def _nominatim_client(**kwargs):
|
|
||||||
return _FakeNominatim()
|
|
||||||
|
|
||||||
|
|
||||||
async def _get(path: str) -> httpx.Response:
|
|
||||||
transport = httpx.ASGITransport(app=app)
|
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
|
||||||
return await client.get(path)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def _reset_place(monkeypatch):
|
|
||||||
place_cache.clear()
|
|
||||||
_FakeNominatim.calls = []
|
|
||||||
monkeypatch.setattr("place._http_client", _nominatim_client)
|
|
||||||
monkeypatch.setattr("place.NOMINATIM_MIN_INTERVAL", 0.0)
|
|
||||||
monkeypatch.setattr("place._last_req", 0.0)
|
|
||||||
yield
|
|
||||||
place_cache.clear()
|
|
||||||
|
|
||||||
|
|
||||||
def test_slim_place_keeps_address_subset():
|
|
||||||
body = slim_place(35.78, -78.64, SAMPLE)
|
|
||||||
assert body["display_name"].startswith("Raleigh")
|
|
||||||
assert body["name"] == "Raleigh"
|
|
||||||
assert body["address"]["city"] == "Raleigh"
|
|
||||||
assert "tourism" not in body["address"]
|
|
||||||
assert body["attribution"].startswith("© OpenStreetMap")
|
|
||||||
|
|
||||||
|
|
||||||
def test_cache_key_quantizes_to_4_decimals():
|
|
||||||
assert cache_key(35.77961, -78.63821) == cache_key(35.77964, -78.63819)
|
|
||||||
|
|
||||||
|
|
||||||
def test_place_requires_lat_lon():
|
|
||||||
resp = asyncio.run(_get("/api/place"))
|
|
||||||
assert resp.status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_place_rejects_out_of_range():
|
|
||||||
assert asyncio.run(_get("/api/place?lat=99&lon=0")).status_code == 422
|
|
||||||
assert asyncio.run(_get("/api/place?lat=0&lon=200")).status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_place_reverse_and_cache():
|
|
||||||
r1 = asyncio.run(_get("/api/place?lat=35.7796&lon=-78.6382"))
|
|
||||||
assert r1.status_code == 200
|
|
||||||
body = r1.json()
|
|
||||||
assert body["display_name"].startswith("Raleigh")
|
|
||||||
assert body["lat"] == pytest.approx(35.7796, abs=0.001)
|
|
||||||
assert "max-age=60" in (r1.headers.get("cache-control") or "").lower()
|
|
||||||
assert len(_FakeNominatim.calls) == 1
|
|
||||||
ua = _FakeNominatim.calls[0]["headers"]["User-Agent"]
|
|
||||||
assert "osint-dashboard" in ua.lower() or "@" in ua
|
|
||||||
r2 = asyncio.run(_get("/api/place?lat=35.77961&lon=-78.63821"))
|
|
||||||
assert r2.status_code == 200
|
|
||||||
assert len(_FakeNominatim.calls) == 1 # cache hit, same 4-decimal key
|
|
||||||
|
|
||||||
|
|
||||||
def test_place_cache_cap_500():
|
|
||||||
from cachetools import TTLCache
|
|
||||||
assert isinstance(place_cache, TTLCache)
|
|
||||||
assert place_cache.maxsize == 500
|
|
||||||
assert place_cache.ttl == 60
|
|
||||||
|
|
@ -1,173 +0,0 @@
|
||||||
"""API tests for GET/PUT /api/settings and GET /api/news/models."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import os
|
|
||||||
|
|
||||||
import asyncpg
|
|
||||||
import httpx
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from conftest import admin_cookies, requires_db
|
|
||||||
|
|
||||||
from main import app
|
|
||||||
|
|
||||||
BASE = "http://test"
|
|
||||||
|
|
||||||
|
|
||||||
def _conn_kwargs() -> dict:
|
|
||||||
return {
|
|
||||||
"host": os.environ["DB_HOST"],
|
|
||||||
"port": int(os.environ["DB_PORT"]),
|
|
||||||
"user": os.environ["DB_USER"],
|
|
||||||
"password": os.environ["DB_PASSWORD"],
|
|
||||||
"database": os.environ["DB_NAME"],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _truncate_settings() -> None:
|
|
||||||
async def run():
|
|
||||||
conn = await asyncpg.connect(**_conn_kwargs())
|
|
||||||
try:
|
|
||||||
await conn.execute("DROP TABLE IF EXISTS app_settings")
|
|
||||||
finally:
|
|
||||||
await conn.close()
|
|
||||||
|
|
||||||
asyncio.run(run())
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
|
||||||
def clean_settings():
|
|
||||||
import settings_store
|
|
||||||
settings_store._ensured = False
|
|
||||||
_truncate_settings()
|
|
||||||
yield
|
|
||||||
settings_store._ensured = False
|
|
||||||
_truncate_settings()
|
|
||||||
|
|
||||||
|
|
||||||
def _request(method: str, path: str, json: dict | None = None) -> httpx.Response:
|
|
||||||
async def _run() -> httpx.Response:
|
|
||||||
transport = httpx.ASGITransport(app=app)
|
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
|
||||||
client.cookies.update(admin_cookies())
|
|
||||||
return await client.request(method, path, json=json)
|
|
||||||
|
|
||||||
return asyncio.run(_run())
|
|
||||||
|
|
||||||
|
|
||||||
def _get(path: str) -> httpx.Response:
|
|
||||||
return _request("GET", path)
|
|
||||||
|
|
||||||
|
|
||||||
def _put(path: str, json: dict) -> httpx.Response:
|
|
||||||
return _request("PUT", path, json=json)
|
|
||||||
|
|
||||||
|
|
||||||
def test_get_news_models_without_key_returns_fallback(monkeypatch):
|
|
||||||
monkeypatch.delenv("NOUS_API_KEY", raising=False)
|
|
||||||
monkeypatch.setattr("keystore.get_api_key", _missing_key)
|
|
||||||
|
|
||||||
resp = _get("/api/news/models")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert body["source"] == "fallback"
|
|
||||||
ids = [m["id"] for m in body["models"]]
|
|
||||||
assert "Hermes-4.3-36B" in ids
|
|
||||||
from settings_store import FALLBACK_MODELS
|
|
||||||
assert ids == FALLBACK_MODELS
|
|
||||||
|
|
||||||
|
|
||||||
async def _missing_key(name: str):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
async def _present_key(name: str):
|
|
||||||
return "test-nous-api-key-1234"
|
|
||||||
|
|
||||||
|
|
||||||
def test_get_news_models_live_from_upstream(monkeypatch):
|
|
||||||
monkeypatch.setattr("keystore.get_api_key", _present_key)
|
|
||||||
monkeypatch.setenv("NOUS_BASE_URL", "https://inference-api.nousresearch.com/v1")
|
|
||||||
monkeypatch.delenv("OSINT_USER_AGENT", raising=False)
|
|
||||||
|
|
||||||
captured: dict = {}
|
|
||||||
|
|
||||||
class FakeResponse:
|
|
||||||
status_code = 200
|
|
||||||
|
|
||||||
def raise_for_status(self):
|
|
||||||
return None
|
|
||||||
|
|
||||||
def json(self):
|
|
||||||
return {"data": [{"id": "live-model-a"}, {"id": "Hermes-4.3-36B"}]}
|
|
||||||
|
|
||||||
async def fake_http_get(url, *, headers, timeout):
|
|
||||||
captured["url"] = url
|
|
||||||
captured["headers"] = headers
|
|
||||||
captured["timeout"] = timeout
|
|
||||||
return FakeResponse()
|
|
||||||
|
|
||||||
import settings_store
|
|
||||||
monkeypatch.setattr(settings_store, "_http_get", fake_http_get)
|
|
||||||
settings_store._models_cache = None
|
|
||||||
|
|
||||||
resp = _get("/api/news/models")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert body["source"] == "live"
|
|
||||||
ids = [m["id"] for m in body["models"]]
|
|
||||||
assert ids == ["live-model-a", "Hermes-4.3-36B"]
|
|
||||||
assert captured["url"] == "https://inference-api.nousresearch.com/v1/models"
|
|
||||||
assert captured["headers"]["User-Agent"] == "osint-dashboard-news-summarizer"
|
|
||||||
assert captured["headers"]["Authorization"] == "Bearer test-nous-api-key-1234"
|
|
||||||
timeout = captured["timeout"]
|
|
||||||
assert timeout == 8 or getattr(timeout, "read", timeout) == 8 or float(timeout) == 8.0
|
|
||||||
|
|
||||||
|
|
||||||
def test_get_news_models_upstream_failure_returns_fallback(monkeypatch):
|
|
||||||
monkeypatch.setattr("keystore.get_api_key", _present_key)
|
|
||||||
|
|
||||||
async def boom_http_get(url, *, headers, timeout):
|
|
||||||
raise httpx.ConnectError("upstream down")
|
|
||||||
|
|
||||||
import settings_store
|
|
||||||
monkeypatch.setattr(settings_store, "_http_get", boom_http_get)
|
|
||||||
settings_store._models_cache = None
|
|
||||||
|
|
||||||
resp = _get("/api/news/models")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert body["source"] == "fallback"
|
|
||||||
ids = [m["id"] for m in body["models"]]
|
|
||||||
assert "Hermes-4.3-36B" in ids
|
|
||||||
|
|
||||||
|
|
||||||
def test_put_settings_empty_returns_422():
|
|
||||||
resp = _put("/api/settings", {"summary_model": ""})
|
|
||||||
assert resp.status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_put_settings_whitespace_only_returns_422():
|
|
||||||
resp = _put("/api/settings", {"summary_model": " "})
|
|
||||||
assert resp.status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
@requires_db
|
|
||||||
def test_put_settings_round_trip(clean_settings, monkeypatch):
|
|
||||||
monkeypatch.delenv("SUMMARY_MODEL", raising=False)
|
|
||||||
monkeypatch.delenv("NOUS_BASE_URL", raising=False)
|
|
||||||
|
|
||||||
put_resp = _put("/api/settings", {"summary_model": "google/gemini-2.5-flash"})
|
|
||||||
assert put_resp.status_code == 200
|
|
||||||
put_body = put_resp.json()
|
|
||||||
assert put_body["summary_model"] == "google/gemini-2.5-flash"
|
|
||||||
assert put_body["nous_base_url"] == "https://inference-api.nousresearch.com/v1"
|
|
||||||
|
|
||||||
get_resp = _get("/api/settings")
|
|
||||||
assert get_resp.status_code == 200
|
|
||||||
get_body = get_resp.json()
|
|
||||||
assert get_body["summary_model"] == "google/gemini-2.5-flash"
|
|
||||||
assert get_body["nous_base_url"] == "https://inference-api.nousresearch.com/v1"
|
|
||||||
assert set(get_body.keys()) == {"summary_model", "nous_base_url"}
|
|
||||||
|
|
@ -1,163 +0,0 @@
|
||||||
"""GET /api/stats HUD counter contract (counts only, small, never 500)."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import re
|
|
||||||
from datetime import timezone
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
from main import app, _stats_counts, _stats_cache
|
|
||||||
|
|
||||||
BASE = "http://test"
|
|
||||||
|
|
||||||
EXPECTED_KEYS = ("aircraft", "vessels", "trains", "cameras",
|
|
||||||
"fires", "quakes", "alerts", "timestamp")
|
|
||||||
|
|
||||||
|
|
||||||
async def _get(path: str) -> httpx.Response:
|
|
||||||
transport = httpx.ASGITransport(app=app)
|
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
|
||||||
return await client.get(path)
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_200_all_keys_present():
|
|
||||||
resp = asyncio.run(_get("/api/stats"))
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
for key in EXPECTED_KEYS:
|
|
||||||
assert key in body, f"missing key {key}"
|
|
||||||
assert "max-age" in (resp.headers.get("cache-control") or "").lower()
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_counters_are_ints():
|
|
||||||
body = asyncio.run(_get("/api/stats")).json()
|
|
||||||
for key in EXPECTED_KEYS:
|
|
||||||
if key == "timestamp":
|
|
||||||
continue
|
|
||||||
assert isinstance(body[key], int), f"{key} is not an int: {body[key]!r}"
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_timestamp_is_iso8601_z():
|
|
||||||
body = asyncio.run(_get("/api/stats")).json()
|
|
||||||
ts = body["timestamp"]
|
|
||||||
# ISO8601 with a trailing Z (we normalize +00:00 -> Z).
|
|
||||||
assert isinstance(ts, str) and ts.endswith("Z")
|
|
||||||
assert re.match(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}", ts)
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_payload_is_tiny():
|
|
||||||
resp = asyncio.run(_get("/api/stats"))
|
|
||||||
assert len(resp.content) < 2048, "stats payload must be counts-only, not GeoJSON"
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_counts_reflect_last_known(monkeypatch):
|
|
||||||
"""aircraft/vessels/trains/alerts come from in-memory last-known state."""
|
|
||||||
import live_layers
|
|
||||||
|
|
||||||
monkeypatch.setattr(live_layers, "aircraft_last_known", {str(i): {} for i in range(7)})
|
|
||||||
monkeypatch.setattr(live_layers, "vessel_last_known", {str(i): {} for i in range(3)})
|
|
||||||
monkeypatch.setattr(live_layers, "train_count", 11)
|
|
||||||
monkeypatch.setattr(live_layers, "nws_alert_count", 5)
|
|
||||||
|
|
||||||
# _stats_counts imports the dicts/counters inside the function from live_layers,
|
|
||||||
# so monkeypatching the module attributes is what it observes.
|
|
||||||
from main import _stats_counts as fn
|
|
||||||
|
|
||||||
body = asyncio.run(fn())
|
|
||||||
assert body["aircraft"] == 7
|
|
||||||
assert body["vessels"] == 3
|
|
||||||
assert body["trains"] == 11
|
|
||||||
assert body["alerts"] == 5
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_db_failure_degrades_to_zero(monkeypatch):
|
|
||||||
"""A down DB yields zeros for the SQL-backed counters, never a 500."""
|
|
||||||
# Make the session factory raise synchronously so the try/except in
|
|
||||||
# _stats_counts degrades the SQL counters to zero (no dangling coroutine).
|
|
||||||
def _raise(*args, **kwargs):
|
|
||||||
raise RuntimeError("db down")
|
|
||||||
|
|
||||||
monkeypatch.setattr("main.async_session", _raise)
|
|
||||||
body = asyncio.run(_stats_counts())
|
|
||||||
assert body["cameras"] == 0
|
|
||||||
assert body["fires"] == 0
|
|
||||||
assert body["quakes"] == 0
|
|
||||||
assert isinstance(body["timestamp"], str)
|
|
||||||
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
@ -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")
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""ffmpeg snapshots stay off the request path (asyncio.create_task)."""
|
"""masscan/ffmpeg stay off the request path (asyncio.create_task)."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
@ -7,27 +7,36 @@ import asyncio
|
||||||
import bg_jobs
|
import bg_jobs
|
||||||
|
|
||||||
|
|
||||||
def test_bg_jobs_has_no_pps_cap():
|
def test_schedule_masscan_pass_returns_without_awaiting_scan(monkeypatch):
|
||||||
assert not any(name.endswith("_PPS_CAP") for name in dir(bg_jobs))
|
started = {"n": 0}
|
||||||
|
|
||||||
|
async def slow_pass():
|
||||||
|
started["n"] += 1
|
||||||
|
await asyncio.sleep(30)
|
||||||
|
|
||||||
|
monkeypatch.setattr(bg_jobs, "_run_masscan_capped", slow_pass)
|
||||||
|
bg_jobs._masscan_task = None
|
||||||
|
|
||||||
|
async def run():
|
||||||
|
launched = bg_jobs.schedule_masscan_pass()
|
||||||
|
assert launched is True
|
||||||
|
# Must not have blocked for the 30s pass.
|
||||||
|
assert bg_jobs._masscan_task is not None
|
||||||
|
assert not bg_jobs._masscan_task.done()
|
||||||
|
launched2 = bg_jobs.schedule_masscan_pass()
|
||||||
|
assert launched2 is False # already running
|
||||||
|
bg_jobs._masscan_task.cancel()
|
||||||
|
try:
|
||||||
|
await bg_jobs._masscan_task
|
||||||
|
except (asyncio.CancelledError, Exception):
|
||||||
|
pass
|
||||||
|
bg_jobs._masscan_task = None
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
|
||||||
|
|
||||||
def test_camera_preview_has_no_public_feed_probe():
|
def test_masscan_rate_cap_is_200():
|
||||||
import camera_preview
|
assert bg_jobs.MASSCAN_PPS_CAP == 200
|
||||||
|
|
||||||
assert not hasattr(camera_preview, "probe_public_feed")
|
|
||||||
assert not hasattr(camera_preview, "_http_feed_url")
|
|
||||||
|
|
||||||
|
|
||||||
def test_ingest_routes_exclude_active_discovery():
|
|
||||||
from main import app
|
|
||||||
|
|
||||||
ingest = [
|
|
||||||
getattr(r, "path", "")
|
|
||||||
for r in app.routes
|
|
||||||
if getattr(r, "path", "").startswith("/api/ingest/")
|
|
||||||
]
|
|
||||||
assert "/api/ingest/fires" in ingest
|
|
||||||
assert all("scan" not in path for path in ingest)
|
|
||||||
|
|
||||||
|
|
||||||
def test_schedule_ffmpeg_snapshot_is_a_task_not_inline(monkeypatch):
|
def test_schedule_ffmpeg_snapshot_is_a_task_not_inline(monkeypatch):
|
||||||
|
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
"""Timeline bucket_hours + static Cache-Control."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
|
||||||
|
|
||||||
|
|
||||||
def test_timeline_uses_bucket_hours():
|
|
||||||
src = (ROOT / "app/main.py").read_text()
|
|
||||||
fn = src.split("async def get_timeline")[1].split("async def sentiment_by_source")[0]
|
|
||||||
assert "bucket_hours" in fn
|
|
||||||
assert "date_trunc('hour'" not in fn or "bucket" in fn.lower()
|
|
||||||
# Must not ignore the query param.
|
|
||||||
assert ":bucket" in fn or "bucket_hours" in fn.split("text(")[1][:800]
|
|
||||||
|
|
||||||
|
|
||||||
def test_static_vendor_cache_control():
|
|
||||||
src = (ROOT / "app/main.py").read_text()
|
|
||||||
assert "max-age=31536000" in src or "immutable" in src.lower()
|
|
||||||
|
|
@ -1,15 +0,0 @@
|
||||||
"""Camera list is slim (no URLs). Popup must fetch GET /api/cameras/{id}."""
|
|
||||||
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
HTML = Path(__file__).resolve().parents[1] / "app/static/index.html"
|
|
||||||
|
|
||||||
|
|
||||||
def test_popupopen_fetches_camera_detail_row():
|
|
||||||
html = HTML.read_text()
|
|
||||||
start = html.index("map.on('popupopen'")
|
|
||||||
end = html.index("map.on('popupclose'")
|
|
||||||
block = html[start:end]
|
|
||||||
assert "fetch(" in block
|
|
||||||
assert "/api/cameras/" in block
|
|
||||||
assert "camPopupHtml(" in block
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
@ -1,122 +0,0 @@
|
||||||
"""Tests for the chokepoint preset catalog + vessels ``src=`` filter.
|
|
||||||
|
|
||||||
- Span: every catalog box passes VesselAPI's ``|dLat|+|dLon| <= 4`` validator.
|
|
||||||
- Catalog: ``GET /api/map/chokepoints`` returns 200 with the documented shape.
|
|
||||||
- Vessels filter: ``GET /api/vessels?src=`` narrows the union store by provider.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
from chokepoints import chokepoints
|
|
||||||
from live_layers import fetch_vessels, vessel_last_known
|
|
||||||
from main import app
|
|
||||||
from vesselapi import validate_bbox_span
|
|
||||||
|
|
||||||
BASE = "http://test"
|
|
||||||
|
|
||||||
|
|
||||||
async def _get(path: str) -> httpx.Response:
|
|
||||||
transport = httpx.ASGITransport(app=app)
|
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
|
||||||
return await client.get(path)
|
|
||||||
|
|
||||||
|
|
||||||
# ── Span validation (VesselAPI rule) ──────────────────────────────────────
|
|
||||||
|
|
||||||
def test_all_catalog_boxes_within_span() -> None:
|
|
||||||
for preset in chokepoints():
|
|
||||||
minlat, minlon, maxlat, maxlon = (float(p) for p in preset["bbox"].split(","))
|
|
||||||
dlat = abs(maxlat - minlat)
|
|
||||||
dlon = abs(maxlon - minlon)
|
|
||||||
assert dlat + dlon <= 4.0, preset["id"]
|
|
||||||
validate_bbox_span(minlat, minlon, maxlat, maxlon) # no raise
|
|
||||||
|
|
||||||
|
|
||||||
# ── Catalog API contract ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def test_chokepoints_catalog_shape() -> None:
|
|
||||||
resp = asyncio.run(_get("/api/map/chokepoints"))
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert set(body) == {"chokepoints"}
|
|
||||||
rows = body["chokepoints"]
|
|
||||||
assert [r["id"] for r in rows] == [
|
|
||||||
"hormuz", "bab_el_mandeb", "suez", "malacca", "taiwan",
|
|
||||||
]
|
|
||||||
for r in rows:
|
|
||||||
assert set(r) == {"id", "title", "bbox", "center", "zoom", "vesselapi"}
|
|
||||||
assert isinstance(r["center"], list) and len(r["center"]) == 2
|
|
||||||
assert r["zoom"] == 9
|
|
||||||
assert isinstance(r["vesselapi"], bool)
|
|
||||||
# bbox is minlat,minlon,maxlat,maxlon
|
|
||||||
minlat, minlon, maxlat, maxlon = (float(p) for p in r["bbox"].split(","))
|
|
||||||
assert minlat < maxlat and minlon < maxlon
|
|
||||||
|
|
||||||
|
|
||||||
def test_only_hormuz_is_vesselapi() -> None:
|
|
||||||
rows = chokepoints()
|
|
||||||
by_id = {r["id"]: r for r in rows}
|
|
||||||
assert by_id["hormuz"]["vesselapi"] is True
|
|
||||||
for cid in ("bab_el_mandeb", "suez", "malacca", "taiwan"):
|
|
||||||
assert by_id[cid]["vesselapi"] is False
|
|
||||||
|
|
||||||
|
|
||||||
# ── Vessels src= filter (mocked store) ────────────────────────────────────
|
|
||||||
|
|
||||||
def _seed_store() -> None:
|
|
||||||
vessel_last_known.clear()
|
|
||||||
vessel_last_known["422050100"] = {
|
|
||||||
"id": "422050100", "lat": 26.5, "lon": 56.3, "label": "HORMUZ STAR",
|
|
||||||
"extra": {"src": "vesselapi", "mmsi": "422050100"},
|
|
||||||
}
|
|
||||||
vessel_last_known["366001230"] = {
|
|
||||||
"id": "366001230", "lat": 35.0, "lon": -79.0, "label": "CONUS SHIP",
|
|
||||||
"extra": {"src": "aisstream", "mmsi": "366001230"},
|
|
||||||
}
|
|
||||||
vessel_last_known["366001231"] = {
|
|
||||||
"id": "366001231", "lat": 36.0, "lon": -78.0, "label": "CONUS SHIP 2",
|
|
||||||
"extra": {"src": "aisstream", "mmsi": "366001231"},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_fetch_vessels_src_filters() -> None:
|
|
||||||
_seed_store()
|
|
||||||
assert {v["id"] for v in asyncio.run(fetch_vessels(None, src="vesselapi"))} == {"422050100"}
|
|
||||||
assert {v["id"] for v in asyncio.run(fetch_vessels(None, src="aisstream"))} == {
|
|
||||||
"366001230", "366001231",
|
|
||||||
}
|
|
||||||
assert len(asyncio.run(fetch_vessels(None, src="all"))) == 3
|
|
||||||
assert len(asyncio.run(fetch_vessels(None))) == 3 # default all
|
|
||||||
|
|
||||||
|
|
||||||
def test_vessels_src_query_param(monkeypatch) -> None:
|
|
||||||
_seed_store()
|
|
||||||
|
|
||||||
async def _fake_fetch(bbox, limit, src=None):
|
|
||||||
rows = [
|
|
||||||
{"id": k, **{kk: v[kk] for kk in ("lat", "lon", "label", "extra")}}
|
|
||||||
for k, v in vessel_last_known.items()
|
|
||||||
]
|
|
||||||
if src and src != "all":
|
|
||||||
rows = [r for r in rows if (r.get("extra") or {}).get("src") == src]
|
|
||||||
return rows
|
|
||||||
|
|
||||||
monkeypatch.setattr("main.fetch_vessels", _fake_fetch)
|
|
||||||
|
|
||||||
body = asyncio.run(_get("/api/vessels?src=vesselapi")).json()
|
|
||||||
assert [r["id"] for r in body] == ["422050100"]
|
|
||||||
|
|
||||||
body = asyncio.run(_get("/api/vessels?src=aisstream")).json()
|
|
||||||
assert {r["id"] for r in body} == {"366001230", "366001231"}
|
|
||||||
|
|
||||||
body = asyncio.run(_get("/api/vessels?src=all")).json()
|
|
||||||
assert len(body) == 3
|
|
||||||
|
|
||||||
|
|
||||||
def test_vessels_src_rejects_bad_value() -> None:
|
|
||||||
resp = asyncio.run(_get("/api/vessels?src=marine-traffic"))
|
|
||||||
assert resp.status_code == 422
|
|
||||||
|
|
@ -1,132 +0,0 @@
|
||||||
"""GET /api/conflicts — curated conflict-zone catalog + event-count roll-up.
|
|
||||||
|
|
||||||
No outbound HTTP: event counts come from geocoded rows already (or not) in the
|
|
||||||
DB, and the API tests monkeypatch ``main._fetch_geocoded_points`` so no database
|
|
||||||
is required for the contract checks.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
from conflicts import SEVERITIES, conflict_zones, zone_event_stats
|
|
||||||
from live_layers import overlay_catalog
|
|
||||||
from main import app
|
|
||||||
|
|
||||||
BASE = "http://test"
|
|
||||||
|
|
||||||
|
|
||||||
def _get(path: str, monkeypatch=None, points=None) -> httpx.Response:
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
async def run() -> httpx.Response:
|
|
||||||
if monkeypatch is not None:
|
|
||||||
async def fake():
|
|
||||||
return points or []
|
|
||||||
|
|
||||||
monkeypatch.setattr("main._fetch_geocoded_points", fake)
|
|
||||||
transport = httpx.ASGITransport(app=app)
|
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
|
||||||
return await client.get(path)
|
|
||||||
|
|
||||||
return asyncio.run(run())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Catalog shape ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
|
|
||||||
def test_catalog_length():
|
|
||||||
zones = conflict_zones()
|
|
||||||
assert len(zones) == 13
|
|
||||||
|
|
||||||
|
|
||||||
def test_catalog_severity_enum():
|
|
||||||
zones = conflict_zones()
|
|
||||||
sevs = {z["severity"] for z in zones}
|
|
||||||
assert sevs.issubset(SEVERITIES)
|
|
||||||
# All three tiers are represented.
|
|
||||||
assert sevs == SEVERITIES
|
|
||||||
|
|
||||||
|
|
||||||
def test_catalog_fields_factual_and_complete():
|
|
||||||
zones = conflict_zones()
|
|
||||||
ids = [z["id"] for z in zones]
|
|
||||||
assert len(set(ids)) == len(ids) # unique ids
|
|
||||||
for z in zones:
|
|
||||||
assert z["label"]
|
|
||||||
assert z["description"].strip()
|
|
||||||
assert -90.0 <= z["lat"] <= 90.0
|
|
||||||
assert -180.0 <= z["lon"] <= 180.0
|
|
||||||
# internal-only bbox is well-formed: (min_lat, min_lon, max_lat, max_lon)
|
|
||||||
min_lat, min_lon, max_lat, max_lon = z["bbox"]
|
|
||||||
assert min_lat <= max_lat and min_lon <= max_lon
|
|
||||||
assert min_lat <= z["lat"] <= max_lat and min_lon <= z["lon"] <= max_lon
|
|
||||||
|
|
||||||
|
|
||||||
def test_overlay_catalog_has_conflicts():
|
|
||||||
entry = overlay_catalog()["conflicts"]
|
|
||||||
assert entry["kind"] == "points"
|
|
||||||
assert entry["endpoint"] == "/api/conflicts"
|
|
||||||
|
|
||||||
|
|
||||||
# ── Pure counting ──────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
TS1 = datetime(2026, 8, 30, 12, 0, tzinfo=timezone.utc)
|
|
||||||
TS2 = datetime(2026, 8, 30, 13, 0, tzinfo=timezone.utc)
|
|
||||||
|
|
||||||
|
|
||||||
def test_zone_event_stats_counts_and_picks_latest():
|
|
||||||
bbox = (40.0, 20.0, 52.0, 40.0) # roughly Ukraine
|
|
||||||
points = [
|
|
||||||
(50.45, 30.52, TS1), # inside
|
|
||||||
(48.0, 25.0, TS2), # inside, later
|
|
||||||
(0.0, -60.0, TS1), # outside
|
|
||||||
(15.0, 45.0, TS2), # outside (lat ok, lon out)
|
|
||||||
]
|
|
||||||
count, latest = zone_event_stats(points, bbox)
|
|
||||||
assert count == 2
|
|
||||||
assert latest == TS2
|
|
||||||
|
|
||||||
|
|
||||||
def test_zone_event_stats_empty_bbox():
|
|
||||||
count, latest = zone_event_stats([], (0.0, 0.0, 1.0, 1.0))
|
|
||||||
assert count == 0
|
|
||||||
assert latest is None
|
|
||||||
|
|
||||||
|
|
||||||
# ── API contract (mocked map items, no DB) ─────────────────────────────
|
|
||||||
|
|
||||||
|
|
||||||
def test_conflicts_returns_catalog_with_mocked_counts(monkeypatch):
|
|
||||||
points = [
|
|
||||||
(50.45, 30.52, TS1), # Ukraine
|
|
||||||
(25.03, 121.56, TS2), # Taiwan Strait
|
|
||||||
(0.0, -60.0, TS1), # nowhere
|
|
||||||
]
|
|
||||||
resp = _get("/api/conflicts", monkeypatch=monkeypatch, points=points)
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert "zones" in body and "timestamp" in body
|
|
||||||
by_id = {z["id"]: z for z in body["zones"]}
|
|
||||||
assert len(body["zones"]) == 13
|
|
||||||
|
|
||||||
zone = by_id["ukraine"]
|
|
||||||
assert zone["eventCount"] == 1
|
|
||||||
assert zone["lastUpdated"] == TS1.isoformat().replace("+00:00", "Z")
|
|
||||||
assert zone["severity"] == "war"
|
|
||||||
|
|
||||||
assert by_id["taiwan_strait"]["eventCount"] == 1
|
|
||||||
assert by_id["gaza"]["eventCount"] == 0
|
|
||||||
# exact per-zone key contract the frontend consumes
|
|
||||||
assert set(zone.keys()) == {
|
|
||||||
"id", "label", "severity", "lat", "lon",
|
|
||||||
"description", "eventCount", "lastUpdated",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_conflicts_empty_db_yields_zero_counts(monkeypatch):
|
|
||||||
resp = _get("/api/conflicts", monkeypatch=monkeypatch, points=[])
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert all(z["eventCount"] == 0 for z in body["zones"])
|
|
||||||
assert all(z["lastUpdated"] is None for z in body["zones"])
|
|
||||||
|
|
@ -1,66 +0,0 @@
|
||||||
"""Conflicts Leaflet overlay: default-off toggle, catalog fetch, no jitter."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
|
||||||
HTML = (ROOT / "app/static/index.html").read_text()
|
|
||||||
|
|
||||||
|
|
||||||
def _fn(name: str, until: str | None = None) -> str:
|
|
||||||
chunk = HTML.split(f"function {name}", 1)[1]
|
|
||||||
if until:
|
|
||||||
chunk = chunk.split(until, 1)[0]
|
|
||||||
return chunk
|
|
||||||
|
|
||||||
|
|
||||||
def test_conflicts_toggle_default_off():
|
|
||||||
assert 'id="lp-conflicts-on"' in HTML
|
|
||||||
assert 'id="conflicts-layer"' in HTML
|
|
||||||
assert "> Conflicts<" in HTML or "> Conflicts</" in HTML
|
|
||||||
on = HTML.split('id="lp-conflicts-on"', 1)[1].split(">", 1)[0]
|
|
||||||
assert "checked" not in on
|
|
||||||
|
|
||||||
|
|
||||||
def test_conflicts_fetches_catalog_not_liveuamap():
|
|
||||||
js = _fn("loadConflicts", "/* ═══════════════ INITIAL LOAD")
|
|
||||||
assert "/api/conflicts" in js
|
|
||||||
assert "liveuamap.com" not in HTML.lower()
|
|
||||||
assert "Math.random" not in js
|
|
||||||
assert "jitter" not in js.lower()
|
|
||||||
|
|
||||||
|
|
||||||
def test_conflicts_not_refetched_on_moveend():
|
|
||||||
refresh = HTML.split("function refreshLiveOverlays", 1)[1].split(
|
|
||||||
"function addExtraAttrib", 1
|
|
||||||
)[0]
|
|
||||||
assert "loadConflicts" not in refresh
|
|
||||||
assert "probeConflicts" not in refresh
|
|
||||||
init = HTML.split("function initMap", 1)[1].split("function readMapPrefs", 1)[0]
|
|
||||||
assert "probeConflicts()" in init
|
|
||||||
assert "loadConflicts(true)" not in init
|
|
||||||
assert "paintConflicts()" not in init
|
|
||||||
|
|
||||||
|
|
||||||
def test_conflicts_hides_toggle_on_404():
|
|
||||||
js = _fn("loadConflicts", "/* ═══════════════ INITIAL LOAD")
|
|
||||||
assert "r.status === 404" in js
|
|
||||||
assert "hideConflictsToggle()" in js
|
|
||||||
hide = _fn("hideConflictsToggle", "function paintConflicts")
|
|
||||||
assert "row.hidden = true" in hide
|
|
||||||
assert "lp-conflicts-on" in hide
|
|
||||||
|
|
||||||
|
|
||||||
def test_conflicts_popup_and_severity_colors():
|
|
||||||
paint = _fn("paintConflicts", "async function probeConflicts")
|
|
||||||
assert "z.label" in paint
|
|
||||||
assert "z.description" in paint
|
|
||||||
assert "eventCount" in paint
|
|
||||||
assert "L.circleMarker" in paint
|
|
||||||
assert "z.lat == null || z.lon == null" in paint
|
|
||||||
assert "Number.isFinite(lat)" in paint
|
|
||||||
color = _fn("conflictSeverityColor", "function hideConflictsToggle")
|
|
||||||
assert "war" in color and "#ff2a6d" in color
|
|
||||||
assert "high" in color and "#fb923c" in color
|
|
||||||
assert "elevated" in color and "#facc15" in color
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue