Compare commits
112 changed files with 1357 additions and 54912 deletions
66
.env.example
66
.env.example
|
|
@ -31,6 +31,20 @@ NOMINATIM_URL=https://nominatim.openstreetmap.org
|
|||
NOMINATIM_MIN_INTERVAL=1.1
|
||||
SNAPSHOT_TTL_SECONDS=300
|
||||
|
||||
# ── masscan active camera discovery (host-level systemd service, NOT compose) ─
|
||||
# Continuous rolling sweep for open RTSP port 554 across a range. Runs on the
|
||||
# Pi host via deploy/osint-masscan.service (needs root + raw sockets). Results
|
||||
# land in the same `cameras` table as the scraper (discovery_source=masscan).
|
||||
# NOTE: 200 pps is the residential-safe default. 1k/10k pps saturated a home
|
||||
# uplink. A full 0.0.0.0/0 sweep at 200 pps takes ~8 months (rolling).
|
||||
MASSCAN_RANGE=0.0.0.0/0
|
||||
MASSCAN_PORTS=554
|
||||
MASSCAN_RATE=200
|
||||
MASSCAN_RETRIES=1
|
||||
MASSCAN_WAIT=0
|
||||
MASSCAN_EXCLUDEFILE=/etc/osint-dashboard/masscan-excludes.txt
|
||||
MASSCAN_FLUSH_EVERY=250
|
||||
|
||||
# ── NASA FIRMS (active fire / hotspot ingest) ──────────────────────────────
|
||||
# MAP_KEY is FREE — get one at https://firms.modaps.eosdis.nasa.gov/api/map_key_info/
|
||||
# (1-minute signup, no payment). Leave blank to keep fire ingest idle.
|
||||
|
|
@ -45,45 +59,12 @@ FIRMS_INTERVAL=900
|
|||
# Set to 0 to disable the fire loop entirely.
|
||||
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) ──────────────────────────────
|
||||
# Keys such as NOUS_API_KEY and TELEGRAM_TOKEN are stored in the Postgres
|
||||
# `api_keys` table and managed from the dashboard's "Keys" tab
|
||||
# (GET/POST/DELETE /api/keys/{name}) — see app/keystore.py. The FIRMS ingestor
|
||||
# currently reads FIRMS_MAP_KEY from .env (above); wiring the Keys-UI store as
|
||||
# its lookup/fallback is a planned follow-up.
|
||||
#
|
||||
# Key management is ADMIN-ONLY (single admin, no user table). Visitors get a
|
||||
# read-only map + news. Configure the three vars below or admin endpoints
|
||||
# answer 403 {"detail": "admin auth not configured"} (fail closed — the public
|
||||
# site keeps working). In the cluster they come from Secret `osint-admin`.
|
||||
# Generate the hash: python app/auth.py hash 'your password'
|
||||
# Generate the secret: python -c 'import secrets; print(secrets.token_urlsafe(48))'
|
||||
ADMIN_USER=
|
||||
ADMIN_PASSWORD_HASH=
|
||||
ADMIN_SESSION_SECRET=
|
||||
# Optional: force the session cookie's Secure flag (1/true/yes) when the app is
|
||||
# reached over plain HTTP behind a TLS-terminating proxy that rewrites
|
||||
# X-Forwarded-Proto to http (the cluster: Cloudflare tunnel -> Cilium Gateway).
|
||||
# Leave unset locally so the cookie works over http://localhost.
|
||||
ADMIN_COOKIE_SECURE=
|
||||
|
||||
# ── News pipeline (scraper + summarizer, profile `ingest`) ────────────────
|
||||
# Scraper crawls urls.txt continuously (default 10s between crawls).
|
||||
|
|
@ -98,25 +79,6 @@ NOUS_BASE_URL=https://inference-api.nousresearch.com/v1
|
|||
# Hermes-4.3-36B remains after a Postgres miss. Env wins when set.
|
||||
# SUMMARY_MODEL=
|
||||
NEWS_BATCH_SIZE=50
|
||||
# Map-phase grading: the map model scores each article 0-100, and only blocks
|
||||
# with score >= SUMMARY_MIN_SCORE reach the reduce brief (best first).
|
||||
# If nothing clears the bar, up to SUMMARY_FALLBACK_TOP blocks scoring at least
|
||||
# SUMMARY_FALLBACK_MIN_SCORE are used; if none do, the reduce phase gets an
|
||||
# empty DATA section (SUMMARY_FALLBACK_TOP=0 does the same unconditionally).
|
||||
SUMMARY_MIN_SCORE=60
|
||||
SUMMARY_TOP_N=12
|
||||
SUMMARY_FALLBACK_TOP=3
|
||||
SUMMARY_FALLBACK_MIN_SCORE=40
|
||||
# Syndication dedupe: the same wire story arrives from many station domains
|
||||
# (kcci.com, wtae.com, …) with an identical headline. Copies are collapsed
|
||||
# before the threshold/cap, so SUMMARY_TOP_N buys distinct stories: normalised
|
||||
# titles (lowercase, trailing " - KCCI"/" | CNN"/" — AP" source suffix dropped)
|
||||
# count as one story when they are equal or >= SUMMARY_DEDUPE_SIMILARITY alike.
|
||||
# The highest-scoring copy represents the story; the rest are still written to
|
||||
# article_scores with selected=false and duplicate_of = the surviving article id.
|
||||
# Set SUMMARY_DEDUPE=0 to skip dedupe entirely (old behaviour).
|
||||
SUMMARY_DEDUPE=1
|
||||
SUMMARY_DEDUPE_SIMILARITY=0.85
|
||||
SUMMARY_WINDOW_MINUTES=15
|
||||
# Futures/markets coupling from the upstream pipeline is OFF by default
|
||||
# (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable.
|
||||
|
|
|
|||
|
|
@ -1,28 +1,17 @@
|
|||
# Build changed OSINT images and publish them to the Forgejo container
|
||||
# registry. Deployment is NOT done here: the cluster (homek8s, namespace
|
||||
# `osint`) runs amd64 images pinned by tag in apps/base/osint/*.yaml, so the
|
||||
# final step prints the tag to pin and a human opens that manifest PR.
|
||||
#
|
||||
# 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.
|
||||
# Build all OSINT images, publish to the Forgejo container registry, then
|
||||
# redeploy on the Pi runner (docker.sock mounted).
|
||||
#
|
||||
# Public pull host: forgejo.siriusdevops.com (NOT ghcr.io)
|
||||
# CI push host: 127.0.0.1:3000 — Cloudflare 413s layers ≳100MB on the public
|
||||
# hostname, even from the Pi (hairpins out through the tunnel).
|
||||
# Images (public names):
|
||||
# forgejo.siriusdevops.com/sirius/osint-dashboard:amd64-<sha12>
|
||||
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg:amd64-<sha12>
|
||||
# forgejo.siriusdevops.com/sirius/osint-news-scraper:amd64-<sha12>
|
||||
# forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64-<sha12>
|
||||
# forgejo.siriusdevops.com/sirius/osint-dashboard
|
||||
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg
|
||||
# forgejo.siriusdevops.com/sirius/osint-news-scraper
|
||||
# forgejo.siriusdevops.com/sirius/osint-news-summarizer
|
||||
#
|
||||
# Optional repo variable FORGEJO_REGISTRY overrides the *public* pull host.
|
||||
# Deploy still uses the local docker socket on the runner host (rpi).
|
||||
|
||||
name: build-and-deploy
|
||||
|
||||
|
|
@ -30,92 +19,23 @@ on:
|
|||
push:
|
||||
branches: [main, master]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
rebuild_pg:
|
||||
description: Rebuild Timescale+PostGIS (Dockerfile.pg)
|
||||
type: boolean
|
||||
default: false
|
||||
rebuild_all:
|
||||
description: Rebuild every app image (ignore path filter)
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
env:
|
||||
PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }}
|
||||
PUSH_REGISTRY: forgejo.forgejo.svc.cluster.local:3000
|
||||
PUSH_REGISTRY: 127.0.0.1:3000
|
||||
OWNER: sirius
|
||||
# Keep compose project/volumes stable on the Pi
|
||||
COMPOSE_PROJECT_NAME: osint-dashboard
|
||||
|
||||
jobs:
|
||||
build-push:
|
||||
# `amd64` only exists on siriussec-amd64, which is also the node the
|
||||
# workloads run on — so the images are built on the architecture they are
|
||||
# pulled to. `runs-on: docker` matched the Pi's arm64 runner, which
|
||||
# produced images the amd64 cluster could never run.
|
||||
# No job-level `permissions:` block: Forgejo ignores it (it emits a
|
||||
# pre-execution warning) and the push authenticates with the FORGEJO_TOKEN
|
||||
# user PAT instead, because the package registry rejects the Actions token.
|
||||
runs-on: amd64
|
||||
build-push-deploy:
|
||||
runs-on: docker
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: https://code.forgejo.org/actions/checkout@v4
|
||||
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
|
||||
id: img
|
||||
|
|
@ -125,11 +45,10 @@ jobs:
|
|||
PUB="${PUBLIC_REGISTRY}"
|
||||
OWN="${OWNER}"
|
||||
SHA="${GITHUB_SHA::12}"
|
||||
TAG="amd64-${SHA}"
|
||||
{
|
||||
echo "reg=$PUSH"
|
||||
echo "pub=$PUB"
|
||||
echo "tag=$TAG"
|
||||
echo "sha=$SHA"
|
||||
echo "app=$PUSH/$OWN/osint-dashboard"
|
||||
echo "pg=$PUSH/$OWN/osint-dashboard-pg"
|
||||
echo "scraper=$PUSH/$OWN/osint-news-scraper"
|
||||
|
|
@ -137,93 +56,109 @@ jobs:
|
|||
} >> "$GITHUB_OUTPUT"
|
||||
echo "Push registry: $PUSH"
|
||||
echo "Public pull: $PUB"
|
||||
echo "Image tag: $TAG"
|
||||
echo "SHA tag: $SHA"
|
||||
|
||||
- name: Login to Forgejo registry
|
||||
if: steps.plan.outputs.app == '1' || steps.plan.outputs.scraper == '1' || steps.plan.outputs.summarizer == '1' || steps.plan.outputs.pg == '1'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# GITHUB_TOKEN login "succeeds" but blob uploads 401 (Forgejo packages
|
||||
# reject the Actions token). Use a user PAT.
|
||||
# The PAT must carry the `write:package` scope: Forgejo mints a push
|
||||
# token even without it and then rejects every blob upload with
|
||||
# `unauthorized: reqPackageAccess` (routers/api/packages/api.go
|
||||
# reqPackageAccess -> AccessTokenScopeWritePackage).
|
||||
# Name is REGISTRY_TOKEN, not FORGEJO_TOKEN: Forgejo reserves the
|
||||
# FORGEJO_/GITHUB_ prefixes and refuses to create or update them via
|
||||
# the API.
|
||||
if [ -z "${{ secrets.REGISTRY_TOKEN }}" ]; then
|
||||
echo "Missing repo secret REGISTRY_TOKEN (user PAT with write:package, not GITHUB_TOKEN)"
|
||||
# reject the Actions token). Use a user PAT with write:package.
|
||||
if [ -z "${{ secrets.FORGEJO_TOKEN }}" ]; then
|
||||
echo "Missing repo secret FORGEJO_TOKEN (user PAT, not GITHUB_TOKEN)"
|
||||
exit 1
|
||||
fi
|
||||
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \
|
||||
echo "${{ secrets.FORGEJO_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \
|
||||
-u sirius --password-stdin
|
||||
|
||||
- name: Build application image (api / ingester / cameras)
|
||||
if: steps.plan.outputs.app == '1'
|
||||
run: |
|
||||
set -ex
|
||||
IMG="${{ steps.img.outputs.app }}"
|
||||
TAG="${{ steps.img.outputs.tag }}"
|
||||
docker build -f Dockerfile -t "${IMG}:${TAG}" .
|
||||
docker push "${IMG}:${TAG}"
|
||||
APP="${{ steps.img.outputs.app }}"
|
||||
SHA="${{ steps.img.outputs.sha }}"
|
||||
docker build -f Dockerfile -t "${APP}:latest" -t "${APP}:${SHA}" \
|
||||
-t "localhost/osint-dashboard:latest" .
|
||||
docker push "${APP}:latest"
|
||||
docker push "${APP}:${SHA}"
|
||||
|
||||
- name: Build news-scraper image
|
||||
if: steps.plan.outputs.scraper == '1'
|
||||
run: |
|
||||
set -ex
|
||||
IMG="${{ steps.img.outputs.scraper }}"
|
||||
TAG="${{ steps.img.outputs.tag }}"
|
||||
docker build -f news/scraper/Dockerfile -t "${IMG}:${TAG}" news/scraper
|
||||
docker push "${IMG}:${TAG}"
|
||||
SHA="${{ steps.img.outputs.sha }}"
|
||||
docker build -f news/scraper/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \
|
||||
-t "localhost/osint-news-scraper:latest" news/scraper
|
||||
docker push "${IMG}:latest"
|
||||
docker push "${IMG}:${SHA}"
|
||||
|
||||
- name: Build news-summarizer image
|
||||
if: steps.plan.outputs.summarizer == '1'
|
||||
run: |
|
||||
set -ex
|
||||
IMG="${{ steps.img.outputs.summarizer }}"
|
||||
TAG="${{ steps.img.outputs.tag }}"
|
||||
docker build -f news/summerizer/Dockerfile -t "${IMG}:${TAG}" news/summerizer
|
||||
docker push "${IMG}:${TAG}"
|
||||
SHA="${{ steps.img.outputs.sha }}"
|
||||
docker build -f news/summerizer/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \
|
||||
-t "localhost/osint-news-summarizer:latest" news/summerizer
|
||||
docker push "${IMG}:latest"
|
||||
docker push "${IMG}:${SHA}"
|
||||
|
||||
- name: Build / refresh Timescale+PostGIS image
|
||||
if: steps.plan.outputs.pg == '1'
|
||||
run: |
|
||||
set -ex
|
||||
IMG="${{ steps.img.outputs.pg }}"
|
||||
TAG="${{ steps.img.outputs.tag }}"
|
||||
docker build -f Dockerfile.pg -t "${IMG}:${TAG}" .
|
||||
docker push "${IMG}:${TAG}"
|
||||
PG="${{ steps.img.outputs.pg }}"
|
||||
SHA="${{ steps.img.outputs.sha }}"
|
||||
# Prefer rebuild so registry always has a current pg image. If packagecloud
|
||||
# is unreachable, fall back to whatever local image already exists.
|
||||
if docker build -f Dockerfile.pg -t "${PG}:latest" -t "${PG}:${SHA}" \
|
||||
-t "localhost/osint-dashboard-pg:latest" .; then
|
||||
docker push "${PG}:latest"
|
||||
docker push "${PG}:${SHA}"
|
||||
elif docker image inspect "localhost/osint-dashboard-pg:latest" >/dev/null 2>&1; then
|
||||
echo "WARN: Dockerfile.pg build failed; retagging existing local pg image into registry"
|
||||
docker tag "localhost/osint-dashboard-pg:latest" "${PG}:latest"
|
||||
docker tag "localhost/osint-dashboard-pg:latest" "${PG}:${SHA}"
|
||||
docker push "${PG}:latest"
|
||||
docker push "${PG}:${SHA}"
|
||||
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
|
||||
# Name-pinned containers (container_name: osint-dashboard, …) collide
|
||||
# when compose tries to create instead of recreate — e.g. leftover from
|
||||
# a different working_dir or a half-failed previous up. down + rm -f
|
||||
# the known names, then up the full ingest profile.
|
||||
chmod +x scripts/compose-reup.sh
|
||||
COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \
|
||||
scripts/compose-reup.sh
|
||||
docker image prune -f
|
||||
echo "osint-dashboard deployed; images also on ${PUB}/${OWN}/"
|
||||
|
||||
- name: Summary
|
||||
if: always()
|
||||
run: |
|
||||
TAG="${{ steps.img.outputs.tag }}"
|
||||
PUB="${{ steps.img.outputs.pub }}"
|
||||
{
|
||||
echo "## Image plan"
|
||||
echo "- app: \`${{ steps.plan.outputs.app }}\`"
|
||||
echo "- news-scraper: \`${{ steps.plan.outputs.scraper }}\`"
|
||||
echo "- news-summarizer: \`${{ steps.plan.outputs.summarizer }}\`"
|
||||
echo "- pg (Timescale): \`${{ steps.plan.outputs.pg }}\`"
|
||||
echo
|
||||
if [ -n "$TAG" ]; then
|
||||
echo "## Pin in homek8s (apps/base/osint)"
|
||||
echo "Pushed tag: \`${TAG}\`. Set the workload images in"
|
||||
echo "\`apps/base/osint/kustomization.yaml\` to:"
|
||||
echo
|
||||
echo '```yaml'
|
||||
echo "images:"
|
||||
echo " - name: ${PUB}/${OWNER}/osint-dashboard"
|
||||
echo " newTag: ${TAG}"
|
||||
echo " - name: ${PUB}/${OWNER}/osint-news-scraper"
|
||||
echo " newTag: ${TAG}"
|
||||
echo " - name: ${PUB}/${OWNER}/osint-news-summarizer"
|
||||
echo " newTag: ${TAG}"
|
||||
echo '```'
|
||||
else
|
||||
echo "_No tag computed — the earlier steps failed before Image refs._"
|
||||
fi
|
||||
echo
|
||||
echo "Postgres is rebuilt only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)."
|
||||
echo "## Forgejo registry images"
|
||||
echo "Pushed via ${{ steps.img.outputs.reg }} (loopback). Pull publicly:"
|
||||
echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-dashboard:latest\`"
|
||||
echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-dashboard-pg:latest\`"
|
||||
echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-news-scraper:latest\`"
|
||||
echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-news-summarizer:latest\`"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import shutil
|
||||
from cachetools import TTLCache
|
||||
|
||||
logger = logging.getLogger("osint.bg_jobs")
|
||||
|
||||
MASSCAN_PPS_CAP = 200
|
||||
|
||||
_masscan_task: asyncio.Task | None = None
|
||||
_ffmpeg_cache: TTLCache = TTLCache(maxsize=100, ttl=300)
|
||||
_ffmpeg_tasks: dict[str, asyncio.Task] = {}
|
||||
_FFMPEG = shutil.which("ffmpeg")
|
||||
|
||||
|
||||
def schedule_masscan_pass() -> bool:
|
||||
"""Kick one capped masscan pass. Returns False if a pass is already running."""
|
||||
global _masscan_task
|
||||
if _masscan_task is not None and not _masscan_task.done():
|
||||
return False
|
||||
_masscan_task = asyncio.create_task(_run_masscan_capped())
|
||||
return True
|
||||
|
||||
|
||||
async def _run_masscan_capped() -> None:
|
||||
import masscan_config as cfg
|
||||
from run_masscan_service import _verify_excludefile, run_pass
|
||||
|
||||
orig = cfg.MASSCAN_RATE
|
||||
if orig > MASSCAN_PPS_CAP:
|
||||
logger.warning("capping masscan rate %s pps -> %s", orig, MASSCAN_PPS_CAP)
|
||||
cfg.MASSCAN_RATE = MASSCAN_PPS_CAP
|
||||
try:
|
||||
_verify_excludefile()
|
||||
await run_pass()
|
||||
finally:
|
||||
cfg.MASSCAN_RATE = orig
|
||||
|
||||
|
||||
def cached_ffmpeg_jpeg(url: str) -> bytes | None:
|
||||
return _ffmpeg_cache.get(url)
|
||||
|
||||
|
|
|
|||
|
|
@ -16,8 +16,6 @@ CALTRANS_CCTV_URLS = tuple(
|
|||
f"https://cwwp2.dot.ca.gov/data/d{n}/cctv/cctvStatusD{n:02d}.json"
|
||||
for n in range(1, 13)
|
||||
)
|
||||
# MDOT MiDrive official DOT CCTV list (fields carry rendered HTML).
|
||||
MDOT_CAMERA_URL = "https://mdotjboss.state.mi.us/MiDrive/camera/list"
|
||||
_DEFAULT_SOURCE_URL = ",".join((
|
||||
# Publicly published open-camera list (markdown bullets of stream URLs).
|
||||
"https://raw.githubusercontent.com/fury999io/public-ip-cams/main/README.md",
|
||||
|
|
@ -27,10 +25,6 @@ _DEFAULT_SOURCE_URL = ",".join((
|
|||
"https://raw.githubusercontent.com/willytop8/Live-Environment-Streams/main/streams.geojson",
|
||||
# Official Caltrans CWWP2 JPEG + HLS CCTV (districts 1–12).
|
||||
*CALTRANS_CCTV_URLS,
|
||||
# Oregon DOT TripCheck public CCTV JPEG inventory (Esri JSON).
|
||||
"https://www.tripcheck.com/Scripts/map/data/cctvinventory.js",
|
||||
# Official MDOT MiDrive CCTV (JPEG stills, Michigan).
|
||||
MDOT_CAMERA_URL,
|
||||
))
|
||||
CAMERA_SOURCE_URLS = [
|
||||
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_TIMEOUT = float(os.getenv("SNAPSHOT_TIMEOUT", "8.0"))
|
||||
|
||||
# Retained so an old CAMERA_NATS_SUBJECT env does not surprise operators.
|
||||
# This service does not publish on it; cameras live in the cameras table.
|
||||
# NATS subject cameras are published on (consumed by the shared ingester).
|
||||
CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera")
|
||||
|
||||
|
||||
# ── 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.
|
||||
|
||||
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
|
||||
handed the browser an rtsp:// URL (which opens VLC).
|
||||
|
||||
|
|
@ -42,6 +42,16 @@ _HTTP_PATHS = (
|
|||
"/tmpfs/auto.jpg",
|
||||
)
|
||||
|
||||
# Browser-playable MJPEG paths the /stream proxy can pass through.
|
||||
_MJPEG_PATHS = (
|
||||
"/mjpg/video.mjpg",
|
||||
"/video.mjpg",
|
||||
"/cgi-bin/mjpg/video.cgi",
|
||||
"/axis-cgi/mjpg/video.cgi",
|
||||
"/nphMotionJpeg",
|
||||
"/mjpeg.cgi",
|
||||
)
|
||||
|
||||
_FFMPEG = shutil.which("ffmpeg")
|
||||
|
||||
|
||||
|
|
@ -77,6 +87,55 @@ async def _http_get_image(url: str, timeout: float = 2.5) -> bytes | None:
|
|||
return None
|
||||
|
||||
|
||||
async def _http_feed_url(url: str, timeout: float = 2.5) -> str | None:
|
||||
"""Return url if it looks like an unauthenticated image/MJPEG feed."""
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=timeout, follow_redirects=True,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
) as c:
|
||||
async with c.stream("GET", url) as r:
|
||||
if r.status_code != 200:
|
||||
return None
|
||||
ctype = (r.headers.get("content-type") or "").lower()
|
||||
if "html" in ctype or ctype.startswith("text/"):
|
||||
return None
|
||||
if any(x in ctype for x in ("image/", "multipart", "mjpeg", "octet-stream")):
|
||||
# Read a little to reject empty/error bodies.
|
||||
chunk = b""
|
||||
async for b in r.aiter_bytes():
|
||||
chunk += b
|
||||
if len(chunk) >= 64:
|
||||
break
|
||||
if len(chunk) < 64:
|
||||
return None
|
||||
if b"html" in chunk[:64].lower():
|
||||
return None
|
||||
return url
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
async def probe_public_feed(host: str) -> str | None:
|
||||
"""Unauthenticated HTTP still or MJPEG URL for this host, or None.
|
||||
|
||||
Used at masscan ingest time so dead RTSP-only hosts never hit the map.
|
||||
No credentials, no RTSP path-walking (too slow / rarely public).
|
||||
"""
|
||||
urls = [f"http://{host}{p}" for p in _HTTP_PATHS]
|
||||
urls.append(f"http://{host}:8080/shot.jpg")
|
||||
urls.extend(f"http://{host}{p}" for p in _MJPEG_PATHS)
|
||||
results = await asyncio.gather(
|
||||
*(_http_feed_url(u) for u in urls),
|
||||
return_exceptions=True,
|
||||
)
|
||||
for url, hit in zip(urls, results):
|
||||
if isinstance(hit, str) and hit:
|
||||
return hit
|
||||
return None
|
||||
|
||||
|
||||
async def ffmpeg_snapshot(url: str, timeout: float = 8.0) -> bytes | None:
|
||||
"""Grab a single JPEG frame from an RTSP URL. None if ffmpeg missing/fails.
|
||||
|
||||
|
|
|
|||
|
|
@ -11,8 +11,8 @@ Pipeline per cycle:
|
|||
2. Parse cameras (Insecam-style HTML with embedded lat/lon, or plain-text
|
||||
`url[|lat,lon|vendor|location]` lines).
|
||||
3. Geocode missing coords via Nominatim at <=1 req/s.
|
||||
4. Upsert into the `cameras` table keyed by sha256(url_hash).
|
||||
Discovery is not published as an event.
|
||||
4. Publish each camera to NATS (`events.camera`) for the shared ingester,
|
||||
and upsert into the `cameras` table keyed by sha256(url_hash).
|
||||
|
||||
Snapshots are cached locally with a TTL; nothing is fetched more often than
|
||||
the cache allows.
|
||||
|
|
@ -25,7 +25,6 @@ import hashlib
|
|||
import ipaddress
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
|
@ -38,7 +37,6 @@ from camera_config import (
|
|||
CAMERA_SOURCE_URLS, CAMERA_REQUEST_DELAY, CAMERA_MAX_PER_SOURCE,
|
||||
NOMINATIM_URL, NOMINATIM_MIN_INTERVAL, USER_AGENT,
|
||||
SNAPSHOT_CACHE_DIR, SNAPSHOT_TTL_SECONDS, SNAPSHOT_TIMEOUT,
|
||||
UDOT_IBI_URL, UDOT_IBI_BASE, UDOT_IBI_PAGE_SIZE, UDOT_IBI_MAX_PAGES,
|
||||
)
|
||||
from camera_models import cameras
|
||||
from database import async_session
|
||||
|
|
@ -116,15 +114,6 @@ class RateLimitedClient:
|
|||
self._last[host] = time.monotonic()
|
||||
return await self.client.get(url, **kw)
|
||||
|
||||
async def post(self, url: str, **kw) -> httpx.Response:
|
||||
host = urlparse(url).netloc
|
||||
now = time.monotonic()
|
||||
wait = self._last.get(host, 0.0) + self._delay - now
|
||||
if wait > 0:
|
||||
await asyncio.sleep(wait)
|
||||
self._last[host] = time.monotonic()
|
||||
return await self.client.post(url, **kw)
|
||||
|
||||
async def aclose(self):
|
||||
await self.client.aclose()
|
||||
|
||||
|
|
@ -390,201 +379,6 @@ def parse_caltrans_json(text: str, source_name: str) -> list[dict]:
|
|||
return out
|
||||
|
||||
|
||||
# ── UDOT IBI 511 ──────────────────────────────────────────────────────────
|
||||
# Utah bbox (lat 36.9–42.1, lon -114.2–-108.9). WKT is `POINT (lng lat)`.
|
||||
_UDOT_IBI_MIN_LAT, _UDOT_IBI_MAX_LAT = 36.9, 42.1
|
||||
_UDOT_IBI_MIN_LON, _UDOT_IBI_MAX_LON = -114.2, -108.9
|
||||
_UDOT_WKT_POINT_RE = re.compile(
|
||||
r"POINT\s*\(\s*(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s*\)", re.I,
|
||||
)
|
||||
|
||||
|
||||
def parse_udot_ibi_page(text: str, source_name: str = "udot") -> list[dict]:
|
||||
"""Parse one UDOT IBI 511 DataTables camera page (`{"data": [...]}`).
|
||||
|
||||
Skips rows whose first image is `blocked` or `disabled`, and drops any
|
||||
point outside the Utah bbox. The `/map/Cctv/{id}` URL is a stable identity
|
||||
(always serves the latest frame), so it is stored as both source_url and
|
||||
snapshot_url — we never scrape frames ourselves.
|
||||
"""
|
||||
try:
|
||||
payload = json.loads(text)
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
return []
|
||||
rows = payload.get("data") if isinstance(payload, dict) else None
|
||||
if not isinstance(rows, list):
|
||||
return []
|
||||
out: list[dict] = []
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
cam_id = row.get("id")
|
||||
images = row.get("images") or []
|
||||
if cam_id is None or not images:
|
||||
continue
|
||||
img = images[0] or {}
|
||||
if img.get("blocked") or img.get("disabled"):
|
||||
continue
|
||||
lon = lat = None
|
||||
try:
|
||||
wkt = (row.get("latLng") or {}).get("geography") or {}
|
||||
wkt = wkt.get("wellKnownText") or ""
|
||||
m = _UDOT_WKT_POINT_RE.match(str(wkt).strip())
|
||||
if m:
|
||||
lon, lat = float(m.group(1)), float(m.group(2))
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
lon = lat = None
|
||||
if lat is None or lon is None:
|
||||
continue
|
||||
if not (_UDOT_IBI_MIN_LAT <= lat <= _UDOT_IBI_MAX_LAT
|
||||
and _UDOT_IBI_MIN_LON <= lon <= _UDOT_IBI_MAX_LON):
|
||||
continue
|
||||
snap = f"{UDOT_IBI_BASE}/map/Cctv/{cam_id}"
|
||||
roadway, direction, location = (
|
||||
row.get("roadway"), row.get("direction"), row.get("location"),
|
||||
)
|
||||
name = ", ".join(
|
||||
str(b) for b in (roadway, direction, location)
|
||||
if b and str(b).strip() and str(b).strip().lower() != "unknown"
|
||||
) or None
|
||||
out.append({
|
||||
"source_url": snap,
|
||||
"snapshot_url": snap,
|
||||
"discovery_source": source_name,
|
||||
"location_lat": lat,
|
||||
"location_lon": lon,
|
||||
"location_name": name,
|
||||
"vendor": "UDOT",
|
||||
"device_type": "http",
|
||||
"raw": {
|
||||
"udot_id": cam_id,
|
||||
"agency": row.get("source"),
|
||||
"source_id": row.get("sourceId"),
|
||||
"roadway": roadway,
|
||||
"direction": direction,
|
||||
},
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
# 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]:
|
||||
"""Parse willytop8/Live-Environment-Streams GeoJSON.
|
||||
|
||||
|
|
@ -696,10 +490,6 @@ async def scrape_source(client: RateLimitedClient, geo: Geocoder,
|
|||
body = resp.text
|
||||
if "cwwp2.dot.ca.gov" in src_url or "cctvStatus" in src_url:
|
||||
cams = parse_caltrans_json(body, name)
|
||||
elif "cctvinventory" in src_url or "tripcheck.com" in src_url:
|
||||
cams = parse_odot_json(body, name)
|
||||
elif "mdotjboss.state.mi.us" in src_url or "/MiDrive/camera/list" in src_url:
|
||||
cams = parse_mdot_json(body, name)
|
||||
elif ("getCameraDataByLoc" in src_url
|
||||
or ("json" in ctype and '"locs"' in body[:4000] and '"cams"' in body[:8000])):
|
||||
cams = parse_alertwest_json(body, name)
|
||||
|
|
@ -759,54 +549,6 @@ async def scrape_source(client: RateLimitedClient, geo: Geocoder,
|
|||
return out
|
||||
|
||||
|
||||
# ── UDOT IBI 511 paginated fetcher ────────────────────────────────────────
|
||||
|
||||
async def scrape_udot_ibi(client: RateLimitedClient) -> list[dict]:
|
||||
"""Page through the UDOT IBI 511 DataTables endpoint and normalize.
|
||||
|
||||
POSTs `start`/`length` form fields (server caps at 100 rows/page), walking
|
||||
pages until `recordsTotal` is exhausted or UDOT_IBI_MAX_PAGES is hit.
|
||||
"""
|
||||
out: list[dict] = []
|
||||
seen: set[str] = set()
|
||||
start = 0
|
||||
for _ in range(UDOT_IBI_MAX_PAGES):
|
||||
try:
|
||||
resp = await client.post(
|
||||
UDOT_IBI_URL,
|
||||
data={
|
||||
"start": str(start),
|
||||
"length": str(UDOT_IBI_PAGE_SIZE),
|
||||
"lang": "en-US",
|
||||
},
|
||||
headers={"X-Requested-With": "XMLHttpRequest"},
|
||||
)
|
||||
resp.raise_for_status()
|
||||
body = resp.text
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("failed to fetch UDOT IBI page start=%d", start)
|
||||
break
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
except ValueError:
|
||||
logger.warning("UDOT IBI non-JSON response at start=%d", start)
|
||||
break
|
||||
total = int(payload.get("recordsTotal") or 0)
|
||||
rows = payload.get("data") or []
|
||||
if not isinstance(rows, list) or not rows:
|
||||
break
|
||||
for cam in parse_udot_ibi_page(body, "udot"):
|
||||
if cam["source_url"] in seen:
|
||||
continue
|
||||
seen.add(cam["source_url"])
|
||||
out.append(cam)
|
||||
if start + len(rows) >= total:
|
||||
break
|
||||
start += len(rows)
|
||||
logger.info("UDOT IBI yielded %d cameras", len(out))
|
||||
return out
|
||||
|
||||
|
||||
# ── Persistence ────────────────────────────────────────────────────────────
|
||||
|
||||
async def upsert_cameras(cams: list[dict]) -> int:
|
||||
|
|
@ -858,7 +600,6 @@ async def run_cycle() -> int:
|
|||
try:
|
||||
results = await asyncio.gather(
|
||||
*(scrape_source(client, geo, s) for s in CAMERA_SOURCE_URLS),
|
||||
scrape_udot_ibi(client),
|
||||
return_exceptions=True,
|
||||
)
|
||||
all_cams: list[dict] = []
|
||||
|
|
|
|||
|
|
@ -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", "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_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.
|
||||
AISSTREAM_IN_APP = os.getenv("AISSTREAM_IN_APP", "1").lower() in ("1", "true", "yes")
|
||||
AISSTREAM_IN_INGEST = os.getenv("AISSTREAM_IN_INGEST", "0").lower() in ("1", "true", "yes")
|
||||
|
||||
# VesselAPI (quota-capped REST AIS poller — free tier 150 calls/mo).
|
||||
# AISStream keeps US coasts; VesselAPI fills the Middle East blind spot. The
|
||||
# poller idles when VESSELAPI_API_KEY is unset (never from GET /api/vessels).
|
||||
VESSELAPI_API_KEY = os.getenv("VESSELAPI_API_KEY", "")
|
||||
# Bounding box(es) as minlat,minlon,maxlat,maxlon — note lat/lon order (same as
|
||||
# AISSTREAM_BBOX). Semicolon-separated for multiple boxes. Default: Strait of
|
||||
# Hormuz (|dLat|+|dLon| = 3.6 ≤ 4° span cap). VesselAPI 400s any box over 4°.
|
||||
VESSELAPI_BBOX = os.getenv("VESSELAPI_BBOX", "25.5,55.4,27.3,57.2")
|
||||
# Poll cadence in seconds. 17280 = 4.8h → 5 polls/day (150/mo free tier).
|
||||
VESSELAPI_INTERVAL = int(os.getenv("VESSELAPI_INTERVAL", "17280"))
|
||||
# Local hard cap on successful 2xx calls per UTC day (persisted in Postgres).
|
||||
VESSELAPI_MAX_CALLS_PER_DAY = int(os.getenv("VESSELAPI_MAX_CALLS_PER_DAY", "5"))
|
||||
# Run the VesselAPI poller inside the dashboard process (default on, like AIS).
|
||||
VESSELAPI_IN_APP = os.getenv("VESSELAPI_IN_APP", "1").lower() in ("1", "true", "yes")
|
||||
VESSELAPI_IN_INGEST = os.getenv("VESSELAPI_IN_INGEST", "0").lower() in ("1", "true", "yes")
|
||||
|
||||
# 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
|
||||
|
|
@ -22,7 +22,6 @@ UTC date (YYYY-MM-DD).
|
|||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
|
|
@ -45,11 +44,6 @@ from upstream_cache import firms_cache
|
|||
|
||||
logger = logging.getLogger("osint.firms")
|
||||
|
||||
# In-process poll state: skip byte-identical CSVs, persist only new hotspots.
|
||||
# Survives the 15-minute loop; one full ON CONFLICT after process start.
|
||||
_csv_digest: dict[tuple, bytes] = {}
|
||||
_seen_ids: dict[tuple, set[int]] = {}
|
||||
|
||||
# ── FIRMS API ─────────────────────────────────────────────────────────────
|
||||
|
||||
FIRMS_AREA_CSV = (
|
||||
|
|
@ -92,34 +86,33 @@ def normalize_acq_time(acq_date: object, acq_time: object) -> datetime | None:
|
|||
return None
|
||||
|
||||
|
||||
def _hotspot_id(lat: float, lon: float, acq_iso: str, satellite: str) -> int:
|
||||
return hash((round(lat, 5), round(lon, 5), acq_iso, satellite))
|
||||
def parse_firms_csv(text: str) -> list[dict]:
|
||||
"""Parse a FIRMS area CSV payload into normalized fire messages.
|
||||
|
||||
|
||||
def parse_firms_csv_delta(
|
||||
text: str, skip_ids: set[int] | None = None,
|
||||
) -> tuple[list[dict], set[int]]:
|
||||
"""Parse FIRMS CSV; optionally drop hotspots already seen this process.
|
||||
|
||||
Returns (new_or_all_points, ids_for_every_valid_row). Streaming — does not
|
||||
materialize the raw CSV as a list of lists.
|
||||
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.
|
||||
"""
|
||||
reader = csv.reader(io.StringIO(text))
|
||||
header = None
|
||||
for row in reader:
|
||||
rows = list(csv.reader(io.StringIO(text)))
|
||||
if not rows:
|
||||
return []
|
||||
|
||||
# Locate the real header row. FIRMS normally returns the CSV header first,
|
||||
# but occasionally prepends a legend/info line, so scan until we see the
|
||||
# canonical header.
|
||||
header_idx = 0
|
||||
for i, row in enumerate(rows):
|
||||
if row and row[0].strip().lower() == "latitude" and len(row) >= 4:
|
||||
header = [c.strip().lower() for c in row]
|
||||
header_idx = i
|
||||
break
|
||||
if not header or "latitude" not in header or "longitude" not in header:
|
||||
logger.warning(
|
||||
"FIRMS payload does not look like a hotspot CSV (first row: %r)",
|
||||
(header or [])[:6],
|
||||
)
|
||||
return [], set()
|
||||
header = [c.strip().lower() for c in rows[header_idx]]
|
||||
# Guard against a header that isn't actually the FIRMS one.
|
||||
if "latitude" not in header or "longitude" not in header:
|
||||
logger.warning("FIRMS payload does not look like a hotspot CSV (first row: %r)", header[:6])
|
||||
return []
|
||||
|
||||
points: list[dict] = []
|
||||
ids: set[int] = set()
|
||||
for row in reader:
|
||||
for row in rows[header_idx + 1:]:
|
||||
if len(row) < len(header):
|
||||
continue
|
||||
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"))
|
||||
if acq_time is None:
|
||||
continue
|
||||
sat = str(rec.get("satellite") or "").strip()
|
||||
acq_iso = acq_time.isoformat()
|
||||
hid = _hotspot_id(lat, lon, acq_iso, sat)
|
||||
ids.add(hid)
|
||||
if skip_ids is not None and hid in skip_ids:
|
||||
continue
|
||||
points.append({
|
||||
"latitude": lat,
|
||||
"longitude": lon,
|
||||
"brightness": _to_float(rec.get("bright_ti4")),
|
||||
"confidence": str(rec.get("confidence") or "").strip(),
|
||||
"acq_time": acq_iso,
|
||||
"satellite": sat,
|
||||
"acq_time": acq_time.isoformat(),
|
||||
"satellite": str(rec.get("satellite") or "").strip(),
|
||||
"instrument": str(rec.get("instrument") or "").strip(),
|
||||
"bright_ti5": _to_float(rec.get("bright_ti5")),
|
||||
"frp": _to_float(rec.get("frp")),
|
||||
|
|
@ -151,17 +138,6 @@ def parse_firms_csv_delta(
|
|||
"track": _to_float(rec.get("track")),
|
||||
"version": str(rec.get("version") or "").strip(),
|
||||
})
|
||||
return points, ids
|
||||
|
||||
|
||||
def parse_firms_csv(text: str) -> list[dict]:
|
||||
"""Parse a FIRMS area CSV payload into normalized fire messages.
|
||||
|
||||
Returns one dict per hotspot with the fields stored in the ``fires`` table
|
||||
(acq_time already combined into a UTC ISO timestamp). Rows that don't look
|
||||
like valid VIIRS detections are skipped rather than failing the whole poll.
|
||||
"""
|
||||
points, _ids = parse_firms_csv_delta(text)
|
||||
return points
|
||||
|
||||
|
||||
|
|
@ -239,18 +215,11 @@ async def ingest_fires(bbox: str | None = None) -> int:
|
|||
dataset, first_line,
|
||||
)
|
||||
continue
|
||||
poll_key = (dataset, area, FIRMS_DAYS)
|
||||
digest = hashlib.sha256(text.encode("utf-8", "surrogatepass")).digest()
|
||||
if _csv_digest.get(poll_key) == digest:
|
||||
logger.info("FIRMS %s CSV unchanged, skip parse/insert", dataset)
|
||||
continue
|
||||
points, ids = parse_firms_csv_delta(text, skip_ids=_seen_ids.get(poll_key))
|
||||
published = await persist_hotspots(points) if points else 0
|
||||
_csv_digest[poll_key] = digest
|
||||
_seen_ids[poll_key] = ids
|
||||
points = parse_firms_csv(text)
|
||||
published = await persist_hotspots(points)
|
||||
total_published += published
|
||||
logger.info(
|
||||
"FIRMS: fetched %d hotspot(s) for bbox=%s (%s), published %d",
|
||||
len(ids), area, dataset, published,
|
||||
len(points), area, dataset, 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
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
|
@ -16,19 +15,6 @@ from sqlalchemy import text
|
|||
|
||||
from database import async_session
|
||||
|
||||
logger = logging.getLogger("osint.geofence")
|
||||
|
||||
# New hit kinds. adsb/ais/firms omit ``evidence``; these three must include it.
|
||||
# ``camera`` is never a hit kind.
|
||||
EVIDENCE_KINDS = frozenset({"earthquake", "fire_incident", "news"})
|
||||
_CAMERA_CAP = 5
|
||||
_NEWS_CAP = 3
|
||||
# Process-local "already paged" set for polled incidents. The 5-minute
|
||||
# cooldown still applies; this stops a later poll (or a restart that
|
||||
# re-reads the DB check) from treating a durable hit as new. Not used
|
||||
# for moving adsb/ais/firms targets.
|
||||
_notified_once: set[tuple[str, str, str]] = set()
|
||||
|
||||
|
||||
def _rings_from_geojson(geojson: dict) -> list[list[list[float]]]:
|
||||
if not isinstance(geojson, dict):
|
||||
|
|
@ -113,160 +99,6 @@ _recent_hits: dict[tuple[str, str], datetime] = {}
|
|||
_HIT_COOLDOWN = timedelta(minutes=5)
|
||||
|
||||
|
||||
def iso_z(ts: datetime) -> str:
|
||||
"""UTC ISO-8601 with a Z suffix so it is safe in a query string."""
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
return ts.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def snapshot_path(gid: str, ts: datetime) -> str:
|
||||
return f"/api/geofences/{gid}/at?ts={iso_z(ts)}"
|
||||
|
||||
|
||||
def camera_evidence(row: dict) -> dict:
|
||||
"""Proxy path only. Never copy ``cameras.snapshot_url`` (agency / rtsp)."""
|
||||
cid = str(row.get("id") or "")
|
||||
name = row.get("name")
|
||||
if name is None:
|
||||
name = row.get("location_name") or ""
|
||||
return {
|
||||
"id": cid,
|
||||
"name": str(name or ""),
|
||||
"snapshot_url": f"/api/cameras/{cid}/snapshot",
|
||||
}
|
||||
|
||||
|
||||
def news_evidence(row: dict) -> dict:
|
||||
return {
|
||||
"headline": str(row.get("headline") or ""),
|
||||
"url": str(row.get("url") or ""),
|
||||
"importance": str(row.get("importance") or ""),
|
||||
}
|
||||
|
||||
|
||||
def evidence_pack(
|
||||
gid: str, ts: datetime, cameras: list[dict], news: list[dict],
|
||||
) -> dict:
|
||||
return {
|
||||
"cameras": [camera_evidence(r) for r in cameras[:_CAMERA_CAP]],
|
||||
"news": [news_evidence(r) for r in news[:_NEWS_CAP]],
|
||||
"snapshot": snapshot_path(gid, ts),
|
||||
}
|
||||
|
||||
|
||||
def polygon_bbox(geojson: dict) -> str | None:
|
||||
"""``minlon,minlat,maxlon,maxlat`` of the outer ring, or None."""
|
||||
try:
|
||||
rings = _rings_from_geojson(geojson)
|
||||
except (ValueError, TypeError, KeyError):
|
||||
return None
|
||||
pts = rings[0]
|
||||
lons = [p[0] for p in pts]
|
||||
lats = [p[1] for p in pts]
|
||||
return f"{min(lons)},{min(lats)},{max(lons)},{max(lats)}"
|
||||
|
||||
|
||||
def earthquake_entity_id(row: dict) -> str:
|
||||
"""Stable id shared by the insert hook and the catch-up scan."""
|
||||
raw = row.get("raw")
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
raw = json.loads(raw)
|
||||
except ValueError:
|
||||
raw = None
|
||||
if isinstance(raw, dict) and raw.get("usgs_id"):
|
||||
return str(raw["usgs_id"])
|
||||
url = row.get("url")
|
||||
if url and str(url).strip():
|
||||
return str(url).strip()
|
||||
return str(row.get("id") or row.get("event_id") or "")
|
||||
|
||||
|
||||
def fire_incident_entity_id(marker: dict) -> str:
|
||||
"""IrwinID when the feed has one, else a stable name|state|discovered key."""
|
||||
extra = marker.get("extra") or {}
|
||||
for key in ("irwin_id", "unique_fire_id"):
|
||||
val = extra.get(key)
|
||||
if val:
|
||||
return str(val)
|
||||
name = marker.get("id") or marker.get("label") or "incident"
|
||||
state = extra.get("state") or ""
|
||||
discovered = extra.get("discovered") or ""
|
||||
return f"{name}|{state}|{discovered}"
|
||||
|
||||
|
||||
# Do not SELECT cameras.snapshot_url — that column is the agency/rtsp URL.
|
||||
_CAMERAS_INSIDE_SQL = """
|
||||
SELECT id::text AS id,
|
||||
COALESCE(location_name, '') AS name
|
||||
FROM cameras
|
||||
WHERE location_lat IS NOT NULL
|
||||
AND location_lon IS NOT NULL
|
||||
AND ST_Intersects(
|
||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
||||
ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326)
|
||||
)
|
||||
ORDER BY ST_Distance(
|
||||
ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326),
|
||||
ST_SetSRID(ST_MakePoint(:lon, :lat), 4326)
|
||||
)
|
||||
LIMIT :limit
|
||||
"""
|
||||
|
||||
_NEWS_INSIDE_SQL = """
|
||||
SELECT headline,
|
||||
COALESCE(url, '') AS url,
|
||||
COALESCE(importance, '') AS importance
|
||||
FROM news_items
|
||||
WHERE lat IS NOT NULL
|
||||
AND lon IS NOT NULL
|
||||
AND ST_Intersects(
|
||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
||||
ST_SetSRID(ST_MakePoint(lon, lat), 4326)
|
||||
)
|
||||
ORDER BY created_at DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
|
||||
_ALREADY_SQL = """
|
||||
SELECT 1
|
||||
FROM geofence_alerts
|
||||
WHERE geofence_id = CAST(:gid AS uuid)
|
||||
AND source_kind = :source_kind
|
||||
AND entity_id = :entity_id
|
||||
LIMIT 1
|
||||
"""
|
||||
|
||||
|
||||
async def _rows(sql: str, params: dict) -> list[dict]:
|
||||
async with async_session() as session:
|
||||
result = await session.execute(text(sql), params)
|
||||
return [dict(r) for r in result.mappings().all()]
|
||||
|
||||
|
||||
async def build_evidence(
|
||||
gid: str, *, lat: float, lon: float, now: datetime,
|
||||
) -> dict:
|
||||
"""Cameras nearest the hit (≤5) and news most-recent (≤3) inside the fence.
|
||||
|
||||
Empty arrays if none or the query fails. Snapshot is a path, not a body.
|
||||
"""
|
||||
cameras: list[dict] = []
|
||||
news: list[dict] = []
|
||||
try:
|
||||
cameras = await _rows(_CAMERAS_INSIDE_SQL, {
|
||||
"gid": gid, "lat": lat, "lon": lon, "limit": _CAMERA_CAP,
|
||||
})
|
||||
except Exception:
|
||||
logger.exception("evidence cameras query failed gid=%s", gid)
|
||||
try:
|
||||
news = await _rows(_NEWS_INSIDE_SQL, {"gid": gid, "limit": _NEWS_CAP})
|
||||
except Exception:
|
||||
logger.exception("evidence news query failed gid=%s", gid)
|
||||
return evidence_pack(gid, now, cameras, news)
|
||||
|
||||
|
||||
async def refresh_cache() -> list[dict]:
|
||||
global _cache
|
||||
async with async_session() as session:
|
||||
|
|
@ -417,24 +249,12 @@ async def record_and_notify(
|
|||
lat: float,
|
||||
lon: float,
|
||||
payload: dict[str, Any] | None = None,
|
||||
skip_existing: bool = False,
|
||||
) -> int:
|
||||
"""Insert a geofence_alerts row per hit and WS-push to viewport clients.
|
||||
|
||||
PostGIS ST_Intersects is the source of truth. The in-process GeoJSON
|
||||
cache is not a reject filter — the FIRMS ingester never fills it.
|
||||
|
||||
``source_kind=camera`` is refused (no row, no WS). Earthquake, fire
|
||||
incident, and news hits get an ``evidence`` object; adsb/ais/firms
|
||||
keep the caller payload unchanged.
|
||||
|
||||
``skip_existing`` is for polled incidents (same id every cycle). It
|
||||
does not change the 5-minute cooldown. A failed existence check
|
||||
skips the hit so a broken read cannot page every fence.
|
||||
"""
|
||||
if source_kind == "camera":
|
||||
logger.warning("refusing geofence notify for source_kind=camera")
|
||||
return 0
|
||||
hits = await st_intersects(lon, lat)
|
||||
if not hits:
|
||||
return 0
|
||||
|
|
@ -455,33 +275,6 @@ async def record_and_notify(
|
|||
hits = fresh
|
||||
async with async_session() as session:
|
||||
for fence in hits:
|
||||
once_key = (str(fence["id"]), source_kind, str(entity_id))
|
||||
if skip_existing:
|
||||
if once_key in _notified_once:
|
||||
continue
|
||||
try:
|
||||
existing = await session.execute(
|
||||
text(_ALREADY_SQL),
|
||||
{
|
||||
"gid": fence["id"],
|
||||
"source_kind": source_kind,
|
||||
"entity_id": str(entity_id),
|
||||
},
|
||||
)
|
||||
if existing.first() is not None:
|
||||
_notified_once.add(once_key)
|
||||
continue
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"geofence existing-hit check failed kind=%s entity=%s",
|
||||
source_kind, entity_id,
|
||||
)
|
||||
continue
|
||||
body_payload = dict(payload or {})
|
||||
if source_kind in EVIDENCE_KINDS:
|
||||
body_payload["evidence"] = await build_evidence(
|
||||
str(fence["id"]), lat=lat, lon=lon, now=now,
|
||||
)
|
||||
aid = str(uuid4())
|
||||
body = {
|
||||
"id": aid,
|
||||
|
|
@ -491,7 +284,7 @@ async def record_and_notify(
|
|||
"entity_id": str(entity_id),
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"payload": body_payload,
|
||||
"payload": payload or {},
|
||||
"created_at": now.isoformat(),
|
||||
}
|
||||
try:
|
||||
|
|
@ -513,7 +306,7 @@ async def record_and_notify(
|
|||
"entity_id": str(entity_id),
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"payload": json.dumps(body_payload),
|
||||
"payload": json.dumps(payload or {}),
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
|
|
@ -521,324 +314,8 @@ async def record_and_notify(
|
|||
sent += await manager.publish_point(
|
||||
"geofence_alert", body, lat=lat, lon=lon,
|
||||
)
|
||||
if skip_existing:
|
||||
_notified_once.add(once_key)
|
||||
try:
|
||||
await session.commit()
|
||||
except Exception:
|
||||
pass
|
||||
return sent
|
||||
|
||||
|
||||
async def list_alerts(
|
||||
*,
|
||||
geofence_id: str | None = None,
|
||||
since: datetime | None = None,
|
||||
until: datetime | None = None,
|
||||
source_kind: str | None = None,
|
||||
limit: int = 100,
|
||||
) -> list[dict]:
|
||||
"""Filterable hit log. Empty list if the DB is down — never raises."""
|
||||
where = ["TRUE"]
|
||||
params: dict[str, Any] = {"limit": int(limit)}
|
||||
if geofence_id:
|
||||
where.append("geofence_id = CAST(:geofence_id AS uuid)")
|
||||
params["geofence_id"] = geofence_id
|
||||
if since is not None:
|
||||
where.append("created_at >= :since")
|
||||
params["since"] = since
|
||||
if until is not None:
|
||||
where.append("created_at <= :until")
|
||||
params["until"] = until
|
||||
if source_kind:
|
||||
where.append("source_kind = :source_kind")
|
||||
params["source_kind"] = source_kind
|
||||
sql = f"""
|
||||
SELECT id::text, geofence_id::text, source_kind, entity_id,
|
||||
lat, lon, payload, created_at
|
||||
FROM geofence_alerts
|
||||
WHERE {' AND '.join(where)}
|
||||
ORDER BY created_at DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
try:
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(text(sql), params)).mappings().all()
|
||||
out = []
|
||||
for r in rows:
|
||||
item = dict(r)
|
||||
if item.get("created_at") is not None:
|
||||
item["created_at"] = item["created_at"].isoformat()
|
||||
out.append(item)
|
||||
return out
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
async def get_geofence(gid: str) -> dict | None:
|
||||
current = next((f for f in _cache if f["id"] == gid), None)
|
||||
if current is not None:
|
||||
return current
|
||||
try:
|
||||
await refresh_cache()
|
||||
except Exception:
|
||||
return None
|
||||
return next((f for f in _cache if f["id"] == gid), None)
|
||||
|
||||
|
||||
def _marker_from_track(row) -> dict:
|
||||
from live_layers import to_marker
|
||||
|
||||
extra = {"bucket": row["bucket"].isoformat() if row.get("bucket") else None, "dvr": True}
|
||||
return to_marker(
|
||||
row["id"], row["lat"], row["lon"],
|
||||
heading=row.get("heading"), speed=row.get("speed"),
|
||||
label=row.get("label") or row["id"],
|
||||
extra=extra,
|
||||
)
|
||||
|
||||
|
||||
async def _cagg_inside(gid: str, kind: str, bucket: datetime, limit: int = 2000) -> list[dict]:
|
||||
table = "aircraft_tracks_1min" if kind == "aircraft" else "vessel_tracks_1min"
|
||||
id_col = "hex" if kind == "aircraft" else "mmsi"
|
||||
sql = f"""
|
||||
SELECT {id_col} AS id, lat, lon, heading, speed, label, bucket
|
||||
FROM {table}
|
||||
WHERE bucket = :bucket
|
||||
AND ST_Intersects(
|
||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
||||
ST_SetSRID(ST_MakePoint(lon, lat), 4326)
|
||||
)
|
||||
LIMIT :limit
|
||||
"""
|
||||
try:
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
text(sql), {"bucket": bucket, "gid": gid, "limit": limit},
|
||||
)).mappings().all()
|
||||
return [
|
||||
_marker_from_track(r)
|
||||
for r in rows
|
||||
if r["lat"] is not None and r["lon"] is not None
|
||||
]
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
async def _fires_inside(gid: str, ts: datetime, limit: int = 2000) -> list[dict]:
|
||||
from tracks import minute_bucket
|
||||
|
||||
bucket = minute_bucket(ts)
|
||||
t1 = bucket + timedelta(minutes=1)
|
||||
sql = """
|
||||
SELECT latitude, longitude, brightness, confidence, acq_time, satellite,
|
||||
instrument, bright_ti5, frp, daynight
|
||||
FROM fires
|
||||
WHERE acq_time >= :t0 AND acq_time < :t1
|
||||
AND ST_Intersects(
|
||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
||||
ST_SetSRID(ST_MakePoint(longitude, latitude), 4326)
|
||||
)
|
||||
LIMIT :limit
|
||||
"""
|
||||
try:
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
text(sql),
|
||||
{"t0": bucket, "t1": t1, "gid": gid, "limit": limit},
|
||||
)).mappings().all()
|
||||
out = []
|
||||
for r in rows:
|
||||
item = dict(r)
|
||||
if item.get("acq_time") is not None:
|
||||
item["acq_time"] = item["acq_time"].isoformat()
|
||||
out.append(item)
|
||||
return out
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
async def snapshot_at(gid: str, ts: datetime) -> dict | None:
|
||||
"""Positions inside the fence at time T. None if the fence is missing.
|
||||
|
||||
Does not persist or notify. Empty lists if track/fire queries fail.
|
||||
"""
|
||||
fence = await get_geofence(gid)
|
||||
if fence is None:
|
||||
return None
|
||||
from tracks import minute_bucket
|
||||
|
||||
bucket = minute_bucket(ts)
|
||||
aircraft = await _cagg_inside(gid, "aircraft", bucket)
|
||||
vessels = await _cagg_inside(gid, "vessel", bucket)
|
||||
fires = await _fires_inside(gid, ts)
|
||||
return {
|
||||
"geofence_id": gid,
|
||||
"timestamp": ts.isoformat(),
|
||||
"aircraft": aircraft,
|
||||
"vessels": vessels,
|
||||
"fires": fires,
|
||||
}
|
||||
|
||||
|
||||
_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
|
||||
|
|
|
|||
|
|
@ -20,11 +20,6 @@ from sources import event_dedup_key
|
|||
|
||||
logger = logging.getLogger("osint.ingestor")
|
||||
|
||||
# asyncpg rejects statements with >32767 bind params. A FIRMS poll is ~90k
|
||||
# rows × 14 columns. Chunk inserts; still one transaction / one commit.
|
||||
FIRE_ROW_BIND_PARAMS = 14
|
||||
FIRE_INSERT_CHUNK = 2000
|
||||
|
||||
# NATS connection settings
|
||||
NATS_URLS = NATS_URL
|
||||
NATS_STREAM = "events"
|
||||
|
|
@ -131,18 +126,15 @@ async def ingest_fire_rows(msgs: list[dict]) -> int:
|
|||
rows.append(row)
|
||||
if not rows:
|
||||
return 0
|
||||
inserted = 0
|
||||
async with async_session() as session:
|
||||
for i in range(0, len(rows), FIRE_INSERT_CHUNK):
|
||||
chunk = rows[i:i + FIRE_INSERT_CHUNK]
|
||||
stmt = (
|
||||
pg_insert(fires_table)
|
||||
.values(chunk)
|
||||
.values(rows)
|
||||
.on_conflict_do_nothing(constraint="pk_fires_natural_key")
|
||||
)
|
||||
result = await session.execute(stmt)
|
||||
inserted += int(result.rowcount or 0)
|
||||
await session.commit()
|
||||
inserted = int(result.rowcount or 0)
|
||||
if inserted:
|
||||
logger.info("bulk ingested %d/%d FIRMS hotspots", inserted, len(rows))
|
||||
from live_layers import aircraft_last_known
|
||||
|
|
@ -213,38 +205,15 @@ async def ingest_event(msg: dict):
|
|||
claimed = await session.execute(dedup)
|
||||
if not claimed.rowcount:
|
||||
await session.commit()
|
||||
logger.debug("skip duplicate event url=%s", key)
|
||||
logger.info("skip duplicate event url=%s", key)
|
||||
return None
|
||||
result = await session.execute(events_table.insert().values(**event_row))
|
||||
await session.commit()
|
||||
event_id = result.inserted_primary_key[0] # type: ignore[union-attr]
|
||||
logger.info("Ingested event %s from source %s", event_id, msg.get("source_type"))
|
||||
# Cameras are persisted as events only. Never a geofence hit.
|
||||
if event_row["source_type"] == "earthquake":
|
||||
await _notify_earthquake(event_row, event_id)
|
||||
return event_id
|
||||
|
||||
|
||||
async def _notify_earthquake(event_row: dict, event_id) -> None:
|
||||
"""One hit per new quake. Dedup already dropped replays; skip if no point."""
|
||||
lat, lon = event_row.get("location_lat"), event_row.get("location_lon")
|
||||
if lat is None or lon is None:
|
||||
return
|
||||
try:
|
||||
from geofence import earthquake_entity_id, record_and_notify
|
||||
row = {**event_row, "id": str(event_id)}
|
||||
await record_and_notify(
|
||||
source_kind="earthquake",
|
||||
entity_id=earthquake_entity_id(row),
|
||||
lat=float(lat),
|
||||
lon=float(lon),
|
||||
payload={"title": event_row.get("title"), "url": event_row.get("url") or ""},
|
||||
skip_existing=True,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("earthquake geofence notify failed")
|
||||
|
||||
|
||||
async def start_nats_consumer():
|
||||
"""Start NATS JetStream consumer for OSINT events."""
|
||||
nc = await nats.connect(NATS_URLS)
|
||||
|
|
|
|||
|
|
@ -68,15 +68,10 @@ KEY_REGISTRY: dict[str, dict] = {
|
|||
"example": "123456789:AA… (bot token from @BotFather)",
|
||||
},
|
||||
"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,}$",
|
||||
"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": {
|
||||
"description": "OpenSky OAuth client id — optional ADS-B fallback (unused until enabled).",
|
||||
"example": "client id from opensky-network.org account",
|
||||
|
|
|
|||
|
|
@ -15,22 +15,18 @@ import asyncio
|
|||
import logging
|
||||
import math
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Awaitable, Callable
|
||||
|
||||
import httpx
|
||||
from urllib.parse import quote, urlencode
|
||||
|
||||
from config import OSINT_USER_AGENT, TITILER_PUBLIC_BASE
|
||||
from config import OSINT_USER_AGENT
|
||||
|
||||
logger = logging.getLogger("osint.live_layers")
|
||||
|
||||
MARKER_FIELDS = ("id", "lat", "lon", "heading", "speed", "label", "extra")
|
||||
|
||||
ADSB_LOL_BASE = "https://api.adsb.lol"
|
||||
PLANESPOTTERS_PHOTO = "https://api.planespotters.net/pub/photos"
|
||||
# Planespotters ToS cap server-side JSON caching at 24 hours.
|
||||
PLANESPOTTERS_CACHE_TTL = 24 * 3600
|
||||
AMTRAKER_TRAINS = "https://api.amtraker.com/v3/trains"
|
||||
RAINVIEWER_MAPS = "https://api.rainviewer.com/public/weather-maps.json"
|
||||
NWS_ALERTS = "https://api.weather.gov/alerts/active"
|
||||
|
|
@ -45,24 +41,6 @@ WFIGS_PERIMETERS = (
|
|||
)
|
||||
NHC_STORMS = "https://www.nhc.noaa.gov/CurrentStorms.json"
|
||||
|
||||
PC_STAC_SEARCH = "https://planetarycomputer.microsoft.com/api/stac/v1/search"
|
||||
PC_SAS_TOKEN = "https://planetarycomputer.microsoft.com/api/sas/v1/token/sentinel-1-grd"
|
||||
# Self-hosted TiTiler on the Pi, exposed same-origin through the osint.rpi.local
|
||||
# nginx vhost. Relative template — Leaflet resolves it against the page origin,
|
||||
# so the browser never touches a raw loopback port or titiler.xyz.
|
||||
TITILER_COG_TILES = f"{TITILER_PUBLIC_BASE}/cog/tiles/WebMercatorQuad/{{z}}/{{x}}/{{y}}"
|
||||
SENTINEL1_TTL = 6 * 3600 # S-1 revisit is 6–12 days; cache the COG all afternoon
|
||||
SENTINEL1_CELL = 2.0 # degrees — pan/zoom inside a cell reuses the same scene
|
||||
SENTINEL1_STAC_LIMIT = 8
|
||||
SENTINEL1_ATTRIBUTION = "Copernicus Sentinel-1 / Microsoft Planetary Computer"
|
||||
|
||||
# GPSJAM (John Wiseman / ADS-B Exchange): daily H3 hexes of aircraft nav
|
||||
# accuracy. Hexes are published as a gzip CSV at a stable per-date URL, soon
|
||||
# after midnight UTC. Red/yellow != proven jamming.
|
||||
GPSJAM_BASE = "https://gpsjam.org"
|
||||
GPSJAM_RES = 4
|
||||
GPSJAM_TTL = 3600.0 # 1h — whole-world layer, fetched once per day effectively
|
||||
|
||||
IEM_NEXRAD = "https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q/{z}/{x}/{y}.png"
|
||||
GIBS_THERMAL = (
|
||||
"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
|
||||
|
|
@ -97,11 +75,6 @@ _MAX_VESSELS = 6000
|
|||
# Last ADS-B snapshot + WFIGS points for fire↔tanker correlation.
|
||||
aircraft_last_known: dict[str, dict] = {}
|
||||
fire_last_known: list[dict] = []
|
||||
# Last-known counts for the cheap GET /api/stats HUD counter. Updated by the
|
||||
# upstream fetchers so the stats endpoint never does its own network/SQL fan-out
|
||||
# for these layers; reads are O(1) in-process.
|
||||
train_count: int = 0
|
||||
nws_alert_count: int = 0
|
||||
|
||||
|
||||
def overlay_catalog() -> dict:
|
||||
|
|
@ -133,15 +106,6 @@ def overlay_catalog() -> dict:
|
|||
"maxZoom": 9,
|
||||
"attribution": "NASA GIBS / EOSDIS",
|
||||
},
|
||||
"sentinel1_sar": {
|
||||
"id": "sentinel1_sar",
|
||||
"title": "Sentinel-1 SAR (Cloud-Penetrating)",
|
||||
"kind": "raster",
|
||||
"tileUrl": None, # filled from /api/map/sentinel1 (signed COG)
|
||||
"endpoint": "/api/map/sentinel1",
|
||||
"maxZoom": 14,
|
||||
"attribution": SENTINEL1_ATTRIBUTION,
|
||||
},
|
||||
"nws_alerts": {"id": "nws_alerts", "kind": "geojson", "endpoint": "/api/weather-alerts"},
|
||||
"wfigs_incidents": {"id": "wfigs_incidents", "kind": "points", "endpoint": "/api/fire-incidents"},
|
||||
"wfigs_perimeters": {"id": "wfigs_perimeters", "kind": "geojson", "endpoint": "/api/fire-perimeters"},
|
||||
|
|
@ -149,30 +113,6 @@ def overlay_catalog() -> dict:
|
|||
"vessels": {"id": "vessels", "kind": "points", "endpoint": "/api/vessels"},
|
||||
"trains": {"id": "trains", "kind": "points", "endpoint": "/api/trains"},
|
||||
"storms": {"id": "storms", "kind": "points", "endpoint": "/api/storms"},
|
||||
"gpsjam": {
|
||||
"id": "gpsjam",
|
||||
"kind": "geojson",
|
||||
"endpoint": "/api/map/gpsjam",
|
||||
"attribution": "GPSJAM / John Wiseman / ADS-B Exchange",
|
||||
},
|
||||
"satellites": {
|
||||
"id": "satellites",
|
||||
"kind": "points",
|
||||
"endpoint": "/api/satellites",
|
||||
"attribution": "CelesTrak (GP JSON / SGP4)",
|
||||
},
|
||||
"infra_nuclear": {
|
||||
"id": "infra_nuclear",
|
||||
"kind": "points",
|
||||
"endpoint": "/api/infrastructure?types=nuclear",
|
||||
"attribution": "OpenStreetMap contributors / Overpass API",
|
||||
},
|
||||
"conflicts": {
|
||||
"id": "conflicts",
|
||||
"kind": "points",
|
||||
"endpoint": "/api/conflicts",
|
||||
"attribution": "Curated OSINT conflict catalog",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -743,6 +683,9 @@ def transform_wfigs_incidents(fc: dict | None) -> list[dict]:
|
|||
continue
|
||||
props = feat.get("properties") or {}
|
||||
name = str(props.get("IncidentName") or "Incident").strip()
|
||||
out.append(to_marker(
|
||||
name, lat, lon,
|
||||
label=name,
|
||||
extra={
|
||||
"acres": props.get("IncidentSize"),
|
||||
"contained": props.get("PercentContained"),
|
||||
|
|
@ -751,17 +694,7 @@ def transform_wfigs_incidents(fc: dict | None) -> list[dict]:
|
|||
"cause": props.get("FireCause"),
|
||||
"discovered": props.get("FireDiscoveryDateTime"),
|
||||
"src": "wfigs",
|
||||
}
|
||||
irwin = props.get("IrwinID")
|
||||
if irwin:
|
||||
extra["irwin_id"] = str(irwin)
|
||||
ufi = props.get("UniqueFireIdentifier")
|
||||
if ufi:
|
||||
extra["unique_fire_id"] = str(ufi)
|
||||
out.append(to_marker(
|
||||
name, lat, lon,
|
||||
label=name,
|
||||
extra=extra,
|
||||
},
|
||||
))
|
||||
return out
|
||||
|
||||
|
|
@ -814,18 +747,6 @@ def _headers() -> dict[str, str]:
|
|||
return {"User-Agent": OSINT_USER_AGENT, "Accept": "application/json"}
|
||||
|
||||
|
||||
def _planespotters_headers() -> dict[str, str]:
|
||||
"""Planespotters 403s server clients whose UA has no contact URL/email."""
|
||||
ua = (OSINT_USER_AGENT or "").strip()
|
||||
if ua and ("@" in ua or "http://" in ua.lower() or "https://" in ua.lower()):
|
||||
return {"User-Agent": ua, "Accept": "application/json"}
|
||||
base = ua or "osint-dashboard/1.0"
|
||||
return {
|
||||
"User-Agent": f"{base} ([email protected])",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
|
||||
async def _lock_for(key: str) -> asyncio.Lock:
|
||||
async with _key_locks_guard:
|
||||
lock = _key_locks.get(key)
|
||||
|
|
@ -869,72 +790,19 @@ async def close_http() -> None:
|
|||
_http = None
|
||||
|
||||
|
||||
async def _get_json(
|
||||
url: str, params: dict | None = None, headers: dict | None = None,
|
||||
) -> Any:
|
||||
async def _get_json(url: str, params: dict | None = None) -> Any:
|
||||
if _http is None:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=_HTTP_TIMEOUT, follow_redirects=True, headers=_headers(),
|
||||
) as client:
|
||||
resp = await client.get(url, params=params, headers=headers)
|
||||
resp = await client.get(url, params=params)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
resp = await _http.get(url, params=params, headers=headers)
|
||||
resp = await _http.get(url, params=params)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _normalize_planespotter_photo(photo: dict) -> dict | None:
|
||||
"""Slim a planespotters.net photo object for the aircraft popup.
|
||||
|
||||
Image binaries are never proxied/re-hosted: we return the CDN ``src``
|
||||
and the browser loads it directly (per ToS).
|
||||
"""
|
||||
if not isinstance(photo, dict):
|
||||
return None
|
||||
large = photo.get("thumbnail_large") or {}
|
||||
small = photo.get("thumbnail") or {}
|
||||
src = large.get("src") or small.get("src")
|
||||
if not src:
|
||||
return None
|
||||
size = large.get("size") or small.get("size") or {}
|
||||
return {
|
||||
"id": str(photo.get("id") or ""),
|
||||
"src": src,
|
||||
"width": size.get("width"),
|
||||
"height": size.get("height"),
|
||||
"link": photo.get("link") or "",
|
||||
"photographer": photo.get("photographer") or "",
|
||||
}
|
||||
|
||||
|
||||
async def fetch_planespotters_photo(
|
||||
hex_code: str | None = None, reg: str | None = None,
|
||||
) -> dict | None:
|
||||
"""Latest photo for an aircraft from planespotters.net (hex preferred).
|
||||
|
||||
Server-side only: planespotters 403s any request carrying an ``Origin``
|
||||
header (browser fetch() always sends one), so the browser can never reach
|
||||
it directly. We fetch here with the identifying UA, cache the JSON ≤24h,
|
||||
and hand the CDN image URL back for the browser to load.
|
||||
"""
|
||||
if hex_code:
|
||||
key = f"psp-hex:{hex_code.strip().lower()}"
|
||||
url = f"{PLANESPOTTERS_PHOTO}/hex/{quote(hex_code.strip())}"
|
||||
elif reg:
|
||||
key = f"psp-reg:{reg.strip().lower()}"
|
||||
url = f"{PLANESPOTTERS_PHOTO}/reg/{quote(reg.strip())}"
|
||||
else:
|
||||
return None
|
||||
|
||||
async def _load() -> dict | None:
|
||||
data = await _get_json(url, headers=_planespotters_headers())
|
||||
photos = data.get("photos") or []
|
||||
return _normalize_planespotter_photo(photos[0]) if photos else None
|
||||
|
||||
return await _ttl_get(key, PLANESPOTTERS_CACHE_TTL, _load)
|
||||
|
||||
|
||||
async def fetch_aircraft(
|
||||
bbox: str, limit: int = DEFAULT_LIMIT, persist: bool = False,
|
||||
) -> list[dict]:
|
||||
|
|
@ -996,24 +864,16 @@ async def fetch_trains(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dic
|
|||
return transform_amtraker(await _get_json(AMTRAKER_TRAINS))
|
||||
|
||||
rows = await _ttl_get("amtraker:trains", 20.0, _load)
|
||||
global train_count
|
||||
train_count = len(rows)
|
||||
if bbox:
|
||||
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
|
||||
return filter_points_bbox(rows, minlon, minlat, maxlon, maxlat, limit)
|
||||
return rows[:limit]
|
||||
|
||||
|
||||
async def fetch_vessels(
|
||||
bbox: str | None,
|
||||
limit: int = DEFAULT_LIMIT,
|
||||
src: str | None = None,
|
||||
) -> list[dict]:
|
||||
async def fetch_vessels(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]:
|
||||
async with vessel_lock:
|
||||
rows = [dict(v) for v in vessel_last_known.values()
|
||||
if v.get("lat") is not None and v.get("lon") is not None]
|
||||
if src and src != "all":
|
||||
rows = [r for r in rows if (r.get("extra") or {}).get("src") == src]
|
||||
if bbox:
|
||||
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
|
||||
return filter_points_bbox(rows, minlon, minlat, maxlon, maxlat, limit)
|
||||
|
|
@ -1046,18 +906,8 @@ async def upsert_vessel(marker: dict) -> None:
|
|||
vessel_last_known[vid] = stored
|
||||
if len(vessel_last_known) > _MAX_VESSELS:
|
||||
excess = len(vessel_last_known) - int(_MAX_VESSELS * 0.9)
|
||||
# AISStream's live US-coast feed can crowd the shared store past
|
||||
# _MAX_VESSELS and evict the Hormuz VesselAPI rows (refreshed only
|
||||
# every VESSELAPI_INTERVAL) as "oldest". Keep src=vesselapi rows
|
||||
# resident so the blind-spot box stays visible between polls.
|
||||
evictable = [
|
||||
k for k, v in vessel_last_known.items()
|
||||
if (v.get("extra") or {}).get("src") != "vesselapi"
|
||||
]
|
||||
if len(evictable) < excess:
|
||||
excess = len(evictable)
|
||||
oldest = sorted(
|
||||
evictable,
|
||||
vessel_last_known,
|
||||
key=lambda k: vessel_last_known[k].get("seen_at", ""),
|
||||
)[:excess]
|
||||
for k in oldest:
|
||||
|
|
@ -1091,27 +941,17 @@ def _wfigs_params(bbox: str | None, *, offset_m: float = 250.0) -> dict:
|
|||
return params
|
||||
|
||||
|
||||
_WFIGS_INCIDENT_FIELDS = (
|
||||
"IncidentName,IncidentSize,FireDiscoveryDateTime,POOState,"
|
||||
"PercentContained,IncidentTypeCategory,FireCause,"
|
||||
"IrwinID,UniqueFireIdentifier"
|
||||
)
|
||||
|
||||
|
||||
async def load_fire_incidents(bbox: str | None) -> list[dict]:
|
||||
"""WFIGS points for a bbox. No last-known mutation, no aircraft correlate."""
|
||||
async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]:
|
||||
params = _wfigs_params(bbox)
|
||||
params["outFields"] = _WFIGS_INCIDENT_FIELDS
|
||||
params["outFields"] = (
|
||||
"IncidentName,IncidentSize,FireDiscoveryDateTime,POOState,"
|
||||
"PercentContained,IncidentTypeCategory,FireCause"
|
||||
)
|
||||
|
||||
async def _load():
|
||||
return transform_wfigs_incidents(await _get_json(WFIGS_INCIDENTS, params))
|
||||
|
||||
rows = await _ttl_get(f"wfigs:inc:{bbox_cell_key(bbox)}", 600.0, _load)
|
||||
return list(rows or [])
|
||||
|
||||
|
||||
async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]:
|
||||
rows = await load_fire_incidents(bbox)
|
||||
fire_last_known[:] = list(rows)
|
||||
if rows and aircraft_last_known:
|
||||
from fire_aircraft import correlate_and_notify
|
||||
|
|
@ -1161,8 +1001,6 @@ async def fetch_weather_alerts(area: str | None, bbox: str | None) -> dict:
|
|||
logger.warning("NWS alerts fetch failed: %s", exc)
|
||||
nws_ok = False
|
||||
nws_fc = {"features": []}
|
||||
global nws_alert_count
|
||||
nws_alert_count = len(nws_fc.get("features") or [])
|
||||
sbw_fc = await _ttl_get("iem:sbw", 45.0, _load_iem)
|
||||
features = []
|
||||
for feat in nws_fc.get("features") or []:
|
||||
|
|
@ -1229,348 +1067,3 @@ async def fetch_storms() -> list[dict]:
|
|||
return transform_nhc_storms(await _get_json(NHC_STORMS))
|
||||
|
||||
return await _ttl_get("nhc:storms", 300.0, _load)
|
||||
|
||||
|
||||
# ── Sentinel-1 SAR (Planetary Computer STAC → signed COG tile template) ────
|
||||
|
||||
class UpstreamRateLimited(Exception):
|
||||
"""Planetary Computer returned 429. Carries Retry-After for the client."""
|
||||
|
||||
def __init__(self, retry_after: str | None = None):
|
||||
self.retry_after = retry_after
|
||||
super().__init__("planetary computer rate limited")
|
||||
|
||||
|
||||
async def _post_json(
|
||||
url: str, json: dict | None = None, headers: dict | None = None,
|
||||
) -> Any:
|
||||
if _http is None:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=_HTTP_TIMEOUT, follow_redirects=True, headers=_headers(),
|
||||
) as client:
|
||||
resp = await client.post(url, json=json, headers=headers)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
resp = await _http.post(url, json=json, headers=headers)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def _pc_call(coro: Awaitable[Any]) -> Any:
|
||||
"""Run a Planetary Computer call, mapping 429 → UpstreamRateLimited."""
|
||||
try:
|
||||
return await coro
|
||||
except httpx.HTTPStatusError as exc:
|
||||
if exc.response.status_code == 429:
|
||||
raise UpstreamRateLimited(
|
||||
exc.response.headers.get("Retry-After")
|
||||
) from exc
|
||||
raise
|
||||
|
||||
|
||||
def sign_cog_url(href: str, token: str) -> str:
|
||||
"""Append a SAS token to a PC blob URL (respect existing query string).
|
||||
|
||||
PC's SAS endpoint returns the token as an already-percent-encoded query
|
||||
string (``st=…&se=…&sp=rl&…&sig=…``). Azure only honours those parameters
|
||||
when they sit top-level on the blob URL — wrapping them under a single
|
||||
``token=`` param yields 403/409, so we append the token verbatim.
|
||||
"""
|
||||
sep = "&" if "?" in href else "?"
|
||||
return f"{href}{sep}{token}"
|
||||
|
||||
|
||||
def sentinel1_tile_url(signed_cog: str) -> str:
|
||||
"""TiTiler XYZ template for a signed COG (Leaflet substitutes {z}/{x}/{y})."""
|
||||
params = urlencode({
|
||||
"url": signed_cog,
|
||||
"rescale": "0,500",
|
||||
"colormap_name": "cfastie",
|
||||
})
|
||||
return f"{TITILER_COG_TILES}?{params}"
|
||||
|
||||
|
||||
def feature_bbox(feat: dict) -> list[float] | None:
|
||||
"""STAC Feature bbox as [minlon, minlat, maxlon, maxlat], or None."""
|
||||
raw = feat.get("bbox") if isinstance(feat, dict) else None
|
||||
if isinstance(raw, (list, tuple)) and len(raw) >= 4:
|
||||
try:
|
||||
return [float(raw[0]), float(raw[1]), float(raw[2]), float(raw[3])]
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
geom = (feat or {}).get("geometry") or {}
|
||||
coords = geom.get("coordinates") if isinstance(geom, dict) else None
|
||||
if not coords:
|
||||
return None
|
||||
lons: list[float] = []
|
||||
lats: list[float] = []
|
||||
|
||||
def _walk(node: Any) -> None:
|
||||
if isinstance(node, (list, tuple)) and node and isinstance(node[0], (int, float)):
|
||||
lons.append(float(node[0]))
|
||||
lats.append(float(node[1]))
|
||||
elif isinstance(node, (list, tuple)):
|
||||
for child in node:
|
||||
_walk(child)
|
||||
|
||||
_walk(coords)
|
||||
if not lons:
|
||||
return None
|
||||
return [min(lons), min(lats), max(lons), max(lats)]
|
||||
|
||||
|
||||
def pick_sentinel_feature(features: list, lon: float, lat: float) -> dict | None:
|
||||
"""Prefer the scene whose bbox covers the viewport center; else first."""
|
||||
if not features:
|
||||
return None
|
||||
for feat in features:
|
||||
bb = feature_bbox(feat)
|
||||
if bb and bb[0] <= lon <= bb[2] and bb[1] <= lat <= bb[3]:
|
||||
return feat
|
||||
return features[0]
|
||||
|
||||
|
||||
async def fetch_sentinel1(bbox: str) -> dict | None:
|
||||
"""Most recent Sentinel-1 GRD COG for a viewport, signed and TiTiler-ready.
|
||||
|
||||
Returns the overlay tile-template dict, or ``None`` when no GRD imagery
|
||||
covers the bbox in the last 7 days (caller maps to 404). Queries Planetary
|
||||
Computer only when called; cached per 2° cell + UTC day so pan/zoom inside
|
||||
the same region reuses the COG instead of picking a neighbouring swath.
|
||||
"""
|
||||
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
|
||||
qminlon, qminlat, qmaxlon, qmaxlat = quantize_bbox(
|
||||
minlon, minlat, maxlon, maxlat, step=SENTINEL1_CELL,
|
||||
)
|
||||
day = datetime.now(timezone.utc).date().isoformat()
|
||||
key = f"sentinel1:{day}:{qminlon:.4f},{qminlat:.4f},{qmaxlon:.4f},{qmaxlat:.4f}"
|
||||
clon = (qminlon + qmaxlon) / 2.0
|
||||
clat = (qminlat + qmaxlat) / 2.0
|
||||
|
||||
async def _load() -> dict | None:
|
||||
now = datetime.now(timezone.utc)
|
||||
week_ago = now - timedelta(days=7)
|
||||
payload = {
|
||||
"collections": ["sentinel-1-grd"],
|
||||
"bbox": [qminlon, qminlat, qmaxlon, qmaxlat],
|
||||
"datetime": f"{week_ago.isoformat()}/{now.isoformat()}",
|
||||
"limit": SENTINEL1_STAC_LIMIT,
|
||||
"sortby": [{"field": "datetime", "direction": "desc"}],
|
||||
}
|
||||
data = await _pc_call(_post_json(PC_STAC_SEARCH, json=payload))
|
||||
features = data.get("features") or []
|
||||
if not features:
|
||||
return None
|
||||
|
||||
feat = pick_sentinel_feature(features, clon, clat)
|
||||
if not feat:
|
||||
return None
|
||||
assets = feat.get("assets") or {}
|
||||
chosen_href: str | None = None
|
||||
polarization: str | None = None
|
||||
for pol in ("vv", "hh"):
|
||||
href = (assets.get(pol) or {}).get("href")
|
||||
if href:
|
||||
chosen_href = href
|
||||
polarization = pol
|
||||
break
|
||||
if not chosen_href:
|
||||
return None
|
||||
|
||||
sas = await _pc_call(_get_json(PC_SAS_TOKEN))
|
||||
token = (sas or {}).get("token")
|
||||
if not token:
|
||||
raise RuntimeError("planetarycomputer SAS token missing")
|
||||
signed = sign_cog_url(chosen_href, token)
|
||||
|
||||
props = feat.get("properties") or {}
|
||||
return {
|
||||
"id": "sentinel-1-sar",
|
||||
"kind": "raster",
|
||||
"tileUrl": sentinel1_tile_url(signed),
|
||||
"opacity": 0.8,
|
||||
"itemId": feat.get("id"),
|
||||
"datetime": props.get("datetime") or feat.get("datetime"),
|
||||
"polarization": polarization,
|
||||
"attribution": SENTINEL1_ATTRIBUTION,
|
||||
"bbox": feature_bbox(feat),
|
||||
}
|
||||
|
||||
return await _ttl_get(key, float(SENTINEL1_TTL), _load)
|
||||
# ── GPSJAM ──────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def gpsjam_level(percent_bad: float) -> str:
|
||||
"""Map a denoised bad-aircraft percentage to GPSJAM's three tiers."""
|
||||
if percent_bad > 10.0:
|
||||
return "high"
|
||||
if percent_bad > 2.0:
|
||||
return "medium"
|
||||
return "low"
|
||||
|
||||
|
||||
def gpsjam_csv_to_geojson(text: str) -> dict:
|
||||
"""Convert a GPSJAM daily CSV to a world FeatureCollection of hex polygons.
|
||||
|
||||
Rows are ``hex,count_good_aircraft,count_bad_aircraft``. The interference
|
||||
percentage uses GPSJAM's published denoise formula
|
||||
``100 * (bad - 1) / (good + bad)``; hexes with zero bad aircraft are the
|
||||
"normal" background and are dropped (the base map already shows nothing).
|
||||
"""
|
||||
import csv
|
||||
import io
|
||||
|
||||
import h3
|
||||
|
||||
features = []
|
||||
for row in csv.DictReader(io.StringIO(text)):
|
||||
hex_id = (row.get("hex") or "").strip()
|
||||
if not hex_id:
|
||||
continue
|
||||
try:
|
||||
good = int(row.get("count_good_aircraft") or 0)
|
||||
bad = int(row.get("count_bad_aircraft") or 0)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if bad < 1:
|
||||
continue
|
||||
denom = good + bad
|
||||
percent = 100.0 * (bad - 1) / denom if denom > 0 else 0.0
|
||||
try:
|
||||
# h3 returns (lat, lng); GeoJSON needs (lng, lat) closed rings.
|
||||
ring = [[lng, lat] for lat, lng in h3.cell_to_boundary(hex_id)]
|
||||
except Exception: # malformed/unknown cell id — skip
|
||||
continue
|
||||
ring.append(ring[0])
|
||||
features.append({
|
||||
"type": "Feature",
|
||||
"geometry": {"type": "Polygon", "coordinates": [ring]},
|
||||
"properties": {
|
||||
"level": gpsjam_level(percent),
|
||||
"percent_bad": round(percent, 2),
|
||||
"good": good,
|
||||
"bad": bad,
|
||||
"hex": hex_id,
|
||||
},
|
||||
})
|
||||
return {"type": "FeatureCollection", "features": features}
|
||||
|
||||
|
||||
async def fetch_gpsjam(date: str) -> dict:
|
||||
"""Fetch + convert one GPSJAM daily hex layer (whole world, 1h TTL)."""
|
||||
url = f"{GPSJAM_BASE}/data/{date}-h3_{GPSJAM_RES}.csv"
|
||||
|
||||
async def _load():
|
||||
if _http is None:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=_HTTP_TIMEOUT, follow_redirects=True, headers=_headers(),
|
||||
) as client:
|
||||
resp = await client.get(url)
|
||||
resp.raise_for_status()
|
||||
return gpsjam_csv_to_geojson(resp.text)
|
||||
resp = await _http.get(url)
|
||||
resp.raise_for_status()
|
||||
return gpsjam_csv_to_geojson(resp.text)
|
||||
|
||||
return await _ttl_get(f"gpsjam:{date}", GPSJAM_TTL, _load)
|
||||
# ── Infrastructure (Overpass) ───────────────────────────────────────────────
|
||||
|
||||
|
||||
OVERPASS_INTERPRETER = "https://overpass-api.de/api/interpreter"
|
||||
# One in-flight query per quantized bbox (the per-key lock in _ttl_get). Overpass
|
||||
# asks for a 25s server timeout in-band; the client gives it 30s of headroom.
|
||||
OVERPASS_TIMEOUT = httpx.Timeout(30.0, connect=5.0)
|
||||
INFRA_TTL = 24 * 3600 # 24h per quantized bbox — static infrastructure
|
||||
|
||||
# `types=` enum. Nuclear ships first; military/hospital slot in behind the same
|
||||
# query template without touching the transport. Overpass bbox is
|
||||
# (south, west, north, east), i.e. (minlat, minlon, maxlat, maxlon).
|
||||
_INFRA_QUERIES: dict[str, str] = {
|
||||
"nuclear": (
|
||||
'[out:json][timeout:25];\n'
|
||||
'nwr["power"="plant"]["plant:source"="nuclear"]({bbox});\n'
|
||||
'out center;'
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def infra_query(type_: str, minlon: float, minlat: float, maxlon: float, maxlat: float) -> str:
|
||||
"""Render one Overpass query with the bbox substituted in south,west,north,east."""
|
||||
bbox = f"{minlat},{minlon},{maxlat},{maxlon}"
|
||||
return _INFRA_QUERIES[type_].replace("{bbox}", bbox)
|
||||
|
||||
|
||||
def normalize_infra_element(elem: dict, type_: str) -> dict | None:
|
||||
"""Map one Overpass element to ``{id, name, lat, lon, type, extra}``.
|
||||
|
||||
``out center`` gives nodes their own ``lat``/``lon`` and ways/relations a
|
||||
``center``. Elements with no usable coordinate are dropped.
|
||||
"""
|
||||
etype = elem.get("type")
|
||||
eid = elem.get("id")
|
||||
if eid is None:
|
||||
return None
|
||||
if etype == "node":
|
||||
lat, lon = elem.get("lat"), elem.get("lon")
|
||||
else:
|
||||
center = elem.get("center") or {}
|
||||
lat, lon = center.get("lat"), center.get("lon")
|
||||
if lat is None or lon is None:
|
||||
return None
|
||||
tags = elem.get("tags") or {}
|
||||
name = tags.get("name") or tags.get("ref") or f"{etype}/{eid}"
|
||||
extra = {k: v for k, v in tags.items() if k != "name"}
|
||||
return {
|
||||
"id": f"{etype}/{eid}",
|
||||
"name": name,
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"type": type_,
|
||||
"extra": extra,
|
||||
}
|
||||
|
||||
|
||||
def overpass_nuclear_to_markers(data: dict) -> list[dict]:
|
||||
"""Convert an Overpass JSON response to normalized nuclear markers."""
|
||||
markers = []
|
||||
for elem in data.get("elements") or []:
|
||||
marker = normalize_infra_element(elem, "nuclear")
|
||||
if marker is not None:
|
||||
markers.append(marker)
|
||||
return markers
|
||||
|
||||
|
||||
async def fetch_infrastructure(types: str, bbox: str) -> list[dict]:
|
||||
"""Fetch Overpass infrastructure markers, cached 24h per quantized bbox.
|
||||
|
||||
``types`` is a single supported enum value (``nuclear`` for now). ``bbox``
|
||||
is ``minlon,minlat,maxlon,maxlat``.
|
||||
"""
|
||||
requested = [t.strip() for t in types.split(",") if t.strip()]
|
||||
minlon, minlat, maxlon, maxlat = parse_bbox(bbox)
|
||||
key = f"infra:{','.join(requested)}:{bbox_cell_key(bbox)}"
|
||||
|
||||
async def _load() -> list[dict]:
|
||||
# One query per requested type, concatenated. Nuclear is the only type
|
||||
# today; the loop keeps the shape ready for military/hospital.
|
||||
out: list[dict] = []
|
||||
for type_ in requested:
|
||||
query = infra_query(type_, minlon, minlat, maxlon, maxlat)
|
||||
if _http is None:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=OVERPASS_TIMEOUT, follow_redirects=True,
|
||||
headers=_headers(),
|
||||
) as client:
|
||||
resp = await client.post(OVERPASS_INTERPRETER, data={"data": query})
|
||||
resp.raise_for_status()
|
||||
out.extend(overpass_nuclear_to_markers(resp.json()))
|
||||
else:
|
||||
resp = await _http.post(
|
||||
OVERPASS_INTERPRETER, data={"data": query},
|
||||
timeout=OVERPASS_TIMEOUT,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
out.extend(overpass_nuclear_to_markers(resp.json()))
|
||||
return out
|
||||
|
||||
return await _ttl_get(key, float(INFRA_TTL), _load)
|
||||
|
|
|
|||
706
app/main.py
706
app/main.py
|
|
@ -14,19 +14,14 @@ from __future__ import annotations
|
|||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from typing import NoReturn
|
||||
from urllib.parse import urlparse
|
||||
from uuid import UUID
|
||||
|
||||
import httpx
|
||||
import structlog
|
||||
from fastapi import FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||
from fastapi import BackgroundTasks, FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
|
@ -34,18 +29,16 @@ from sqlalchemy import and_, func, or_, select, text
|
|||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from database import async_session, init_extensions
|
||||
from auth import AdminAuthMiddleware, router as auth_router
|
||||
from models import (
|
||||
alerts, documents, entities, entity_events, events, feed_sources, fires,
|
||||
articles, article_scores, article_summaries, news_items,
|
||||
articles, article_summaries, news_items,
|
||||
)
|
||||
from schemas import (
|
||||
AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate,
|
||||
ConflictZoneOut, ConflictsOut,
|
||||
DashboardSummary, EntityCreate, EntityKind, EntityOut,
|
||||
EventCreate, EventOut, FireOut, NewsArticleOut, NewsBlipOut, NewsMapItemOut,
|
||||
EventCreate, EventOut, FireOut, NewsArticleOut, NewsMapItemOut,
|
||||
NewsSummaryOut, NewsTickerItemOut,
|
||||
FeedSourceCreate, FeedSourceOut, FeedSourceUpdate,
|
||||
FeedSourceCreate, FeedSourceOut,
|
||||
KeyOut, KeyValueIn,
|
||||
NewsModelsOut, SettingsIn, SettingsOut,
|
||||
SearchResult, SentimentSummary, SourceType,
|
||||
|
|
@ -53,20 +46,15 @@ from schemas import (
|
|||
GeofenceCreate, GeofenceUpdate,
|
||||
)
|
||||
from ingestor import ingest_event, fetch_and_process
|
||||
from camera_scraper import is_public_url
|
||||
from sources import GDELT_API, ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals
|
||||
from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals
|
||||
from fire_sources import ingest_fires
|
||||
from keystore import KeyFormatError, delete_key, list_keys, set_key
|
||||
from news_title import unwrap_cdata_title
|
||||
from settings_store import SettingsError, get_app_settings, list_models, set_summary_model
|
||||
from live_layers import (
|
||||
fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters,
|
||||
fetch_gpsjam, fetch_planespotters_photo, fetch_radar_meta, fetch_sentinel1,
|
||||
fetch_storms, fetch_trains, fetch_vessels, fetch_weather_alerts,
|
||||
fetch_infrastructure, overlay_catalog, parse_bbox, UpstreamRateLimited,
|
||||
fetch_radar_meta, fetch_storms, fetch_trains, fetch_vessels,
|
||||
fetch_weather_alerts, overlay_catalog, parse_bbox,
|
||||
)
|
||||
from satellites import fetch_satellites, parse_groups, DEFAULT_GROUPS
|
||||
from place import reverse_geocode
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = structlog.get_logger("osint.dashboard")
|
||||
|
|
@ -82,31 +70,18 @@ async def _lifespan(app: FastAPI):
|
|||
await refresh_cache()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from vesselapi import hydrate_last_known
|
||||
await hydrate_last_known()
|
||||
except Exception:
|
||||
pass
|
||||
from config import AISSTREAM_IN_APP, VESSELAPI_IN_APP
|
||||
from config import AISSTREAM_IN_APP
|
||||
ais_task = None
|
||||
vesselapi_task = None
|
||||
adsb_task = None
|
||||
if AISSTREAM_IN_APP:
|
||||
from ais_stream import run_ais_worker
|
||||
ais_task = asyncio.create_task(run_ais_worker())
|
||||
if VESSELAPI_IN_APP:
|
||||
from vesselapi import run_vesselapi_worker
|
||||
vesselapi_task = asyncio.create_task(run_vesselapi_worker())
|
||||
adsb_task = asyncio.create_task(_adsb_refresh_loop())
|
||||
yield
|
||||
if ais_task is not None:
|
||||
ais_task.cancel()
|
||||
if vesselapi_task is not None:
|
||||
vesselapi_task.cancel()
|
||||
if adsb_task is not None:
|
||||
adsb_task.cancel()
|
||||
from vesselapi import close_client
|
||||
await close_client()
|
||||
await close_http()
|
||||
|
||||
|
||||
|
|
@ -118,57 +93,17 @@ app = FastAPI(
|
|||
)
|
||||
app.add_middleware(GZipMiddleware, minimum_size=1024)
|
||||
|
||||
# Single-admin auth: deny-by-default on /api/* with an explicit public read
|
||||
# allowlist (app/auth.py), plus /login, /api/auth/{login,logout,me}.
|
||||
app.add_middleware(AdminAuthMiddleware)
|
||||
app.include_router(auth_router)
|
||||
|
||||
STATIC_DIR = Path(__file__).parent / "static"
|
||||
|
||||
|
||||
def _adsb_watch_boxes() -> list[tuple[float, float, float, float]]:
|
||||
"""Chokepoint presets as viewport boxes (minlon, minlat, maxlon, maxlat).
|
||||
|
||||
Used only while no browser viewport is registered: without it the refresh
|
||||
loop persists nothing and ``aircraft_positions`` silently stalls whenever
|
||||
nobody has the map open.
|
||||
"""
|
||||
from chokepoints import chokepoints
|
||||
|
||||
out: list[tuple[float, float, float, float]] = []
|
||||
for preset in chokepoints():
|
||||
try:
|
||||
# Preset bboxes are minlat,minlon,maxlat,maxlon (VesselAPI order).
|
||||
minlat, minlon, maxlat, maxlon = (float(v) for v in str(preset["bbox"]).split(","))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
out.append((minlon, minlat, maxlon, maxlat))
|
||||
return out
|
||||
|
||||
|
||||
async def _adsb_refresh_loop() -> None:
|
||||
"""Poll ADSB.lol for connected viewports — never from GET /api/aircraft.
|
||||
|
||||
When no client viewport is registered the loop sweeps the watch boxes
|
||||
(chokepoint presets) at ``ADSB_WATCH_INTERVAL`` so aircraft ingest keeps
|
||||
advancing with no map open.
|
||||
"""
|
||||
"""Poll ADSB.lol for connected viewports — never from GET /api/aircraft."""
|
||||
from ws_manager import manager
|
||||
from live_layers import fetch_aircraft
|
||||
from config import ADSB_REFRESH_INTERVAL, ADSB_WATCH_ENABLED, ADSB_WATCH_INTERVAL
|
||||
|
||||
watch_boxes: list[tuple[float, float, float, float]] | None = None
|
||||
|
||||
while True:
|
||||
interval = ADSB_REFRESH_INTERVAL
|
||||
try:
|
||||
boxes = manager.viewports()
|
||||
if not boxes and ADSB_WATCH_ENABLED:
|
||||
if watch_boxes is None:
|
||||
watch_boxes = _adsb_watch_boxes()
|
||||
boxes = watch_boxes
|
||||
interval = ADSB_WATCH_INTERVAL
|
||||
logger.debug("adsb_idle_watch", boxes=len(boxes))
|
||||
for box in boxes:
|
||||
bbox = f"{box[0]},{box[1]},{box[2]},{box[3]}"
|
||||
try:
|
||||
|
|
@ -177,7 +112,7 @@ async def _adsb_refresh_loop() -> None:
|
|||
logger.warning("adsb_refresh_failed", error=str(exc))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("adsb_refresh_loop", error=str(exc))
|
||||
await asyncio.sleep(interval)
|
||||
await asyncio.sleep(8)
|
||||
|
||||
|
||||
class CachedStaticFiles(StaticFiles):
|
||||
|
|
@ -308,14 +243,7 @@ async def _pipeline_checks(session) -> dict:
|
|||
|
||||
await _age("SELECT max(ingested_at) FROM events", "events", 20 * 60)
|
||||
await _age("SELECT max(ingested_at) FROM fires", "fires", 30 * 60)
|
||||
# Same closed-at-now window as GET /api/news. A future max() made age_s
|
||||
# negative and hid a fresh list. NULL timestamps are not fresh.
|
||||
await _age(
|
||||
"SELECT max(timestamp) FROM articles "
|
||||
"WHERE timestamp IS NOT NULL AND timestamp <= now()",
|
||||
"articles",
|
||||
2 * 3600,
|
||||
)
|
||||
await _age("SELECT max(timestamp) FROM articles", "articles", 2 * 3600)
|
||||
await _age("SELECT max(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600)
|
||||
return checks
|
||||
|
||||
|
|
@ -327,99 +255,6 @@ def overlay_json(data, max_age: int) -> JSONResponse:
|
|||
return resp
|
||||
|
||||
|
||||
# ── HUD counters ─────────────────────────────────────────────────────────
|
||||
|
||||
# Cheap ~100 B–2 KB counts for the layer rail. Cached in-process so the HUD
|
||||
# can poll every second without re-hitting SQL or upstream feeds.
|
||||
_STATS_TTL = 20.0
|
||||
_stats_cache: dict[str, tuple[float, dict]] = {}
|
||||
|
||||
|
||||
async def _stats_counts() -> dict:
|
||||
"""Fan out to in-memory last-known / cheap SQL counts. Never raises."""
|
||||
from live_layers import (
|
||||
aircraft_last_known, vessel_last_known, train_count, nws_alert_count,
|
||||
)
|
||||
|
||||
counts: dict = {
|
||||
"aircraft": len(aircraft_last_known),
|
||||
"vessels": len(vessel_last_known),
|
||||
"trains": train_count,
|
||||
"cameras": 0,
|
||||
"fires": 0,
|
||||
"quakes": 0,
|
||||
"alerts": nws_alert_count,
|
||||
}
|
||||
|
||||
# SQL counts are best-effort: a down DB or missing table must not 500 the
|
||||
# rail — the frontend still renders with zeros.
|
||||
try:
|
||||
from camera_models import cameras as cam_table
|
||||
async with async_session() as session:
|
||||
counts["cameras"] = int(
|
||||
(await session.execute(select(func.count()).select_from(cam_table))).scalar() or 0
|
||||
)
|
||||
counts["fires"] = int(
|
||||
(await session.execute(select(func.count()).select_from(fires))).scalar() or 0
|
||||
)
|
||||
counts["quakes"] = int(
|
||||
(await session.execute(
|
||||
select(func.count()).select_from(events).where(
|
||||
events.c.source_type == "earthquake"
|
||||
)
|
||||
)).scalar() or 0
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("stats_db_failed", error=str(exc))
|
||||
|
||||
counts["timestamp"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
# Public booleans only. Never include the stored value, a prefix, or last-4.
|
||||
counts["feeds"] = await _feed_flags()
|
||||
return counts
|
||||
|
||||
|
||||
async def _key_configured(*names: str) -> bool:
|
||||
"""True when any named key has a non-empty value in the api_keys store.
|
||||
|
||||
Uses keystore.get_api_key — not env, not a second store. The value is
|
||||
discarded after the emptiness check.
|
||||
"""
|
||||
from keystore import get_api_key
|
||||
|
||||
for name in names:
|
||||
value = await get_api_key(name)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
async def _feed_flags() -> dict:
|
||||
"""HUD layer flags. Fail closed (configured false) if the store is down."""
|
||||
try:
|
||||
vessels = await _key_configured("AISSTREAM_API_KEY", "VESSELAPI_API_KEY")
|
||||
fires = await _key_configured("FIRMS_MAP_KEY")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("stats_feed_flags_failed", error=str(exc))
|
||||
vessels = False
|
||||
fires = False
|
||||
return {
|
||||
"vessels": {"configured": vessels},
|
||||
"fires": {"configured": fires},
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/stats")
|
||||
async def api_stats():
|
||||
"""Cheap HUD counters (counts only — no GeoJSON). Cached ~20 s."""
|
||||
now = time.monotonic()
|
||||
cached = _stats_cache.get("stats")
|
||||
if cached and now - cached[0] < _STATS_TTL:
|
||||
return cached[1]
|
||||
payload = await _stats_counts()
|
||||
_stats_cache["stats"] = (now, payload)
|
||||
return overlay_json(payload, 15)
|
||||
|
||||
|
||||
# ── Feed Sources ──────────────────────────────────────────────────────────
|
||||
|
||||
@app.get("/api/sources", response_model=list[FeedSourceOut])
|
||||
|
|
@ -449,20 +284,18 @@ async def create_source(payload: FeedSourceCreate):
|
|||
|
||||
|
||||
@app.patch("/api/sources/{source_id}")
|
||||
async def update_source(source_id: UUID, payload: FeedSourceUpdate):
|
||||
"""Update a feed source (name/url/config/enabled only)."""
|
||||
values = payload.model_dump(exclude_unset=True)
|
||||
async def update_source(source_id: UUID, payload: dict):
|
||||
"""Update a feed source (e.g., toggle enabled)."""
|
||||
async with async_session() as session:
|
||||
row = (await session.execute(
|
||||
select(feed_sources).where(feed_sources.c.id == source_id)
|
||||
)).mappings().one_or_none()
|
||||
if not row:
|
||||
raise HTTPException(404, "Source not found")
|
||||
if values:
|
||||
await session.execute(
|
||||
feed_sources.update()
|
||||
.where(feed_sources.c.id == source_id)
|
||||
.values(**values)
|
||||
.values(**payload)
|
||||
)
|
||||
await session.commit()
|
||||
return {"ok": True}
|
||||
|
|
@ -907,15 +740,9 @@ async def put_settings(payload: SettingsIn):
|
|||
|
||||
# ── Ingestion Triggers ───────────────────────────────────────────────────
|
||||
|
||||
def _require_public_url(url: str, field: str) -> None:
|
||||
if not is_public_url(url):
|
||||
raise HTTPException(400, f"{field} is not a public URL")
|
||||
|
||||
|
||||
@app.post("/api/ingest/rss")
|
||||
async def trigger_rss_ingest(feed_url: str, source_id: str | None = None):
|
||||
"""Trigger RSS feed ingestion."""
|
||||
_require_public_url(feed_url, "feed_url")
|
||||
count = await ingest_rss_feed(feed_url, source_id)
|
||||
return {"status": "ok", "items_ingested": count}
|
||||
|
||||
|
|
@ -923,10 +750,6 @@ async def trigger_rss_ingest(feed_url: str, source_id: str | None = None):
|
|||
@app.post("/api/ingest/gdelt")
|
||||
async def trigger_gdelt_ingest(query: str = "", max_articles: int = 50):
|
||||
"""Trigger GDELT data ingestion."""
|
||||
_require_public_url(GDELT_API, "GDELT target")
|
||||
parsed = urlparse(query)
|
||||
if parsed.scheme in ("http", "https") and parsed.hostname:
|
||||
_require_public_url(query, "query")
|
||||
count = await ingest_gdelt(query, max_articles)
|
||||
return {"status": "ok", "articles_ingested": count}
|
||||
|
||||
|
|
@ -952,16 +775,24 @@ async def trigger_social_ingest(query: str = "", max_items: int = 50):
|
|||
return {"status": "ok", "signals_ingested": count}
|
||||
|
||||
|
||||
@app.post("/api/ingest/masscan")
|
||||
async def trigger_masscan(background_tasks: BackgroundTasks):
|
||||
"""Queue one masscan pass at ≤200 pps. Does not block the request on the scan."""
|
||||
from bg_jobs import MASSCAN_PPS_CAP, schedule_masscan_pass
|
||||
|
||||
async def _kick() -> None:
|
||||
schedule_masscan_pass()
|
||||
|
||||
background_tasks.add_task(_kick)
|
||||
return JSONResponse(
|
||||
{"status": "accepted", "rate_pps": MASSCAN_PPS_CAP},
|
||||
status_code=202,
|
||||
)
|
||||
|
||||
|
||||
@app.websocket("/ws/live")
|
||||
async def live_ws(ws: WebSocket):
|
||||
"""Viewport-filtered AIS/ADS-B fan-out.
|
||||
|
||||
Client JSON:
|
||||
{"type":"viewport","bbox":"minlon,minlat,maxlon,maxlat"}
|
||||
{"type":"watch_geofences","ids":["<uuid>", ...]} — empty list = none
|
||||
geofence_alert delivers if the point is in-viewport OR geofence_id is watched.
|
||||
AIS/ADS-B/fire_aircraft stay viewport-only.
|
||||
"""
|
||||
"""Viewport-filtered AIS/ADS-B fan-out. Client sends {type:viewport,bbox}."""
|
||||
from ws_manager import manager
|
||||
|
||||
client_id = str(id(ws))
|
||||
|
|
@ -987,10 +818,6 @@ async def live_ws(ws: WebSocket):
|
|||
manager.set_viewport(client_id, parse_bbox(str(data["bbox"])))
|
||||
except ValueError:
|
||||
continue
|
||||
elif data.get("type") == "watch_geofences":
|
||||
ids = data.get("ids") or []
|
||||
if isinstance(ids, list):
|
||||
manager.set_watched_geofences(client_id, [str(x) for x in ids])
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
|
|
@ -1142,7 +969,7 @@ async def list_cameras(
|
|||
True,
|
||||
description="Only cameras with a verified HTTP/MJPEG snapshot_url "
|
||||
"(the ones that actually preview). Set false to include "
|
||||
"rows without a snapshot_url.",
|
||||
"unverified masscan port-554 hits.",
|
||||
),
|
||||
limit: int = Query(500, ge=1, le=5000),
|
||||
):
|
||||
|
|
@ -1219,7 +1046,7 @@ async def get_camera(camera_id: UUID):
|
|||
async def camera_snapshot(camera_id: UUID):
|
||||
"""Still image for one camera.
|
||||
|
||||
HTTP cameras go through the TTL cache. RTSP finds have no HTTP
|
||||
HTTP cameras go through the TTL cache. masscan/RTSP finds have no HTTP
|
||||
snapshot_url — we probe common still-image paths and, failing that, grab
|
||||
one JPEG frame from RTSP via ffmpeg. No credentials are tried.
|
||||
"""
|
||||
|
|
@ -1368,12 +1195,7 @@ async def list_news(
|
|||
):
|
||||
"""Most recent scraped news articles (newest first)."""
|
||||
async with async_session() as session:
|
||||
stmt = select(articles).where(
|
||||
or_(
|
||||
articles.c.timestamp.is_(None),
|
||||
articles.c.timestamp <= func.now(),
|
||||
)
|
||||
).order_by(
|
||||
stmt = select(articles).order_by(
|
||||
articles.c.timestamp.desc().nullslast()
|
||||
)
|
||||
if domain:
|
||||
|
|
@ -1384,7 +1206,7 @@ async def list_news(
|
|||
rows = (await session.execute(stmt)).mappings().all()
|
||||
return [
|
||||
NewsArticleOut(
|
||||
id=r["id"], title=unwrap_cdata_title(r["title"]), url=r["url"],
|
||||
id=r["id"], title=r["title"], url=r["url"],
|
||||
content=r["content"] if include_content else None, domain=r["domain"],
|
||||
timestamp=r["timestamp"],
|
||||
)
|
||||
|
|
@ -1398,38 +1220,28 @@ async def list_news_summaries(
|
|||
None,
|
||||
description="Only summaries generated at/after this UTC instant.",
|
||||
),
|
||||
kind: str | None = Query(
|
||||
None,
|
||||
description="Filter: interval or daily_recap. Omit for all.",
|
||||
),
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
offset: int = Query(0, ge=0),
|
||||
):
|
||||
"""Most recent master LLM summaries (newest first)."""
|
||||
if kind is not None and kind not in ("interval", "daily_recap"):
|
||||
raise HTTPException(422, "kind must be interval or daily_recap")
|
||||
async with async_session() as session:
|
||||
stmt = select(article_summaries).order_by(
|
||||
article_summaries.c.batch_timestamp.desc().nullslast()
|
||||
)
|
||||
if since:
|
||||
stmt = stmt.where(article_summaries.c.batch_timestamp >= since)
|
||||
if kind is not None:
|
||||
stmt = stmt.where(article_summaries.c.kind == kind)
|
||||
stmt = stmt.limit(limit).offset(offset)
|
||||
rows = (await session.execute(stmt)).mappings().all()
|
||||
return [
|
||||
NewsSummaryOut(
|
||||
id=r["id"], summary_text=r["summary_text"],
|
||||
batch_timestamp=r["batch_timestamp"], model=r["model"],
|
||||
kind=r["kind"],
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
_FLAGGED = ("critical", "high")
|
||||
_LESSER = ("medium", "low")
|
||||
|
||||
|
||||
@app.get("/api/news/ticker", response_model=list[NewsTickerItemOut])
|
||||
|
|
@ -1440,7 +1252,7 @@ async def list_news_ticker(
|
|||
),
|
||||
limit: int = Query(20, ge=1, le=50),
|
||||
):
|
||||
"""Ticker rows: critical/high first; medium/low if nothing is flagged."""
|
||||
"""Flagged ticker rows (critical/high), newest first. No LLM required."""
|
||||
async with async_session() as session:
|
||||
stmt = (
|
||||
select(news_items)
|
||||
|
|
@ -1454,19 +1266,6 @@ async def list_news_ticker(
|
|||
stmt = stmt.where(news_items.c.created_at >= since)
|
||||
stmt = stmt.limit(limit)
|
||||
rows = (await session.execute(stmt)).mappings().all()
|
||||
if not rows:
|
||||
stmt = (
|
||||
select(news_items)
|
||||
.where(
|
||||
news_items.c.kind == "ticker",
|
||||
news_items.c.importance.in_(_LESSER),
|
||||
)
|
||||
.order_by(news_items.c.created_at.desc())
|
||||
)
|
||||
if since:
|
||||
stmt = stmt.where(news_items.c.created_at >= since)
|
||||
stmt = stmt.limit(limit)
|
||||
rows = (await session.execute(stmt)).mappings().all()
|
||||
return [
|
||||
NewsTickerItemOut(
|
||||
id=r["id"], headline=r["headline"], importance=r["importance"],
|
||||
|
|
@ -1537,94 +1336,6 @@ async def list_news_map(
|
|||
]
|
||||
|
||||
|
||||
@app.get("/api/news/blips", response_model=list[NewsBlipOut])
|
||||
async def list_news_blips(
|
||||
bbox: str | None = Query(
|
||||
None,
|
||||
description="Comma-separated 'minlon,minlat,maxlon,maxlat' to bound the "
|
||||
"result set by article coordinates. Omit for all blips.",
|
||||
),
|
||||
since: datetime | None = Query(
|
||||
None,
|
||||
description="Only gradings created at/after this UTC instant. "
|
||||
"Defaults to the last 24 hours.",
|
||||
),
|
||||
limit: int = Query(1000, ge=1, le=5000),
|
||||
):
|
||||
"""Per-article proximate geo blips: EVERY graded article with a derivable
|
||||
location (not just the critical/high map pins). Deduped by article id —
|
||||
the latest grading's geo wins. Only finite lat/lon rows, newest first.
|
||||
"""
|
||||
if since is None:
|
||||
since = datetime.now(timezone.utc) - timedelta(hours=24)
|
||||
async with async_session() as session:
|
||||
# DISTINCT ON (article_id) + ORDER BY article_id, created_at DESC
|
||||
# keeps the latest grading per article; the outer query re-sorts
|
||||
# newest-first and applies the limit. NaN is excluded explicitly:
|
||||
# Postgres sorts NaN above every finite value, so range checks
|
||||
# alone would let it through. prefix_with keeps this renderable on
|
||||
# both SQLAlchemy 2.0 and 2.1 (requirements pin >=2.0).
|
||||
stmt = (
|
||||
select(
|
||||
article_scores.c.article_id.label("id"),
|
||||
articles.c.title.label("headline"),
|
||||
articles.c.url,
|
||||
articles.c.domain,
|
||||
article_scores.c.location_name,
|
||||
article_scores.c.lat,
|
||||
article_scores.c.lon,
|
||||
article_scores.c.location_confidence,
|
||||
article_scores.c.category,
|
||||
article_scores.c.score,
|
||||
article_scores.c.created_at,
|
||||
)
|
||||
.select_from(
|
||||
article_scores.join(articles, articles.c.id == article_scores.c.article_id)
|
||||
)
|
||||
.where(
|
||||
article_scores.c.lat.isnot(None),
|
||||
article_scores.c.lon.isnot(None),
|
||||
article_scores.c.lat.between(-90, 90),
|
||||
article_scores.c.lon.between(-180, 180),
|
||||
text("article_scores.lat <> 'NaN'::double precision"),
|
||||
text("article_scores.lon <> 'NaN'::double precision"),
|
||||
article_scores.c.created_at >= since,
|
||||
)
|
||||
.prefix_with("DISTINCT ON (article_scores.article_id)")
|
||||
.order_by(article_scores.c.article_id, article_scores.c.created_at.desc())
|
||||
)
|
||||
if bbox:
|
||||
parts = [p.strip() for p in bbox.split(",")]
|
||||
if len(parts) != 4:
|
||||
raise HTTPException(
|
||||
422, "bbox must be 'minlon,minlat,maxlon,maxlat' (4 comma-separated values)"
|
||||
)
|
||||
try:
|
||||
minlon, minlat, maxlon, maxlat = (float(p) for p in parts)
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
422, "bbox values must be floats: 'minlon,minlat,maxlon,maxlat'"
|
||||
)
|
||||
stmt = stmt.where(
|
||||
and_(
|
||||
article_scores.c.lon >= minlon, article_scores.c.lon <= maxlon,
|
||||
article_scores.c.lat >= minlat, article_scores.c.lat <= maxlat,
|
||||
)
|
||||
)
|
||||
latest = stmt.subquery()
|
||||
ordered = select(latest).order_by(latest.c.created_at.desc()).limit(limit)
|
||||
rows = (await session.execute(ordered)).mappings().all()
|
||||
return [
|
||||
NewsBlipOut(
|
||||
id=r["id"], headline=r["headline"] or "", url=r["url"], domain=r["domain"],
|
||||
location_name=r["location_name"], lat=r["lat"], lon=r["lon"],
|
||||
location_confidence=r["location_confidence"], category=r["category"],
|
||||
score=r["score"], created_at=r["created_at"],
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
@app.get("/api/news/models", response_model=NewsModelsOut)
|
||||
async def list_news_models():
|
||||
"""Nous model catalog for the summarizer selector. Never 502s."""
|
||||
|
|
@ -1670,70 +1381,7 @@ async def map_layers():
|
|||
return {"layers": MAP_LAYERS, "overlays": overlay_catalog()}
|
||||
|
||||
|
||||
@app.get("/api/map/chokepoints")
|
||||
async def map_chokepoints():
|
||||
"""Static one-tap fly-to presets (Strait of Hormuz, Bab el-Mandeb, …).
|
||||
|
||||
Pure catalog — no upstream calls and no VesselAPI quota spend. ``vesselapi``
|
||||
is True only for Hormuz (the box the VesselAPI poller already covers).
|
||||
"""
|
||||
from chokepoints import chokepoints
|
||||
return {"chokepoints": chokepoints()}
|
||||
|
||||
|
||||
async def _fetch_geocoded_points() -> list[tuple[float, float, datetime | None]]:
|
||||
"""Collect geocoded ``(lat, lon, ts)`` rows from the local DB.
|
||||
|
||||
Sources are the flagged map pins (``news_items`` kind=map) and geocoded
|
||||
news/GDELT events (``events`` with ``location_lat/lon``). This is the
|
||||
pre-existing geocoded corpus the conflict-zone counters roll up — no
|
||||
upstream scraping and no generated/jittered coordinates.
|
||||
"""
|
||||
async with async_session() as session:
|
||||
map_rows = (
|
||||
await session.execute(
|
||||
select(news_items.c.lat, news_items.c.lon, news_items.c.created_at)
|
||||
.where(
|
||||
news_items.c.kind == "map",
|
||||
news_items.c.lat.isnot(None),
|
||||
news_items.c.lon.isnot(None),
|
||||
)
|
||||
)
|
||||
).all()
|
||||
event_rows = (
|
||||
await session.execute(
|
||||
select(events.c.location_lat, events.c.location_lon, events.c.source_timestamp)
|
||||
.where(
|
||||
events.c.source_type.in_(["rss", "gdel-t2"]),
|
||||
events.c.location_lat.isnot(None),
|
||||
events.c.location_lon.isnot(None),
|
||||
)
|
||||
)
|
||||
).all()
|
||||
return [tuple(r) for r in map_rows] + [tuple(r) for r in event_rows]
|
||||
|
||||
|
||||
@app.get("/api/conflicts", response_model=ConflictsOut)
|
||||
async def list_conflicts():
|
||||
"""Curated conflict-zone catalog with per-zone event counts.
|
||||
|
||||
Static catalogue (severity + short factual description) merged with a live
|
||||
``eventCount`` roll-up of pre-existing geocoded news/GDELT//api/news/map
|
||||
rows inside each zone bbox. Empty DB → ``eventCount=0`` (never 502).
|
||||
"""
|
||||
from conflicts import conflict_zones, zone_event_stats
|
||||
|
||||
points = await _fetch_geocoded_points()
|
||||
timestamp = datetime.now(timezone.utc)
|
||||
zones = []
|
||||
for z in conflict_zones():
|
||||
bbox = z.pop("bbox")
|
||||
count, latest = zone_event_stats(points, bbox)
|
||||
zones.append({**z, "eventCount": count, "lastUpdated": latest})
|
||||
return {"zones": zones, "timestamp": timestamp}
|
||||
|
||||
|
||||
def _upstream_or_502(exc: Exception, name: str) -> NoReturn:
|
||||
def _upstream_or_502(exc: Exception, name: str):
|
||||
logger.warning("live_layer_upstream_failed", layer=name, error=str(exc))
|
||||
raise HTTPException(502, f"{name} upstream unavailable: {exc}") from exc
|
||||
|
||||
|
|
@ -1747,33 +1395,6 @@ async def map_radar():
|
|||
_upstream_or_502(exc, "radar")
|
||||
|
||||
|
||||
@app.get("/api/map/sentinel1")
|
||||
async def map_sentinel1(bbox: str = Query(..., description="minlon,minlat,maxlon,maxlat")):
|
||||
"""Most recent Sentinel-1 GRD as a signed COG tile template (TiTiler).
|
||||
|
||||
Queries Planetary Computer only on demand; no tiles proxied through the Pi.
|
||||
"""
|
||||
_parse_bbox_query(bbox)
|
||||
try:
|
||||
result = await fetch_sentinel1(bbox)
|
||||
except UpstreamRateLimited as exc:
|
||||
headers = {"Retry-After": exc.retry_after} if exc.retry_after else None
|
||||
raise HTTPException(
|
||||
429, "Planetary Computer rate limit", headers=headers,
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
_upstream_or_502(exc, "sentinel1")
|
||||
if result is None:
|
||||
return JSONResponse(
|
||||
status_code=404,
|
||||
content={
|
||||
"error": "no_imagery",
|
||||
"message": "No Sentinel-1 GRD in the last 7 days for this bbox",
|
||||
},
|
||||
)
|
||||
return overlay_json(result, 300)
|
||||
|
||||
|
||||
@app.get("/api/aircraft")
|
||||
async def list_aircraft(
|
||||
bbox: str = Query(..., description="minlon,minlat,maxlon,maxlat"),
|
||||
|
|
@ -1794,23 +1415,6 @@ async def list_aircraft(
|
|||
_upstream_or_502(exc, "aircraft")
|
||||
|
||||
|
||||
@app.get("/api/aircraft/photo")
|
||||
async def aircraft_photo(
|
||||
hex_code: str | None = Query(None, alias="hex", pattern="^[0-9a-fA-F]{6}$"),
|
||||
reg: str | None = Query(None, min_length=1, max_length=12),
|
||||
):
|
||||
"""Latest planespotters.net photo for an aircraft (hex preferred, reg fallback)."""
|
||||
if not hex_code and not reg:
|
||||
raise HTTPException(422, "hex or reg required")
|
||||
try:
|
||||
photo = await fetch_planespotters_photo(hex_code=hex_code, reg=reg)
|
||||
except Exception as exc:
|
||||
_upstream_or_502(exc, "planespotters")
|
||||
if photo is None:
|
||||
raise HTTPException(404, "no photo")
|
||||
return overlay_json(photo, 86400)
|
||||
|
||||
|
||||
@app.get("/api/trains")
|
||||
async def list_trains(
|
||||
bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"),
|
||||
|
|
@ -1832,36 +1436,16 @@ async def list_vessels(
|
|||
bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"),
|
||||
limit: int = Query(2000, ge=1, le=5000),
|
||||
timestamp: str | None = Query(None, description="ISO time — DVR 1-min tracks instead of live"),
|
||||
src: str | None = Query(None, description="aisstream|vesselapi|all (default all)"),
|
||||
):
|
||||
"""AIS last-known — union of two independent providers.
|
||||
|
||||
AISStream (extra.src="aisstream", live US-coast WebSocket) and VesselAPI
|
||||
(extra.src="vesselapi", Strait of Hormuz 5×/day poll) both upsert into the
|
||||
same store. Empty without either key / until the first successful poll.
|
||||
``src`` filters the union to one provider (default ``all``) so a Hormuz
|
||||
view can skip the ~5k CONUS AISStream rows.
|
||||
"""
|
||||
if src is not None and src not in ("aisstream", "vesselapi", "all"):
|
||||
raise HTTPException(422, "src must be one of: aisstream, vesselapi, all")
|
||||
"""AIS last-known from the server-side AISStream worker. Empty without a key."""
|
||||
if bbox:
|
||||
_parse_bbox_query(bbox)
|
||||
try:
|
||||
from tracks import fetch_positions_at, parse_timestamp
|
||||
ts = parse_timestamp(timestamp)
|
||||
if ts is not None:
|
||||
from vesselapi import fetch_vessels_as_of
|
||||
if src == "vesselapi":
|
||||
return overlay_json(await fetch_vessels_as_of(ts, bbox, limit), 5)
|
||||
ais = await fetch_positions_at("vessel", ts, bbox, limit)
|
||||
if src == "aisstream":
|
||||
return overlay_json(ais, 5)
|
||||
va = await fetch_vessels_as_of(ts, bbox, limit)
|
||||
by_id = {m["id"]: m for m in ais}
|
||||
for m in va:
|
||||
by_id[m["id"]] = m
|
||||
return overlay_json(list(by_id.values())[:limit], 5)
|
||||
return overlay_json(await fetch_vessels(bbox, limit, src=src), 5)
|
||||
return overlay_json(await fetch_positions_at("vessel", ts, bbox, limit), 5)
|
||||
return overlay_json(await fetch_vessels(bbox, limit), 5)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
|
||||
|
|
@ -1942,83 +1526,33 @@ async def api_update_geofence(gid: str, payload: GeofenceUpdate):
|
|||
@app.delete("/api/geofences/{gid}", status_code=204)
|
||||
async def api_delete_geofence(gid: str):
|
||||
from geofence import delete_geofence
|
||||
ok = await delete_geofence(gid)
|
||||
if not ok:
|
||||
raise HTTPException(404, "geofence not found")
|
||||
await delete_geofence(gid)
|
||||
return None
|
||||
|
||||
|
||||
@app.get("/api/geofences/{gid}/at")
|
||||
async def api_geofence_at(
|
||||
gid: str,
|
||||
timestamp: str | None = Query(
|
||||
None, description="ISO-8601 instant for the 1-minute DVR bucket",
|
||||
),
|
||||
ts: str | None = Query(
|
||||
None,
|
||||
description="Alias of timestamp. Evidence snapshot URLs use this name.",
|
||||
),
|
||||
):
|
||||
"""Aircraft/vessels/fires inside this fence at time T. Never writes."""
|
||||
from geofence import snapshot_at
|
||||
from tracks import parse_timestamp
|
||||
|
||||
raw_ts = timestamp or ts
|
||||
try:
|
||||
ts_parsed = parse_timestamp(raw_ts)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
if ts_parsed is None:
|
||||
raise HTTPException(422, "timestamp required")
|
||||
try:
|
||||
body = await snapshot_at(gid, ts_parsed)
|
||||
except Exception:
|
||||
body = {
|
||||
"geofence_id": gid,
|
||||
"timestamp": ts_parsed.isoformat(),
|
||||
"aircraft": [],
|
||||
"vessels": [],
|
||||
"fires": [],
|
||||
}
|
||||
if body is None:
|
||||
raise HTTPException(404, "geofence not found")
|
||||
return body
|
||||
|
||||
|
||||
@app.get("/api/geofence-alerts")
|
||||
async def api_geofence_alerts(
|
||||
geofence_id: UUID | None = Query(None),
|
||||
since: str | None = Query(None, description="ISO-8601 inclusive lower bound"),
|
||||
until: str | None = Query(None, description="ISO-8601 inclusive upper bound"),
|
||||
source_kind: str | None = Query(
|
||||
None,
|
||||
description="firms|ais|adsb|earthquake|fire_incident|news",
|
||||
),
|
||||
limit: int = Query(100, ge=1, le=500),
|
||||
):
|
||||
"""Hit log for drawn fences. Not /api/alerts (entity/keyword)."""
|
||||
from geofence import list_alerts
|
||||
from tracks import parse_timestamp
|
||||
|
||||
if source_kind is not None and source_kind not in (
|
||||
"firms", "ais", "adsb", "earthquake", "fire_incident", "news",
|
||||
):
|
||||
raise HTTPException(
|
||||
422,
|
||||
"source_kind must be one of: firms, ais, adsb, earthquake, fire_incident, news",
|
||||
)
|
||||
async def api_geofence_alerts(limit: int = Query(100, ge=1, le=500)):
|
||||
from sqlalchemy import text as sql_text
|
||||
try:
|
||||
since_ts = parse_timestamp(since) if since else None
|
||||
until_ts = parse_timestamp(until) if until else None
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
return await list_alerts(
|
||||
geofence_id=str(geofence_id) if geofence_id else None,
|
||||
since=since_ts,
|
||||
until=until_ts,
|
||||
source_kind=source_kind,
|
||||
limit=limit,
|
||||
)
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(sql_text(
|
||||
"""
|
||||
SELECT id::text, geofence_id::text, source_kind, entity_id,
|
||||
lat, lon, payload, created_at
|
||||
FROM geofence_alerts
|
||||
ORDER BY created_at DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
), {"limit": limit})).mappings().all()
|
||||
out = []
|
||||
for r in rows:
|
||||
item = dict(r)
|
||||
if item.get("created_at") is not None:
|
||||
item["created_at"] = item["created_at"].isoformat()
|
||||
out.append(item)
|
||||
return out
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
@app.get("/api/fire-aircraft")
|
||||
|
|
@ -2080,122 +1614,6 @@ async def list_storms():
|
|||
_upstream_or_502(exc, "storms")
|
||||
|
||||
|
||||
@app.get("/api/place")
|
||||
async def get_place(
|
||||
lat: float = Query(..., ge=-90, le=90),
|
||||
lon: float = Query(..., ge=-180, le=180),
|
||||
):
|
||||
"""Nominatim reverse geocode for the map \"What's here?\" dossier.
|
||||
|
||||
Identifying ``OSINT_USER_AGENT``, 1 req/s, 60s cache, 500 keys. The HUD
|
||||
lists already-loaded overlay entities client-side — this route does not
|
||||
refetch aircraft/vessels/cameras/fires.
|
||||
"""
|
||||
try:
|
||||
return overlay_json(await reverse_geocode(lat, lon), 60)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
except Exception as exc:
|
||||
_upstream_or_502(exc, "nominatim")
|
||||
|
||||
|
||||
_GPSJAM_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||||
|
||||
|
||||
@app.get("/api/map/gpsjam")
|
||||
async def map_gpsjam(
|
||||
date: str | None = Query(None, description="YYYY-MM-DD (default: yesterday UTC)"),
|
||||
):
|
||||
"""GPSJAM daily GPS-interference hex layer (whole world, GeoJSON).
|
||||
|
||||
Red/yellow hexes correlate with suspected jamming but are NOT proof of it.
|
||||
Fetched once per day from gpsjam.org (ADS-B Exchange data) and cached 1h.
|
||||
"""
|
||||
target = date
|
||||
if target is None:
|
||||
target = (datetime.now(timezone.utc) - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
if not _GPSJAM_DATE.match(target):
|
||||
raise HTTPException(422, "date must be YYYY-MM-DD")
|
||||
try:
|
||||
fc = await fetch_gpsjam(target)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
if exc.response.status_code == 404:
|
||||
return JSONResponse(
|
||||
{"error": "unavailable", "href": "https://gpsjam.org/",
|
||||
"date": target},
|
||||
)
|
||||
_upstream_or_502(exc, "gpsjam")
|
||||
except Exception as exc:
|
||||
_upstream_or_502(exc, "gpsjam")
|
||||
if not fc.get("features"):
|
||||
return JSONResponse(
|
||||
{"error": "unavailable", "href": "https://gpsjam.org/", "date": target},
|
||||
)
|
||||
return overlay_json(fc, 3600)
|
||||
|
||||
|
||||
@app.get("/api/satellites")
|
||||
async def list_satellites(
|
||||
groups: str | None = Query(None, description="Comma-separated CelesTrak groups"),
|
||||
bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"),
|
||||
limit: int = Query(2000, ge=1, le=5000),
|
||||
):
|
||||
"""Last-known satellite positions from CelesTrak GP JSON, SGP4-propagated.
|
||||
|
||||
Default groups are ``stations,weather`` (tens of objects). The GP element
|
||||
blob is fetched at most once per 2 hours per group and cached; positions
|
||||
are re-propagated on every request. Falls back to the last good blob on a
|
||||
CelesTrak 403 / stale response, and to SatNOGS TLE only when the cache is
|
||||
empty. Unknown groups 400.
|
||||
"""
|
||||
try:
|
||||
group_list = parse_groups(groups if groups is not None else ",".join(DEFAULT_GROUPS))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(400, str(exc)) from exc
|
||||
if bbox:
|
||||
_parse_bbox_query(bbox)
|
||||
try:
|
||||
payload = await fetch_satellites(group_list, bbox=bbox, limit=limit)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
except Exception as exc:
|
||||
_upstream_or_502(exc, "satellites")
|
||||
return overlay_json(payload, 30)
|
||||
|
||||
|
||||
_INFRA_TYPES = frozenset({"nuclear"})
|
||||
|
||||
|
||||
@app.get("/api/infrastructure")
|
||||
async def api_infrastructure(
|
||||
types: str = Query(..., description="comma-separated enum (nuclear)"),
|
||||
bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"),
|
||||
):
|
||||
"""Overpass-derived static infrastructure markers (nuclear power plants).
|
||||
|
||||
``bbox`` is required; ``types`` is a comma-separated subset of ``nuclear``.
|
||||
Fetched from Overpass (identifying UA, 25s query) and cached 24h per
|
||||
quantized bbox. Markers are ``{id, name, lat, lon, type, extra}``.
|
||||
"""
|
||||
if not bbox:
|
||||
raise HTTPException(400, "bbox required (minlon,minlat,maxlon,maxlat)")
|
||||
requested = [t.strip() for t in (types or "").split(",") if t.strip()]
|
||||
if not requested:
|
||||
raise HTTPException(422, "types required (e.g. nuclear)")
|
||||
unknown = [t for t in requested if t not in _INFRA_TYPES]
|
||||
if unknown:
|
||||
raise HTTPException(
|
||||
422, f"unsupported types: {', '.join(unknown)} (supported: nuclear)"
|
||||
)
|
||||
try:
|
||||
markers = await fetch_infrastructure(",".join(requested), bbox)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
except Exception as exc:
|
||||
_upstream_or_502(exc, "infrastructure")
|
||||
return overlay_json(markers, 86400)
|
||||
|
||||
|
||||
@app.get("/api/map/times")
|
||||
async def map_layer_times(
|
||||
layer: str = Query(..., description="GIBS layer identifier, e.g. VIIRS_SNPP_CorrectedReflectance_TrueColor"),
|
||||
|
|
@ -2226,4 +1644,4 @@ app.mount("/static", CachedStaticFiles(directory=str(STATIC_DIR)), name="static"
|
|||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=8000, workers=1) # single worker: in-memory WS/pubsub + layer caches
|
||||
uvicorn.run(app, host="0.0.0.0", port=8000)
|
||||
|
|
|
|||
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 sqlalchemy import (
|
||||
Boolean, Column, Enum, Float, Index, Integer, String, Text,
|
||||
Column, Enum, Float, Index, Integer, String, Text,
|
||||
DateTime, JSON, func, Table, PrimaryKeyConstraint,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
|
||||
|
|
@ -219,7 +219,6 @@ article_summaries = Table(
|
|||
Column("batch_timestamp", DateTime(timezone=True),
|
||||
server_default=func.now(), nullable=False),
|
||||
Column("model", Text), # LLM id used for this batch; nullable for old rows
|
||||
Column("kind", Text), # interval | daily_recap; nullable for old rows
|
||||
)
|
||||
|
||||
Index("ix_article_summaries_batch_timestamp", article_summaries.c.batch_timestamp)
|
||||
|
|
@ -242,34 +241,3 @@ news_items = Table(
|
|||
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
|
||||
)
|
||||
Index("ix_news_items_kind_created", news_items.c.kind, news_items.c.created_at)
|
||||
|
||||
|
||||
# Per-article map-phase grades (alembic 012/013/014). One row per graded
|
||||
# article per run; PK (article_id, created_at) lets re-grades accumulate.
|
||||
# Geo columns are nullable: only articles with a derivable location carry
|
||||
# coordinates, served by GET /api/news/blips.
|
||||
article_scores = Table(
|
||||
"article_scores",
|
||||
metadata,
|
||||
Column("article_id", Integer, nullable=False),
|
||||
Column("summary_id", Integer),
|
||||
Column("score", Integer, nullable=False),
|
||||
Column("category", Text),
|
||||
Column("selected", Boolean, nullable=False),
|
||||
Column("model", Text),
|
||||
Column("duplicate_of", Integer),
|
||||
Column("location_name", Text),
|
||||
Column("lat", Float),
|
||||
Column("lon", Float),
|
||||
Column("location_confidence", Text),
|
||||
Column("created_at", DateTime(timezone=True),
|
||||
server_default=func.now(), nullable=False),
|
||||
PrimaryKeyConstraint("article_id", "created_at"),
|
||||
)
|
||||
Index("ix_article_scores_summary", article_scores.c.summary_id)
|
||||
Index(
|
||||
"ix_article_scores_geo_bbox",
|
||||
article_scores.c.lon, article_scores.c.lat,
|
||||
postgresql_where=article_scores.c.lat.isnot(None)
|
||||
& article_scores.c.lon.isnot(None),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
websockets>=14
|
||||
cachetools>=5.5
|
||||
h3>=4.0
|
||||
sgp4>=2.23
|
||||
|
|
|
|||
|
|
@ -1,10 +1,9 @@
|
|||
"""Long-running camera discovery service.
|
||||
|
||||
Discovers cameras on an interval and upserts them into the `cameras` table
|
||||
(dedupe by url_hash) for the /api/cameras bbox query. Discovery is not an
|
||||
event: this process does not publish `events.camera` messages. Those were
|
||||
inserted as events rows and flooded the HUD feed. The cameras table is the
|
||||
index.
|
||||
Follows the existing ingest pattern: discovers cameras on an interval and
|
||||
publishes each one as a NATS message (`events.camera`) so the shared NATS ->
|
||||
ingester pipeline persists them; also upserts directly into the `cameras`
|
||||
table (dedupe by url_hash) for the /api/cameras bbox query.
|
||||
|
||||
Env:
|
||||
CAMERA_SOURCE_URLS comma-separated public directory/list URLs
|
||||
|
|
@ -15,6 +14,7 @@ Env:
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
|
@ -22,12 +22,16 @@ from pathlib import Path
|
|||
sys_path = str(Path(__file__).parent)
|
||||
sys.path.insert(0, sys_path)
|
||||
|
||||
import nats # noqa: E402
|
||||
|
||||
from camera_config import ( # noqa: E402
|
||||
CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL,
|
||||
CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL, CAMERA_NATS_SUBJECT,
|
||||
SNAPSHOT_CACHE_DIR,
|
||||
)
|
||||
from camera_scraper import run_cycle # noqa: E402
|
||||
from database import init_extensions # noqa: E402
|
||||
from camera_models import cameras # noqa: E402
|
||||
from camera_scraper import run_cycle, url_hash # noqa: E402
|
||||
from database import async_session, init_extensions # noqa: E402
|
||||
from config import NATS_URL # noqa: E402
|
||||
|
||||
logging.basicConfig(level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
|
|
@ -36,16 +40,48 @@ logger = logging.getLogger("osint.camera_service")
|
|||
ENABLED = sys.argv[1:] != ["--once"]
|
||||
|
||||
|
||||
async def publish_new_cameras(rows: list | None = None) -> int:
|
||||
"""Do not publish camera discoveries as events.
|
||||
|
||||
``run_cycle`` already upserts the cameras table, which backs
|
||||
``GET /api/cameras``. ``rows`` is newly seen cameras from a cycle or a
|
||||
test; none are JetStream-published, so the ingester inserts 0 events
|
||||
with source_type=camera.
|
||||
"""
|
||||
del rows
|
||||
async def publish_new_cameras() -> int:
|
||||
"""Publish cameras seen in the latest cycle to NATS for the ingester."""
|
||||
from datetime import datetime, timezone, timedelta
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=CAMERA_SCRAPE_INTERVAL * 2)
|
||||
published = 0
|
||||
try:
|
||||
nc = await nats.connect(NATS_URL)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("NATS unavailable — skipping publish pass")
|
||||
return 0
|
||||
try:
|
||||
js = nc.jetstream()
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
cameras.select().where(cameras.c.last_seen >= cutoff)
|
||||
)).mappings().all()
|
||||
for r in rows:
|
||||
msg = {
|
||||
"source_type": "camera",
|
||||
"title": f"Open camera ({r['vendor'] or 'unknown vendor'})",
|
||||
"url": r["source_url"],
|
||||
"location_lat": r["location_lat"],
|
||||
"location_lon": r["location_lon"],
|
||||
"location_name": r["location_name"],
|
||||
"tags": ["osint", "camera", r["discovery_source"]],
|
||||
"raw": {
|
||||
"url_hash": r["url_hash"],
|
||||
"snapshot_url": r["snapshot_url"],
|
||||
"vendor": r["vendor"],
|
||||
"device_type": r["device_type"],
|
||||
"first_seen": r["first_seen"].isoformat(),
|
||||
"last_seen": r["last_seen"].isoformat(),
|
||||
},
|
||||
"source_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
await js.publish(CAMERA_NATS_SUBJECT, json.dumps(msg).encode())
|
||||
published += 1
|
||||
if published >= 500: # per-cycle cap
|
||||
break
|
||||
finally:
|
||||
await nc.close()
|
||||
return published
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
|
|
@ -57,7 +93,8 @@ async def main() -> None:
|
|||
try:
|
||||
n = await run_cycle()
|
||||
p = await publish_new_cameras()
|
||||
logger.info("cycle: %d stored, %d camera events published", n, p)
|
||||
logger.info("cycle: %d stored, %d published to %s",
|
||||
n, p, CAMERA_NATS_SUBJECT)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("camera cycle error")
|
||||
if not ENABLED: # --once mode
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ import sys
|
|||
|
||||
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 fire_sources import ingest_fires # noqa: E402
|
||||
from ingestor import ingest_event, start_nats_consumer # noqa: E402
|
||||
|
|
@ -56,11 +56,8 @@ async def producer_loop() -> None:
|
|||
try:
|
||||
g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50)
|
||||
logger.info("GDELT -> %d articles", g)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# Quota/backoff cases are handled inside ingest_gdelt (one clean
|
||||
# line); anything reaching here is a real failure and a stack
|
||||
# trace every 5 minutes is not actionable, so keep it to one line.
|
||||
logger.warning("GDELT fetch failed: %s", exc)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("GDELT fetch failed")
|
||||
if ENABLE_QUAKES:
|
||||
try:
|
||||
q = await ingest_earthquakes()
|
||||
|
|
@ -119,24 +116,6 @@ async def fire_loop() -> None:
|
|||
await asyncio.sleep(FIRMS_INTERVAL)
|
||||
|
||||
|
||||
async def geofence_feed_loop() -> None:
|
||||
"""Hear quakes already stored, WFIGS incidents, and news map pins.
|
||||
|
||||
WFIGS is not persisted — fetched per active-fence bbox here (no FIRMS
|
||||
or AIS key). News pins are read from ``news_items``; the summarizer
|
||||
is not imported. New earthquakes also notify from ``ingest_event``.
|
||||
"""
|
||||
logger.info("geofence feed loop starting (interval=%ss)", INTERVAL)
|
||||
while True:
|
||||
try:
|
||||
from geofence import scan_geofence_feeds
|
||||
n = await scan_geofence_feeds()
|
||||
logger.info("geofence feeds -> %d notifies", n)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("geofence feed scan failed")
|
||||
await asyncio.sleep(INTERVAL)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
logger.info(
|
||||
"ingester starting (rss=%d feeds, gdelt_q=%r, quakes=%s, fires=%s, interval=%ss)",
|
||||
|
|
@ -147,9 +126,7 @@ async def main() -> None:
|
|||
await refresh_cache()
|
||||
except Exception:
|
||||
logger.exception("geofence cache refresh failed (ST_Intersects still runs on ingest)")
|
||||
tasks: list[asyncio.Task] = [
|
||||
asyncio.create_task(geofence_feed_loop()),
|
||||
]
|
||||
tasks: list[asyncio.Task] = []
|
||||
if ENABLE_FIRES:
|
||||
# Fire ingest only starts once FIRMS_MAP_KEY is set (ingest_fires logs
|
||||
# and idles otherwise).
|
||||
|
|
@ -157,9 +134,6 @@ async def main() -> None:
|
|||
if AISSTREAM_IN_INGEST:
|
||||
from ais_stream import run_ais_worker # noqa: E402
|
||||
tasks.append(asyncio.create_task(run_ais_worker()))
|
||||
if VESSELAPI_IN_INGEST:
|
||||
from vesselapi import run_vesselapi_worker # noqa: E402
|
||||
tasks.append(asyncio.create_task(run_vesselapi_worker()))
|
||||
await asyncio.gather(producer_loop(), consumer_loop(), *tasks)
|
||||
|
||||
|
||||
|
|
|
|||
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(),
|
||||
}
|
||||
|
|
@ -4,10 +4,10 @@ from __future__ import annotations
|
|||
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from typing import Literal, Optional
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
|
||||
# ─── Enums ───────────────────────────────────────────────────────────────
|
||||
|
|
@ -63,17 +63,6 @@ class FeedSourceCreate(BaseModel):
|
|||
config: Optional[dict] = None
|
||||
|
||||
|
||||
class FeedSourceUpdate(BaseModel):
|
||||
"""PATCH /api/sources/{id} — only these keys may be set."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: Optional[str] = None
|
||||
url: Optional[str] = None
|
||||
config: Optional[dict] = None
|
||||
enabled: Optional[bool] = None
|
||||
|
||||
|
||||
class FeedSourceOut(BaseModel):
|
||||
id: UUID
|
||||
name: str
|
||||
|
|
@ -285,7 +274,6 @@ class NewsSummaryOut(BaseModel):
|
|||
summary_text: str
|
||||
batch_timestamp: datetime
|
||||
model: Optional[str] = None
|
||||
kind: Optional[str] = None
|
||||
|
||||
|
||||
class NewsTickerItemOut(BaseModel):
|
||||
|
|
@ -314,26 +302,6 @@ class NewsMapItemOut(BaseModel):
|
|||
created_at: datetime
|
||||
|
||||
|
||||
class NewsBlipOut(BaseModel):
|
||||
"""One per-article proximate geo blip as exposed by GET /api/news/blips.
|
||||
|
||||
Frozen wire contract (card t_bc15eb53): every graded article with a
|
||||
derivable location, deduped by article id (latest grading wins).
|
||||
Unlike /api/news/map this is NOT limited to critical/high items.
|
||||
"""
|
||||
id: int
|
||||
headline: str
|
||||
url: Optional[str] = None
|
||||
domain: Optional[str] = None
|
||||
location_name: Optional[str] = None
|
||||
lat: float
|
||||
lon: float
|
||||
location_confidence: Optional[str] = None
|
||||
category: Optional[str] = None
|
||||
score: Optional[int] = None
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class NewsModelId(BaseModel):
|
||||
"""One model id as exposed by GET /api/news/models."""
|
||||
|
||||
|
|
@ -417,24 +385,3 @@ class GeofenceUpdate(BaseModel):
|
|||
geojson: Optional[dict] = None
|
||||
active: Optional[bool] = None
|
||||
|
||||
|
||||
class ConflictZoneOut(BaseModel):
|
||||
"""One curated conflict theatre as exposed by GET /api/conflicts."""
|
||||
|
||||
id: str
|
||||
label: str
|
||||
severity: Literal["war", "high", "elevated"]
|
||||
lat: float
|
||||
lon: float
|
||||
description: str
|
||||
eventCount: int
|
||||
lastUpdated: Optional[datetime] = None
|
||||
|
||||
|
||||
class ConflictsOut(BaseModel):
|
||||
"""Response envelope for GET /api/conflicts."""
|
||||
|
||||
zones: list[ConflictZoneOut]
|
||||
timestamp: datetime
|
||||
|
||||
|
||||
|
|
|
|||
394
app/sources.py
394
app/sources.py
|
|
@ -2,15 +2,9 @@
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timezone
|
||||
from email.utils import parsedate_to_datetime
|
||||
|
||||
import httpx
|
||||
|
|
@ -61,35 +55,6 @@ def event_dedup_key(msg: dict) -> str | None:
|
|||
return url or None
|
||||
|
||||
|
||||
async def existing_event_urls(urls: list[str]) -> set[str]:
|
||||
"""URLs already claimed in event_dedup. Empty input -> empty set."""
|
||||
if not urls:
|
||||
return set()
|
||||
from sqlalchemy import select
|
||||
|
||||
from database import async_session
|
||||
from models import event_dedup as event_dedup_table
|
||||
|
||||
async with async_session() as session:
|
||||
result = await session.execute(
|
||||
select(event_dedup_table.c.url).where(event_dedup_table.c.url.in_(urls))
|
||||
)
|
||||
return {row[0] for row in result}
|
||||
|
||||
|
||||
async def _publish_unknown(subject: str, events: list[dict]) -> int:
|
||||
"""Publish only events whose URL is not already in event_dedup."""
|
||||
keys = [event_dedup_key(e) for e in events]
|
||||
known = await existing_event_urls([k for k in keys if k])
|
||||
published = 0
|
||||
for event, key in zip(events, keys):
|
||||
if key and key in known:
|
||||
continue
|
||||
await publish_event(subject, event)
|
||||
published += 1
|
||||
return published
|
||||
|
||||
|
||||
def _ua_headers() -> dict[str, str]:
|
||||
return {"User-Agent": OSINT_USER_AGENT}
|
||||
|
||||
|
|
@ -149,61 +114,6 @@ def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]:
|
|||
}
|
||||
|
||||
|
||||
# GDELT 429 backoff state. GDELT sends no Retry-After, and its block window
|
||||
# grows with request volume, so the only useful reaction to a 429 is to stop
|
||||
# asking: skip whole producer cycles, doubling the wait from BASE to MAX.
|
||||
GDELT_BACKOFF_BASE = int(os.getenv("GDELT_BACKOFF_BASE", "300"))
|
||||
GDELT_BACKOFF_MAX = int(os.getenv("GDELT_BACKOFF_MAX", "1800"))
|
||||
_gdelt_backoff_secs = 0
|
||||
_gdelt_backoff_until = 0.0 # time.monotonic()
|
||||
|
||||
|
||||
def gdelt_backoff_remaining() -> float:
|
||||
"""Seconds left in the GDELT cooldown window (0 = ready to call)."""
|
||||
return max(0.0, _gdelt_backoff_until - time.monotonic())
|
||||
|
||||
|
||||
def _gdelt_backoff_until_iso() -> str:
|
||||
return (
|
||||
datetime.now(timezone.utc).replace(microsecond=0)
|
||||
+ timedelta(seconds=gdelt_backoff_remaining())
|
||||
).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def _gdelt_start_backoff(retry_after: float | None = None) -> None:
|
||||
global _gdelt_backoff_secs, _gdelt_backoff_until
|
||||
wait = retry_after or min(
|
||||
GDELT_BACKOFF_MAX, max(GDELT_BACKOFF_BASE, _gdelt_backoff_secs * 2)
|
||||
)
|
||||
_gdelt_backoff_secs = int(wait)
|
||||
_gdelt_backoff_until = time.monotonic() + wait
|
||||
|
||||
|
||||
def _gdelt_clear_backoff() -> None:
|
||||
global _gdelt_backoff_secs, _gdelt_backoff_until
|
||||
_gdelt_backoff_secs = 0
|
||||
_gdelt_backoff_until = 0.0
|
||||
|
||||
|
||||
def _gdelt_retry_after(resp: httpx.Response) -> float | None:
|
||||
"""Retry-After as seconds (delta-seconds or HTTP-date); GDELT sends neither."""
|
||||
raw = resp.headers.get("retry-after")
|
||||
if not raw:
|
||||
return None
|
||||
raw = raw.strip()
|
||||
try:
|
||||
return max(1.0, float(raw))
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
return max(
|
||||
1.0,
|
||||
(parsedate_to_datetime(raw) - datetime.now(timezone.utc)).total_seconds(),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _parse_gdelt_seendate(value: object) -> str:
|
||||
if isinstance(value, str) and len(value) >= 15:
|
||||
try:
|
||||
|
|
@ -236,59 +146,25 @@ def parse_gdelt_articles(data: dict) -> list[dict]:
|
|||
return events
|
||||
|
||||
|
||||
async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50):
|
||||
"""Fetch articles from the GDELT DOC 2.0 API.
|
||||
|
||||
GDELT enforces a per-IP quota that answers ``429`` with a plain-text body
|
||||
("Please limit requests to one every 5 seconds"), sends **no** Retry-After,
|
||||
and widens the block window as request volume accumulates. So a 429 is not
|
||||
retried: the ingester stops calling until a backoff window expires, and the
|
||||
cycle is skipped with a single log line. See ``gdelt_backoff_remaining``.
|
||||
"""
|
||||
remaining = gdelt_backoff_remaining()
|
||||
if remaining > 0:
|
||||
logger.info(
|
||||
"GDELT: cooling down (%ds left after 429); skipping this cycle", int(remaining)
|
||||
)
|
||||
return 0
|
||||
|
||||
async def ingest_gdelt(query: str = "", max_articles: int = 50):
|
||||
"""Fetch articles from the GDELT DOC 2.0 API."""
|
||||
params = gdelt_params(query=query, max_articles=max_articles)
|
||||
data: dict = {"articles": []}
|
||||
async with httpx.AsyncClient(
|
||||
timeout=60, headers=_ua_headers(), follow_redirects=True,
|
||||
) as client:
|
||||
try:
|
||||
resp = await client.get(GDELT_API, params=params)
|
||||
except httpx.TransportError as exc:
|
||||
# gdeltproject.org certs have expired in the wild; HTTP fallback.
|
||||
# Only transport failures (TLS/connect) get the fallback — an HTTP
|
||||
# error status is a quota answer and retrying it just burns the
|
||||
# same per-IP budget a second time.
|
||||
logger.warning("GDELT HTTPS transport error (%s); retrying HTTP", exc)
|
||||
http_url = GDELT_API.replace("https://", "http://", 1)
|
||||
resp = await client.get(http_url, params=params)
|
||||
|
||||
if resp.status_code == 429:
|
||||
_gdelt_start_backoff(_gdelt_retry_after(resp))
|
||||
logger.warning(
|
||||
"GDELT 429 (rate limited) -> backing off until %s",
|
||||
_gdelt_backoff_until_iso(),
|
||||
)
|
||||
return 0
|
||||
|
||||
try:
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
except (httpx.HTTPStatusError, ValueError) as exc:
|
||||
# GDELT also signals errors/throttling as HTTP 200 + prose, so a
|
||||
# JSON decode failure is "busy", not "no results".
|
||||
_gdelt_start_backoff(_gdelt_retry_after(resp))
|
||||
logger.warning(
|
||||
"GDELT unusable response (HTTP %s: %s) -> backing off until %s",
|
||||
resp.status_code, str(exc).splitlines()[0][:120], _gdelt_backoff_until_iso(),
|
||||
)
|
||||
return 0
|
||||
except (httpx.TransportError, httpx.HTTPStatusError) as exc:
|
||||
# gdeltproject.org certs have expired in the wild; HTTP fallback.
|
||||
logger.warning("GDELT HTTPS failed (%s); retrying HTTP", exc)
|
||||
http_url = GDELT_API.replace("https://", "http://", 1)
|
||||
resp = await client.get(http_url, params=params)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
|
||||
_gdelt_clear_backoff()
|
||||
events = parse_gdelt_articles(data if isinstance(data, dict) else {})
|
||||
for event in events:
|
||||
await publish_event("events.gdelt", event)
|
||||
|
|
@ -296,240 +172,6 @@ async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50):
|
|||
return len(events)
|
||||
|
||||
|
||||
# ─── GDELT 2.0 15-minute bulk files (throttle-free) ─────────────────────
|
||||
#
|
||||
# The DOC 2.0 API is per-IP quota'd (429, no Retry-After). The same coverage is
|
||||
# published every 15 minutes as static files under /gdeltv2/ with no key and no
|
||||
# quota, indexed by ``lastupdate.txt``:
|
||||
# *.export.CSV.zip events (CAMEO codes)
|
||||
# *.mentions.CSV.zip event->article mentions (URL + confidence, no title)
|
||||
# *.gkg.csv.zip Global Knowledge Graph, one row per article: URL, source
|
||||
# domain, themes, locations with lat/lon, tone, and the
|
||||
# page title in the V2ExtrasXML column
|
||||
# GKG is the one that carries title + geo, so map a filtered row into the same
|
||||
# event shape ``parse_gdelt_articles`` produces and let the existing
|
||||
# ``events.gdelt`` NATS consumer + ``event_dedup`` (URL) keep working.
|
||||
|
||||
GDELT_BULK_ENABLED = os.getenv("GDELT_BULK_ENABLED", "1").lower() in ("1", "true", "yes")
|
||||
GDELT_BULK_LASTUPDATE = os.getenv(
|
||||
"GDELT_BULK_LASTUPDATE", "https://data.gdeltproject.org/gdeltv2/lastupdate.txt"
|
||||
)
|
||||
GDELT_BULK_MAX_EVENTS = int(os.getenv("GDELT_BULK_MAX_EVENTS", "100"))
|
||||
|
||||
# Newest bulk file already parsed; lastupdate.txt is re-read every cycle but the
|
||||
# 15-minute file behind it only changes 4x/hour.
|
||||
_gdelt_bulk_last_file: str | None = None
|
||||
|
||||
_PAGE_TITLE_RE = re.compile(r"<PAGE_TITLE>(.*?)</PAGE_TITLE>", re.DOTALL)
|
||||
_PAGE_PUB_TS_RE = re.compile(r"<PAGE_PRECISEPUBTIMESTAMP>(\d{14})<")
|
||||
|
||||
|
||||
def gdelt_query_terms(query: str = "") -> list[str]:
|
||||
"""CONFIG GDELT query (``(unrest OR protest OR ...)``) -> plain terms.
|
||||
|
||||
Used to filter bulk rows against their GKG theme tokens instead of
|
||||
publishing every article in the 15-minute window.
|
||||
"""
|
||||
q = (query or "").strip() or GDELT_DEFAULT_QUERY
|
||||
terms: list[str] = []
|
||||
for part in re.split(r"\s+OR\s+", q.strip().strip("()"), flags=re.IGNORECASE):
|
||||
term = part.strip().strip('"').strip("'").strip().lower()
|
||||
if term and term not in terms:
|
||||
terms.append(term)
|
||||
return terms
|
||||
|
||||
|
||||
def _term_hits_themes(term: str, themes: str) -> bool:
|
||||
"""Term matches when every word of it appears in the theme token list."""
|
||||
words = [w for w in re.split(r"[\s_\-]+", term) if w]
|
||||
return bool(words) and all(w in themes for w in words)
|
||||
|
||||
|
||||
def select_gdelt_bulk_url(lastupdate_text: str) -> tuple[str, str] | None:
|
||||
"""``(filename, https_url)`` of the newest GKG file in lastupdate.txt.
|
||||
|
||||
lastupdate.txt lists plain ``http://`` URLs, which 301 to https; normalise
|
||||
so the fetch never follows a redirect into a stale mirror.
|
||||
"""
|
||||
for line in (lastupdate_text or "").splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) < 3 or not parts[2].endswith(".gkg.csv.zip"):
|
||||
continue
|
||||
url = parts[2]
|
||||
if url.startswith("http://"):
|
||||
url = "https://" + url[len("http://"):]
|
||||
return url.rsplit("/", 1)[-1], url
|
||||
return None
|
||||
|
||||
|
||||
def _gkg_location(field: str) -> tuple[float | None, float | None, str | None]:
|
||||
"""First location in a V2Locations field -> (lat, lon, name).
|
||||
|
||||
V2Locations is ``type#fullname#cc#adm1[#adm2]#lat#lon#featureid``; the
|
||||
adm2 slot is sometimes dropped, so read the triple from the end.
|
||||
"""
|
||||
segment = (field or "").split(";", 1)[0]
|
||||
parts = segment.split("#")
|
||||
if len(parts) < 5:
|
||||
return None, None, None
|
||||
name = parts[1].strip() or None
|
||||
try:
|
||||
lat = float(parts[-3])
|
||||
lon = float(parts[-2])
|
||||
except (TypeError, ValueError):
|
||||
return None, None, name
|
||||
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
||||
return None, None, name
|
||||
return lat, lon, name
|
||||
|
||||
|
||||
def _gkg_tone(field: str) -> float | None:
|
||||
try:
|
||||
return _parse_gdelt_tone(field.split(",", 1)[0])
|
||||
except (AttributeError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
def _gkg_timestamp(row: list[str], extras: str) -> str:
|
||||
"""Article publish time: PAGE_PRECISEPUBTIMESTAMP, else the GKG window stamp."""
|
||||
stamps = []
|
||||
pub = _PAGE_PUB_TS_RE.search(extras)
|
||||
if pub is not None:
|
||||
stamps.append(pub.group(1))
|
||||
if len(row) > 1 and isinstance(row[1], str):
|
||||
stamps.append(row[1][:14])
|
||||
for stamp in stamps:
|
||||
try:
|
||||
return datetime.strptime(stamp, "%Y%m%d%H%M%S").replace(
|
||||
tzinfo=timezone.utc
|
||||
).isoformat()
|
||||
except ValueError:
|
||||
continue
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def parse_gkg_row(row: list[str], terms: list[str], bulk_file: str = "") -> dict | None:
|
||||
"""Map one GKG CSV row into the ``events.gdelt`` event shape.
|
||||
|
||||
Returns None when the row has no usable URL or matches none of ``terms``.
|
||||
"""
|
||||
if len(row) < 8:
|
||||
return None
|
||||
url = (row[4] or "").strip()
|
||||
if not url.startswith(("http://", "https://")):
|
||||
return None
|
||||
|
||||
raw_themes = row[7] or ""
|
||||
themes = raw_themes.lower()
|
||||
matched = [t for t in terms if _term_hits_themes(t, themes)]
|
||||
if not matched:
|
||||
return None
|
||||
|
||||
extras = row[-1] if isinstance(row[-1], str) else ""
|
||||
title_match = _PAGE_TITLE_RE.search(extras)
|
||||
title = html.unescape(title_match.group(1)).strip() if title_match else None
|
||||
|
||||
lat = lon = loc_name = None
|
||||
for idx in (9, 10):
|
||||
if idx < len(row):
|
||||
lat, lon, loc_name = _gkg_location(row[idx])
|
||||
if lat is not None:
|
||||
break
|
||||
|
||||
theme_tokens = [t for t in raw_themes.split(";") if t]
|
||||
tags = matched + [
|
||||
t for t in theme_tokens
|
||||
if any(w in t.lower() for w in matched)
|
||||
]
|
||||
tags = list(dict.fromkeys(tags))[:10]
|
||||
|
||||
return {
|
||||
"source_type": "gdel-t2",
|
||||
"title": title,
|
||||
"body": (row[3] or "").strip() or None,
|
||||
"url": url,
|
||||
"location_lat": lat,
|
||||
"location_lon": lon,
|
||||
"location_name": loc_name,
|
||||
"source_timestamp": _gkg_timestamp(row, extras),
|
||||
"tags": tags,
|
||||
"raw": {
|
||||
"gkg_record_id": row[0],
|
||||
"source_common_name": row[3],
|
||||
"source_collection": row[2],
|
||||
"themes": theme_tokens[:12],
|
||||
"tone": _gkg_tone(row[15]) if len(row) > 15 else None,
|
||||
"bulk_file": bulk_file,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
async def ingest_gdelt_bulk(query: str = "", max_events: int | None = None) -> int:
|
||||
"""Publish new articles from the newest 15-minute GKG bulk file.
|
||||
|
||||
No API key, no per-IP quota, and the existing URL dedupe means re-reading
|
||||
the same file after a restart publishes nothing new.
|
||||
"""
|
||||
global _gdelt_bulk_last_file
|
||||
cap = GDELT_BULK_MAX_EVENTS if max_events is None else max_events
|
||||
|
||||
async with httpx.AsyncClient(
|
||||
timeout=120, headers=_ua_headers(), follow_redirects=True,
|
||||
) as client:
|
||||
index = await client.get(GDELT_BULK_LASTUPDATE)
|
||||
index.raise_for_status()
|
||||
picked = select_gdelt_bulk_url(index.text)
|
||||
if picked is None:
|
||||
logger.warning("GDELT bulk: no .gkg file listed in lastupdate.txt")
|
||||
return 0
|
||||
filename, url = picked
|
||||
if filename == _gdelt_bulk_last_file:
|
||||
logger.debug("GDELT bulk: %s already ingested; nothing new", filename)
|
||||
return 0
|
||||
archive = await client.get(url)
|
||||
archive.raise_for_status()
|
||||
|
||||
terms = gdelt_query_terms(query)
|
||||
events: list[dict] = []
|
||||
scanned = 0
|
||||
with zipfile.ZipFile(io.BytesIO(archive.content)) as zf:
|
||||
member = zf.namelist()[0]
|
||||
with zf.open(member) as fh:
|
||||
for line in io.TextIOWrapper(fh, encoding="utf-8", errors="replace"):
|
||||
if not line.strip():
|
||||
continue
|
||||
scanned += 1
|
||||
event = parse_gkg_row(line.rstrip("\r\n").split("\t"), terms, filename)
|
||||
if event is not None and len(events) < cap:
|
||||
events.append(event)
|
||||
|
||||
published = await _publish_unknown("events.gdelt", events)
|
||||
_gdelt_bulk_last_file = filename
|
||||
logger.info(
|
||||
"GDELT bulk %s: %d/%d rows matched %s, %d new articles published",
|
||||
filename, len(events), scanned, "/".join(terms), published,
|
||||
)
|
||||
return published
|
||||
|
||||
|
||||
async def ingest_gdelt(query: str = "", max_articles: int = 50):
|
||||
"""GDELT articles: throttle-free 15-minute bulk file first, DOC API fallback.
|
||||
|
||||
The bulk path carries the coverage; the DOC 2.0 call (with its 429 backoff)
|
||||
only runs when the bulk fetch itself fails, so the per-IP quota is no longer
|
||||
on the hot path.
|
||||
"""
|
||||
if GDELT_BULK_ENABLED:
|
||||
try:
|
||||
return await ingest_gdelt_bulk(query=query)
|
||||
except Exception as exc: # noqa: BLE001 — any bulk failure falls back
|
||||
logger.warning(
|
||||
"GDELT bulk fetch failed (%s: %s); falling back to DOC API",
|
||||
type(exc).__name__, str(exc)[:160],
|
||||
)
|
||||
return await _ingest_gdelt_doc(query=query, max_articles=max_articles)
|
||||
|
||||
|
||||
def _parse_gdelt_tone(tone: str) -> float | None:
|
||||
"""Parse GDELT tone string to a -1..1 sentiment score."""
|
||||
try:
|
||||
|
|
@ -641,9 +283,10 @@ async def ingest_eonet():
|
|||
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
|
||||
for event in events:
|
||||
await publish_event("events.disaster", event)
|
||||
logger.info("Ingested %d EONET events", len(events))
|
||||
return len(events)
|
||||
|
||||
|
||||
# ─── CISA KEV ───────────────────────────────────────────────────────────
|
||||
|
|
@ -687,9 +330,10 @@ async def ingest_cisa_kev():
|
|||
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
|
||||
for event in events:
|
||||
await publish_event("events.disaster", event)
|
||||
logger.info("Ingested %d CISA KEV rows", len(events))
|
||||
return len(events)
|
||||
|
||||
|
||||
# ─── Social Signals (Twitter/X-like placeholder) ────────────────────────
|
||||
|
|
|
|||
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:
|
||||
row = (await session.execute(text(
|
||||
"""
|
||||
SELECT min(t) AS tmin, max(t) AS tmax FROM (
|
||||
SELECT min(bucket) AS t FROM vessel_tracks_1min
|
||||
UNION ALL SELECT max(bucket) FROM vessel_tracks_1min
|
||||
UNION ALL SELECT min(bucket) FROM aircraft_tracks_1min
|
||||
UNION ALL SELECT max(bucket) FROM aircraft_tracks_1min
|
||||
UNION ALL SELECT min(poll_at) FROM vessels
|
||||
UNION ALL SELECT max(poll_at) FROM vessels
|
||||
) s
|
||||
SELECT
|
||||
LEAST(
|
||||
(SELECT min(bucket) FROM vessel_tracks_1min),
|
||||
(SELECT min(bucket) FROM aircraft_tracks_1min)
|
||||
) AS tmin,
|
||||
GREATEST(
|
||||
(SELECT max(bucket) FROM vessel_tracks_1min),
|
||||
(SELECT max(bucket) FROM aircraft_tracks_1min)
|
||||
) AS tmax
|
||||
"""
|
||||
))).mappings().first()
|
||||
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
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
BBox = tuple[float, float, float, float] # minlon, minlat, maxlon, maxlat
|
||||
|
||||
|
||||
def _uuid_str(value: object) -> str | None:
|
||||
try:
|
||||
return str(UUID(str(value)))
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
def point_in_bbox(lon: float, lat: float, bbox: BBox | None) -> bool:
|
||||
"""True if (lon, lat) sits inside an axis-aligned viewport."""
|
||||
if bbox is None:
|
||||
|
|
@ -34,7 +26,6 @@ class ConnectionManager:
|
|||
def __init__(self) -> None:
|
||||
self._queues: dict[str, asyncio.Queue] = {}
|
||||
self._viewports: dict[str, BBox] = {}
|
||||
self._watched: dict[str, set[str]] = {}
|
||||
|
||||
def register(self, client_id: str, maxsize: int = 256) -> asyncio.Queue:
|
||||
q: asyncio.Queue = asyncio.Queue(maxsize=maxsize)
|
||||
|
|
@ -44,21 +35,6 @@ class ConnectionManager:
|
|||
def unregister(self, client_id: str) -> None:
|
||||
self._queues.pop(client_id, None)
|
||||
self._viewports.pop(client_id, None)
|
||||
self._watched.pop(client_id, None)
|
||||
|
||||
def set_watched_geofences(self, client_id: str, ids: list[str]) -> None:
|
||||
"""Watch these fence UUIDs so geofence_alert delivers off-viewport.
|
||||
|
||||
Invalid UUIDs are ignored. Empty list = watch none (viewport-only).
|
||||
"""
|
||||
if client_id not in self._queues:
|
||||
return
|
||||
watched: set[str] = set()
|
||||
for raw in ids:
|
||||
uid = _uuid_str(raw)
|
||||
if uid is not None:
|
||||
watched.add(uid)
|
||||
self._watched[client_id] = watched
|
||||
|
||||
def set_viewport(self, client_id: str, bbox: BBox) -> None:
|
||||
if client_id in self._queues:
|
||||
|
|
@ -83,21 +59,13 @@ class ConnectionManager:
|
|||
) -> int:
|
||||
"""Enqueue `{type, payload}` for clients whose viewport contains the point.
|
||||
|
||||
kind=geofence_alert also delivers when payload.geofence_id is in the
|
||||
client's watch set (even if the point is off-viewport). Other kinds
|
||||
stay viewport-only. Drops the oldest queued message if a client's
|
||||
buffer is full. Returns the number of clients that got a copy.
|
||||
Drops the oldest queued message if a client's buffer is full so a slow
|
||||
tab cannot stall ingest. Returns the number of clients that got a copy.
|
||||
"""
|
||||
msg = {"type": kind, "payload": payload}
|
||||
sent = 0
|
||||
gid = _uuid_str(payload.get("geofence_id")) if kind == "geofence_alert" else None
|
||||
for client_id, queue in list(self._queues.items()):
|
||||
in_view = point_in_bbox(lon, lat, self._viewports.get(client_id))
|
||||
if kind == "geofence_alert":
|
||||
watching = gid is not None and gid in self._watched.get(client_id, set())
|
||||
if not in_view and not watching:
|
||||
continue
|
||||
elif not in_view:
|
||||
if not point_in_bbox(lon, lat, self._viewports.get(client_id)):
|
||||
continue
|
||||
if queue.full():
|
||||
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;
|
||||
}
|
||||
|
|
@ -20,10 +20,8 @@ services:
|
|||
# networks (and ISP abuse-mitigation blackholes) block, so rebuilding it
|
||||
# on every CI deploy made the pipeline flaky. Rebuild manually when the
|
||||
# base image or extensions need bumping:
|
||||
# docker build -f Dockerfile.pg -t localhost/osint-dashboard-pg:latest .
|
||||
# FORCE_RECREATE_DB=1 scripts/compose-reup.sh db
|
||||
# docker compose build db && docker compose up -d db
|
||||
image: localhost/osint-dashboard-pg:latest
|
||||
pull_policy: never
|
||||
container_name: osint-db
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
|
|
@ -54,7 +52,6 @@ services:
|
|||
|
||||
nats:
|
||||
image: nats:2.10
|
||||
pull_policy: missing
|
||||
platform: linux/arm64
|
||||
container_name: osint-nats
|
||||
restart: unless-stopped
|
||||
|
|
@ -70,7 +67,6 @@ services:
|
|||
dockerfile: Dockerfile
|
||||
platforms: ["linux/arm64"]
|
||||
image: localhost/osint-dashboard:latest
|
||||
pull_policy: never
|
||||
container_name: osint-ingester
|
||||
restart: unless-stopped
|
||||
profiles: ["ingest"]
|
||||
|
|
@ -97,15 +93,10 @@ services:
|
|||
FIRMS_DATASETS: ${FIRMS_DATASETS:-VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT}
|
||||
FIRMS_BBOX: ${FIRMS_BBOX:--180,-60,180,75}
|
||||
FIRMS_INTERVAL: ${FIRMS_INTERVAL:-900}
|
||||
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted; [email protected])}
|
||||
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted)}
|
||||
AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-}
|
||||
AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66}
|
||||
AISSTREAM_IN_INGEST: ${AISSTREAM_IN_INGEST:-0}
|
||||
VESSELAPI_API_KEY: ${VESSELAPI_API_KEY:-}
|
||||
VESSELAPI_BBOX: ${VESSELAPI_BBOX:-25.5,55.4,27.3,57.2}
|
||||
VESSELAPI_INTERVAL: ${VESSELAPI_INTERVAL:-17280}
|
||||
VESSELAPI_MAX_CALLS_PER_DAY: ${VESSELAPI_MAX_CALLS_PER_DAY:-5}
|
||||
VESSELAPI_IN_INGEST: ${VESSELAPI_IN_INGEST:-0}
|
||||
command: ["python", "app/run_ingester.py"]
|
||||
entrypoint: ["python", "app/run_ingester.py"]
|
||||
|
||||
|
|
@ -115,7 +106,6 @@ services:
|
|||
dockerfile: Dockerfile
|
||||
platforms: ["linux/arm64"]
|
||||
image: localhost/osint-dashboard:latest
|
||||
pull_policy: never
|
||||
container_name: osint-dashboard
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
|
|
@ -137,20 +127,10 @@ services:
|
|||
FIRMS_DATASET: ${FIRMS_DATASET:-VIIRS_NOAA20_NRT}
|
||||
FIRMS_DATASETS: ${FIRMS_DATASETS:-VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT}
|
||||
FIRMS_BBOX: ${FIRMS_BBOX:--180,-60,180,75}
|
||||
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted; [email protected])}
|
||||
NOMINATIM_URL: ${NOMINATIM_URL:-https://nominatim.openstreetmap.org}
|
||||
NOMINATIM_MIN_INTERVAL: ${NOMINATIM_MIN_INTERVAL:-1.0}
|
||||
OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted)}
|
||||
AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-}
|
||||
AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66}
|
||||
AISSTREAM_IN_APP: ${AISSTREAM_IN_APP:-1}
|
||||
VESSELAPI_API_KEY: ${VESSELAPI_API_KEY:-}
|
||||
VESSELAPI_BBOX: ${VESSELAPI_BBOX:-25.5,55.4,27.3,57.2}
|
||||
VESSELAPI_INTERVAL: ${VESSELAPI_INTERVAL:-17280}
|
||||
VESSELAPI_MAX_CALLS_PER_DAY: ${VESSELAPI_MAX_CALLS_PER_DAY:-5}
|
||||
VESSELAPI_IN_APP: ${VESSELAPI_IN_APP:-1}
|
||||
# ── Self-hosted TiTiler (Sentinel-1 SAR tiles) ──
|
||||
TITILER_PUBLIC_BASE: ${TITILER_PUBLIC_BASE:-/titiler}
|
||||
TITILER_INTERNAL_URL: ${TITILER_INTERNAL_URL:-http://titiler:8000}
|
||||
ports:
|
||||
- "127.0.0.1:8000:8000"
|
||||
deploy:
|
||||
|
|
@ -163,35 +143,12 @@ services:
|
|||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
# ── Self-hosted TiTiler (Sentinel-1 SAR COG → XYZ tiles) ────────────────
|
||||
# Warps the signed Planetary Computer COG into WebMercator XYZ tiles so the
|
||||
# browser never loads a multi-GB GeoTIFF. The FastAPI app signs the COG URL
|
||||
# and returns a /titiler/... template; nginx routes /titiler/ here.
|
||||
# Listens on 8000 INSIDE the container (the app already owns host 8000);
|
||||
# published on host loopback 127.0.0.1:8001 only.
|
||||
titiler:
|
||||
image: ghcr.io/developmentseed/titiler:latest@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:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
platforms: ["linux/arm64"]
|
||||
image: localhost/osint-dashboard:latest
|
||||
pull_policy: never
|
||||
container_name: osint-camera-scraper
|
||||
restart: unless-stopped
|
||||
profiles: ["ingest"]
|
||||
|
|
@ -230,7 +187,6 @@ services:
|
|||
dockerfile: Dockerfile
|
||||
platforms: ["linux/arm64"]
|
||||
image: localhost/osint-news-scraper:latest
|
||||
pull_policy: never
|
||||
container_name: osint-news-scraper
|
||||
restart: unless-stopped
|
||||
profiles: ["ingest"]
|
||||
|
|
@ -256,7 +212,6 @@ services:
|
|||
dockerfile: Dockerfile
|
||||
platforms: ["linux/arm64"]
|
||||
image: localhost/osint-news-summarizer:latest
|
||||
pull_policy: never
|
||||
container_name: osint-news-summarizer
|
||||
restart: unless-stopped
|
||||
profiles: ["ingest"]
|
||||
|
|
@ -279,9 +234,6 @@ services:
|
|||
NEWS_SUMMARIZE_INTERVAL_S: ${NEWS_SUMMARIZE_INTERVAL_S:-900}
|
||||
NEWS_SUMMARIZE_RUN_ON_START: ${NEWS_SUMMARIZE_RUN_ON_START:-1}
|
||||
NEWS_SUMMARIZE_FORCE: ${NEWS_SUMMARIZE_FORCE:-0}
|
||||
TZ: ${TZ:-America/New_York}
|
||||
NEWS_RECAP_HOUR: ${NEWS_RECAP_HOUR:-23}
|
||||
NEWS_RECAP_MINUTE: ${NEWS_RECAP_MINUTE:-0}
|
||||
command: ["python", "run_news_summarizer.py"]
|
||||
|
||||
volumes:
|
||||
|
|
|
|||
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.
|
||||
|
||||
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 GIBS basemaps | Frontend tiles via `app/gibs_map.py` | No key. CORS `*`. |
|
||||
| GIBS VIIRS thermal tiles | Documented, not wired as overlay | Same GIBS stack; no key. |
|
||||
| Cameras | Scraper → `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. |
|
||||
|
||||
**Action for existing fire ingest:** NASA will stop Suomi NPP product delivery on **2026-11-01**. Switch `FIRMS_DATASET` from `VIIRS_SNPP_NRT` to `VIIRS_NOAA20_NRT` and/or `VIIRS_NOAA21_NRT` before then.[20]
|
||||
|
|
@ -261,7 +261,7 @@ Use later if you want commuter rail / subway vehicle positions (LA Metro, MTA, e
|
|||
|
||||
## 6. Open video / camera feeds (official public only)
|
||||
|
||||
Do **not** add Insecam-style random IP cams as a new source. The scraper already has a public list; 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
|
||||
|
||||
|
|
@ -304,7 +304,7 @@ Do not call the YouTube Data API unless you want search. Embedding existing stre
|
|||
|
||||
### 6.5 Skip
|
||||
|
||||
- Insecam / random “public IP cam” aggregators — ToS / privacy.
|
||||
- Insecam / random “public IP cam” aggregators — ToS / privacy / already covered by masscan ethics.
|
||||
- TrafficLand, EarthCam commercial APIs.
|
||||
- SkylineWebcams — scraping, not an API.
|
||||
|
||||
|
|
@ -523,7 +523,7 @@ Attribution bar (required): OpenSky / ADSB.lol ODbL / Amtraker / RainViewer / IE
|
|||
|
||||
## 12. Legal / ethics (non-negotiable)
|
||||
|
||||
- RTSP policy unchanged (never emit `rtsp://` hrefs).
|
||||
- Masscan / RTSP policy unchanged.
|
||||
- AISStream: server-side only; do not put the key in JS.[5]
|
||||
- OpenSky: non-commercial unless licensed; cite if you publish.[2]
|
||||
- ADSB.lol: ODbL share-alike on derived databases.[4]
|
||||
|
|
|
|||
110
docs/news.md
110
docs/news.md
|
|
@ -16,7 +16,7 @@ urls.txt (RSS + homepages)
|
|||
news-scraper (Scrapy, continuous) ──► articles table (osint-db)
|
||||
│ │
|
||||
│ ▼
|
||||
news-summarizer (Nous Portal, every 15m + 23:00 recap) ──► article_summaries + news_items
|
||||
news-summarizer (Nous Portal, every 15m) ──► article_summaries + news_items
|
||||
│
|
||||
▼
|
||||
GET /api/news · /api/news/summaries · /api/news/ticker · /api/news/map
|
||||
|
|
@ -43,18 +43,13 @@ feeds (`GET /api/news` exact key set is unchanged on purpose).
|
|||
URLs from `urls.txt` (homepages autodiscover RSS; feed URLs are parsed
|
||||
directly), follows each `<item>` link, extracts the main article body, and
|
||||
the `PostgresPipeline` writes to `articles` with URL-based dedup
|
||||
(`ON CONFLICT (url) DO NOTHING`). Items whose parsed publish date is more
|
||||
than 2 hours in the future are dropped at ingest (`future_dated_dropped`)
|
||||
and never surface via `/api/news`, which additionally hides any
|
||||
`articles.timestamp > now()` row until its date arrives.
|
||||
(`ON CONFLICT (url) DO NOTHING`).
|
||||
2. **Summarizer** — `news/summerizer/run_news_summarizer.py` runs
|
||||
`summarizer.py` every `NEWS_SUMMARIZE_INTERVAL_S` (default 900) over the
|
||||
last `SUMMARY_WINDOW_MINUTES` (default 15), and again at 23:00
|
||||
`America/New_York` (`TZ`) over the last 24 hours as a daily recap
|
||||
(`kind=daily_recap`). Both map-reduce through Nous Portal (`SUMMARY_MODEL`
|
||||
/ Settings, default `Hermes-4.3-36B`), write the English brief to
|
||||
`article_summaries` (column `model` is the LLM id; `kind` is
|
||||
`interval` or `daily_recap`), and flagged ticker/map rows to `news_items`.
|
||||
`summarizer.py` every `NEWS_SUMMARIZE_INTERVAL_S` (default 900). It reads
|
||||
articles from the last `SUMMARY_WINDOW_MINUTES` (default 15), map-reduces
|
||||
them through Nous Portal (`SUMMARY_MODEL` / Settings, default
|
||||
`Hermes-4.3-36B`), writes the English brief to `article_summaries` (column
|
||||
`model` is the LLM id), and flagged ticker/map rows to `news_items`.
|
||||
|
||||
Loops are serial (two crawls/summaries never overlap). Interval idempotency:
|
||||
if `article_summaries` already has a row in the last interval, the summarizer
|
||||
|
|
@ -63,46 +58,8 @@ if `article_summaries` already has a row in the last interval, the summarizer
|
|||
|
||||
The `articles` and `article_summaries` tables are created by the idempotent
|
||||
alembic migration `003_news` (also created by the scraper's own
|
||||
`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items` and
|
||||
`article_scores` is `012_article_scores` (also created by the summarizer's own
|
||||
`ensure_tables()`). Container startup order doesn't matter.
|
||||
|
||||
## Grading and selection
|
||||
|
||||
The map phase grades every article 0-100 against the rubric in the map prompt
|
||||
(90-100 breaking geopolitical/military/security or major disaster, 70-89
|
||||
significant national/international news, 40-69 notable regional/economic/tech/
|
||||
health, 10-39 routine crime and local interest, 0-9 noise: sport, celebrity,
|
||||
entertainment, market tape, promotional and event-calendar listings). The
|
||||
summarizer parses the first `Score:` line in each `Article <n>:` block, clamps
|
||||
it to 0-100, and falls back to the `Importance:` label (critical 95, high 78,
|
||||
medium 50, low 22, none 5) when the line is missing or unparsable — a block is
|
||||
never dropped and the fallback count is logged per batch. Only blocks scoring
|
||||
`>= SUMMARY_MIN_SCORE` (default 60) reach the reduce prompt, best first, capped
|
||||
at `SUMMARY_TOP_N` (default 12). If nothing clears the bar, up to
|
||||
`SUMMARY_FALLBACK_TOP` blocks (default 3) scoring at least
|
||||
`SUMMARY_FALLBACK_MIN_SCORE` (default 40) are used; when none does, or when
|
||||
`SUMMARY_FALLBACK_TOP=0`, the reduce phase receives an empty DATA section and
|
||||
writes the empty-brief response instead of promoting noise. The reduce prompt
|
||||
no longer asks for filler: it leads with the highest-scoring stories and never
|
||||
promotes an item above its score. Every graded article is persisted to
|
||||
`article_scores` (score, category, selected, model, summary_id) so the operator
|
||||
can tune the thresholds against real data.
|
||||
|
||||
Syndicated wire copy is collapsed **before** the threshold and cap, so
|
||||
`SUMMARY_TOP_N` counts distinct stories instead of stations: the same headline
|
||||
carried by seven Hearst domains is one story, not seven. Titles are normalised
|
||||
first (lowercase, punctuation flattened, a trailing ` - KCCI` / ` | CNN` /
|
||||
` — AP` source suffix dropped when it is short and digit-free), then two blocks
|
||||
are the same story when the normalised titles are equal or at least
|
||||
`SUMMARY_DEDUPE_SIMILARITY` similar (default 0.85; word-set Jaccard or
|
||||
word-sequence `difflib` ratio). The highest-scoring copy represents the story
|
||||
(ties → earliest); differing `category` values and titles that disagree on any
|
||||
number are never merged. Duplicates are still written to `article_scores` with
|
||||
`selected=false` and `duplicate_of` = the surviving `article_id`, so nothing is
|
||||
lost for tuning. `SUMMARY_DEDUPE=0` disables dedupe entirely; raising
|
||||
`SUMMARY_DEDUPE_SIMILARITY` toward 0.95 makes it stricter. Dedupe is pure string
|
||||
work — no extra LLM call.
|
||||
`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items`.
|
||||
Container startup order doesn't matter.
|
||||
|
||||
## Keys and Settings
|
||||
|
||||
|
|
@ -159,22 +116,18 @@ Key set **unchanged** (no `lat`/`lon` on articles; geo lives on `/api/news/map`)
|
|||
"id": 1,
|
||||
"summary_text": "English markdown brief…",
|
||||
"batch_timestamp": "2026-08-24T18:10:00Z",
|
||||
"model": "Hermes-4.3-36B",
|
||||
"kind": "daily_recap"
|
||||
"model": "Hermes-4.3-36B"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
`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`.
|
||||
`model` is additive. Empty DB → `[]` (no crash).
|
||||
|
||||
### GET /api/news/ticker — HUD headlines
|
||||
### GET /api/news/ticker — flagged 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.
|
||||
Critical/high `news_items` with `kind=ticker` only. Do **not** reuse
|
||||
`GET /api/alerts`. Bottom HUD `#nt-track` scrolls these rows, not a dump of
|
||||
the whole brief.
|
||||
|
||||
| Query param | Meaning | Default |
|
||||
|---|---|---|
|
||||
|
|
@ -268,10 +221,10 @@ markdown json fences, then brace-slices:
|
|||
}
|
||||
```
|
||||
|
||||
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`.
|
||||
Persist ticker/map only for `importance` in `critical`/`high`. Map rows also
|
||||
need valid coords; Unknown / invented places are dropped. Caps: 12 ticker
|
||||
(≤140 chars, no markdown), 20 map. Empty ticker is allowed. `summary_en`
|
||||
lands in `article_summaries.summary_text`.
|
||||
|
||||
## Configuration (all via env / `.env`)
|
||||
|
||||
|
|
@ -281,22 +234,13 @@ map. `summary_en` lands in `article_summaries.summary_text`.
|
|||
| `NOUS_BASE_URL` | `https://inference-api.nousresearch.com/v1` | Read-only in Settings. |
|
||||
| `SUMMARY_MODEL` | `Hermes-4.3-36B` | Compose default. Operator-facing choice is Settings → `app_settings.SUMMARY_MODEL`. |
|
||||
| `NEWS_BATCH_SIZE` | `50` | Articles per map-phase batch (compose maps to container `BATCH_SIZE`). |
|
||||
| `SUMMARY_MIN_SCORE` | `60` | Map-phase score a block must reach to enter the reduce brief. |
|
||||
| `SUMMARY_TOP_N` | `12` | Max blocks passed to the reduce phase (best score first). |
|
||||
| `SUMMARY_FALLBACK_TOP` | `3` | Blocks used when nothing clears `SUMMARY_MIN_SCORE`; `0` = empty DATA. |
|
||||
| `SUMMARY_FALLBACK_MIN_SCORE` | `40` | Score floor for the fallback set; below it the reduce phase gets empty DATA. |
|
||||
| `SUMMARY_DEDUPE` | `1` | Collapse syndicated wire copies before selection; `0` skips dedupe entirely. |
|
||||
| `SUMMARY_DEDUPE_SIMILARITY` | `0.85` | Normalised-title similarity at which two blocks count as the same story (1.0 = verbatim only). |
|
||||
| `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles (window is `(now - N, now]`; future-dated rows are ignored). |
|
||||
| `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles. |
|
||||
| `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). |
|
||||
| `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). |
|
||||
| `TZ` | `America/New_York` | Timezone for the 23:00 daily recap. |
|
||||
| `NEWS_RECAP_HOUR` | `23` | Local hour of the daily 24h recap. |
|
||||
| `NEWS_RECAP_MINUTE` | `0` | Local minute of the daily recap. |
|
||||
| `NEWS_SCRAPE_RUN_ON_START` | `1` | Run one scrape immediately on container start. |
|
||||
| `NEWS_SUMMARIZE_RUN_ON_START` | `1` | Run one summarize immediately on container start. |
|
||||
| `NEWS_SUMMARIZE_FORCE` | `0` | `1` ignores the interval/recap idempotency skip (double-pins on recreate). |
|
||||
| `INCLUDE_FUTURES` | `0` | Legacy. Ignored — prompts never inject futures/market tape. |
|
||||
| `NEWS_SUMMARIZE_FORCE` | `0` | `1` ignores the interval idempotency skip (double-pins on recreate). |
|
||||
| `INCLUDE_FUTURES` | `0` | Legacy futures-prices coupling. OFF for OSINT; set `1` + install `yfinance` to enable. |
|
||||
| `NEWS_LOG_LEVEL` | `INFO` | Scrapy log level. |
|
||||
| `OSINT_USER_AGENT` | `osint-dashboard-news-summarizer` | Sent on every outbound Nous call. |
|
||||
| `TELEGRAM_TOKEN` / `TELEGRAM_CHAT_ID` | *(blank)* | Reserved for the (out-of-scope) Telegram delivery bot. |
|
||||
|
|
@ -310,11 +254,11 @@ No Hermes-4 reasoning system prompt. Reduce uses `json_mode=True`.
|
|||
|
||||
## Prompts
|
||||
|
||||
Both prompts are env-overridable. Defaults recap the articles actually
|
||||
provided, ranked by breaking important news, and ignore futures / commodity
|
||||
tape. ticker/map may be empty; `summary_en` must still be a real brief.
|
||||
`RECAP_PROMPT` (23:00, 24h window) is the daily recap; `SUMMARY_PROMPT` is the
|
||||
15-min analyst. `INCLUDE_FUTURES` is ignored.
|
||||
Both prompts are env-overridable — the default `MAP_PROMPT` is OSINT-neutral
|
||||
(facts, locations, entities, category, OSINT signal per article; English) and
|
||||
the default `SUMMARY_PROMPT` demands the reduce JSON above (with a
|
||||
"no qualifying events" escape hatch). Upstream's futures/markets prompt
|
||||
language is gated behind `INCLUDE_FUTURES=1`.
|
||||
|
||||
## Tests
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
@ -3,7 +3,6 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import re
|
||||
from email.utils import parsedate_to_datetime
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
|
@ -31,26 +30,3 @@ def article_timestamp(pub_date: str | None) -> datetime.datetime:
|
|||
except ValueError:
|
||||
pass
|
||||
return datetime.datetime.now(datetime.timezone.utc)
|
||||
|
||||
|
||||
# Whole-title CDATA wrapper only. Keep in sync with app/news_title.py —
|
||||
# the scraper image and the API image do not share a package.
|
||||
_CDATA_WRAPPER = re.compile(
|
||||
r"\A\s*<!\[CDATA\[(.*?)\]\]>\s*\Z",
|
||||
re.DOTALL,
|
||||
)
|
||||
|
||||
|
||||
def unwrap_cdata_title(title):
|
||||
"""Strip a surrounding CDATA wrapper. Anything else is unchanged.
|
||||
|
||||
``<![CDATA[Hello]]>`` and ``\\n <![CDATA[Hello]]>`` become
|
||||
``Hello``. Real HTML (``<b>Hello</b>``) and a title that merely contains
|
||||
the markers are returned as-is. Non-strings pass through.
|
||||
"""
|
||||
if not isinstance(title, str):
|
||||
return title
|
||||
match = _CDATA_WRAPPER.match(title)
|
||||
if match is None:
|
||||
return title
|
||||
return match.group(1).strip()
|
||||
|
|
|
|||
|
|
@ -3,51 +3,10 @@
|
|||
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
|
||||
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import psycopg2
|
||||
import os
|
||||
from scrapy.exceptions import DropItem
|
||||
|
||||
from newsScraper.feed_util import unwrap_cdata_title
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# Feed items dated further ahead than this are event listings (or clock skew
|
||||
# from the source), not news. Dropping them keeps `ORDER BY timestamp DESC`
|
||||
# from pinning the top of /api/news for days. See docs/news.md.
|
||||
FUTURE_TOLERANCE = datetime.timedelta(hours=2)
|
||||
|
||||
|
||||
def _parsed_timestamp(value):
|
||||
"""Return an aware UTC datetime for an item timestamp, or None.
|
||||
|
||||
None means "could not parse" — callers must keep such items, exactly as
|
||||
before this guard existed (undated items currently get now() upstream).
|
||||
"""
|
||||
if isinstance(value, datetime.datetime):
|
||||
ts = value
|
||||
elif isinstance(value, str) and value.strip():
|
||||
try:
|
||||
ts = datetime.datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=datetime.timezone.utc)
|
||||
return ts.astimezone(datetime.timezone.utc)
|
||||
|
||||
|
||||
def is_future_dated(value, now=None, tolerance=FUTURE_TOLERANCE):
|
||||
"""True when a parsed publish timestamp is more than `tolerance` ahead."""
|
||||
ts = _parsed_timestamp(value)
|
||||
if ts is None:
|
||||
return False
|
||||
now = now or datetime.datetime.now(datetime.timezone.utc)
|
||||
return ts > now + tolerance
|
||||
|
||||
|
||||
class PostgresPipeline:
|
||||
|
||||
def __init__(self, db_config):
|
||||
|
|
@ -55,8 +14,6 @@ class PostgresPipeline:
|
|||
self.db_config = db_config
|
||||
# 2. Initialize the set here so it exists when process_item is called
|
||||
self.seen_urls = set()
|
||||
# 3. Future-dated drops, reported once per run in close_spider()
|
||||
self.future_dated_dropped = 0
|
||||
|
||||
@classmethod
|
||||
def from_crawler(cls, crawler):
|
||||
|
|
@ -97,16 +54,9 @@ class PostgresPipeline:
|
|||
|
||||
def process_item(self, item, spider):
|
||||
url = item['url']
|
||||
if is_future_dated(item.get('timestamp')):
|
||||
self.future_dated_dropped += 1
|
||||
stats = getattr(getattr(spider, 'crawler', None), 'stats', None)
|
||||
if stats is not None:
|
||||
stats.inc_value('future_dated_dropped')
|
||||
raise DropItem(f"Future-dated item: {url}")
|
||||
if url in self.seen_urls:
|
||||
raise DropItem(f"Duplicate URL (in-memory): {url}")
|
||||
self.seen_urls.add(url)
|
||||
item['title'] = unwrap_cdata_title(item['title'])
|
||||
try:
|
||||
self.cur.execute("""
|
||||
INSERT INTO articles (title, url, content, domain, timestamp)
|
||||
|
|
@ -132,11 +82,6 @@ class PostgresPipeline:
|
|||
raise
|
||||
|
||||
def close_spider(self, spider):
|
||||
if self.future_dated_dropped:
|
||||
spider.logger.info(
|
||||
"Dropped %d future-dated item(s) (>%s ahead)",
|
||||
self.future_dated_dropped, FUTURE_TOLERANCE,
|
||||
)
|
||||
self.cur.close()
|
||||
self.connection.close()
|
||||
|
||||
|
|
|
|||
|
|
@ -7,14 +7,13 @@ WORKDIR /app
|
|||
|
||||
# libpq-dev + gcc for psycopg2 build/adapters; keep the image lean.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
libpq-dev gcc tzdata \
|
||||
libpq-dev gcc \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY summarizer.py run_news_summarizer.py intel.py nous_client.py gazetteer.py ./
|
||||
COPY data/ ./data/
|
||||
COPY summarizer.py run_news_summarizer.py intel.py nous_client.py ./
|
||||
|
||||
# Security: run as a non-privileged user.
|
||||
RUN useradd -m summarizer_user
|
||||
|
|
|
|||
|
|
@ -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,14 +1,12 @@
|
|||
"""Pure parser for the news-summarizer map grading / reduce JSON / geo contract."""
|
||||
"""Pure parser for the news-summarizer reduce JSON / geo / importance contract."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
import json
|
||||
import re
|
||||
|
||||
_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)
|
||||
|
||||
|
|
@ -17,94 +15,6 @@ MAP_HEADLINE_MAX = 160
|
|||
TICKER_CAP = 12
|
||||
MAP_CAP = 20
|
||||
|
||||
# ── Map-phase grading (score parsing + selection, pure) ────────────────────
|
||||
# Importance label → stand-in score, used when the map model omits Score:.
|
||||
IMPORTANCE_SCORE = {"critical": 95, "high": 78, "medium": 50, "low": 22, "none": 5}
|
||||
NEUTRAL_SCORE = 50
|
||||
|
||||
_ARTICLE_RE = re.compile(r"^[ \t>*_#\-]*Article[ \t]+(\d{1,3})[ \t]*:", re.IGNORECASE | re.MULTILINE)
|
||||
_SCORE_RE = re.compile(r"Score:\s*(\d{1,3})", re.IGNORECASE)
|
||||
_IMPORTANCE_RE = re.compile(r"Importance:\s*(critical|high|medium|low|none)", re.IGNORECASE)
|
||||
_CATEGORY_RE = re.compile(r"Category:\s*(.+)", re.IGNORECASE)
|
||||
_LOCATION_RE = re.compile(r"Location:[ \t]*(.+)", re.IGNORECASE)
|
||||
_CONFIDENCE_RE = re.compile(
|
||||
r"Confidence:[ \t]*(exact|city|region|country|approx)", re.IGNORECASE
|
||||
)
|
||||
# Numeric token, optional degree sign, optional hemisphere letter. The
|
||||
# trailing lookahead keeps "12.3 South Sudan" from reading the S of a word
|
||||
# as a south marker (and from truncating the number to dodge it).
|
||||
_LAT_RE = re.compile(
|
||||
r"Lat:[ \t]*([+-]?\d+(?:\.\d+)?)[ \t]*°?[ \t]*([NS])?(?![A-Za-z\d.])", re.IGNORECASE
|
||||
)
|
||||
_LON_RE = re.compile(
|
||||
r"Lon:[ \t]*([+-]?\d+(?:\.\d+)?)[ \t]*°?[ \t]*([EW])?(?![A-Za-z\d.])", re.IGNORECASE
|
||||
)
|
||||
|
||||
LOCATION_NAME_MAX = 120
|
||||
_UNKNOWN_LOCATIONS = frozenset(
|
||||
{"unknown", "n/a", "none", "null", "unspecified", "not specified"}
|
||||
)
|
||||
GEO_CONFIDENCES = frozenset({"exact", "city", "region", "country", "approx"})
|
||||
|
||||
|
||||
def clean_location_name(raw) -> str | None:
|
||||
"""Normalise a model-written place name; Unknown/empty -> None.
|
||||
|
||||
Strips markdown decoration and trailing periods, caps the length.
|
||||
Never invents a place: a name the model did not write stays None.
|
||||
"""
|
||||
if not isinstance(raw, str):
|
||||
return None
|
||||
value = raw.strip().rstrip(".").strip().strip("*_`").strip()
|
||||
if not value:
|
||||
return None
|
||||
lowered = value.lower()
|
||||
if lowered in _UNKNOWN_LOCATIONS or lowered.startswith("unknown"):
|
||||
return None
|
||||
return value[:LOCATION_NAME_MAX]
|
||||
|
||||
|
||||
def _coord_from_block(text: str, kind: str) -> float | None:
|
||||
"""One Lat:/Lon: value from a block; hemisphere S/W negates."""
|
||||
match = (_LAT_RE if kind == "lat" else _LON_RE).search(text)
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
value = float(match.group(1))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
hemisphere = (match.group(2) or "").upper()
|
||||
if hemisphere in ("S", "W") and value > 0:
|
||||
value = -value
|
||||
return value
|
||||
|
||||
|
||||
def _geo_from_block(text: str) -> dict:
|
||||
"""Structured geo for one article block (pure).
|
||||
|
||||
Model coords are only trusted alongside a real place name — coords
|
||||
next to ``Location: Unknown`` are dropped (never invent a place).
|
||||
Missing/invalid coords leave lat/lon None for the offline gazetteer
|
||||
step; confidence defaults to "city" when the model gave coords but
|
||||
no Confidence line.
|
||||
"""
|
||||
loc_match = _LOCATION_RE.search(text)
|
||||
location_name = clean_location_name(loc_match.group(1) if loc_match else None)
|
||||
lat = lon = None
|
||||
confidence = None
|
||||
if location_name is not None:
|
||||
coords = clamp_coords(_coord_from_block(text, "lat"), _coord_from_block(text, "lon"))
|
||||
if coords is not None:
|
||||
lat, lon = coords
|
||||
conf_match = _CONFIDENCE_RE.search(text)
|
||||
confidence = conf_match.group(1).lower() if conf_match else "city"
|
||||
return {
|
||||
"location_name": location_name,
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"location_confidence": confidence,
|
||||
}
|
||||
|
||||
|
||||
def parse_reduce_json(raw: str) -> dict:
|
||||
try:
|
||||
|
|
@ -148,29 +58,19 @@ def _trimmed_headline(row: dict, limit: int) -> str:
|
|||
|
||||
|
||||
def select_ticker(rows: list) -> list:
|
||||
flagged = []
|
||||
medium = []
|
||||
low = []
|
||||
out = []
|
||||
for row in rows:
|
||||
imp = row.get("importance")
|
||||
if imp not in _RANK:
|
||||
if row.get("importance") not in _KEEP:
|
||||
continue
|
||||
headline = _trimmed_headline(row, TICKER_HEADLINE_MAX)
|
||||
if not headline:
|
||||
continue
|
||||
item = dict(row)
|
||||
item["headline"] = headline
|
||||
if imp in _KEEP:
|
||||
flagged.append(item)
|
||||
elif imp == "medium":
|
||||
medium.append(item)
|
||||
else:
|
||||
low.append(item)
|
||||
if len(flagged) >= TICKER_CAP:
|
||||
out.append(item)
|
||||
if len(out) >= TICKER_CAP:
|
||||
break
|
||||
if flagged:
|
||||
return flagged[:TICKER_CAP]
|
||||
return (medium + low)[:TICKER_CAP]
|
||||
return out
|
||||
|
||||
|
||||
def select_map(items: list) -> list:
|
||||
|
|
@ -191,401 +91,3 @@ def select_map(items: list) -> list:
|
|||
if len(out) >= MAP_CAP:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
# ── Map grading ────────────────────────────────────────────────────────────
|
||||
|
||||
def _clamp_score(value: int) -> int:
|
||||
return max(0, min(100, int(value)))
|
||||
|
||||
|
||||
def _score_from_block(text: str) -> tuple[int, bool]:
|
||||
"""Score for one article block. Second element True when a fallback was used."""
|
||||
match = _SCORE_RE.search(text)
|
||||
if match:
|
||||
try:
|
||||
return _clamp_score(int(match.group(1))), False
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
match = _IMPORTANCE_RE.search(text)
|
||||
if match:
|
||||
return IMPORTANCE_SCORE.get(match.group(1).lower(), NEUTRAL_SCORE), True
|
||||
return NEUTRAL_SCORE, True
|
||||
|
||||
|
||||
def _category_from_block(text: str) -> str | None:
|
||||
match = _CATEGORY_RE.search(text)
|
||||
if not match:
|
||||
return None
|
||||
value = match.group(1).strip().strip("*_` ").rstrip(".").strip()
|
||||
return value[:40] or None
|
||||
|
||||
|
||||
def parse_map_scores(
|
||||
raw: str, *, articles: list[dict], batch_index: int = 0, batch_size: int = 1
|
||||
) -> tuple[list[dict], dict]:
|
||||
"""Split one map response into scored per-article blocks.
|
||||
|
||||
Pure: no DB, no logging. Block ``n`` of batch ``b`` is attributed to
|
||||
``articles[b * batch_size + n - 1]``. Blocks whose ``Article <n>`` number does
|
||||
not land inside this batch (model omitted/reordered articles) are counted in
|
||||
``stats["unattributed"]`` and dropped — there is no article row to attribute
|
||||
them to. Never raises.
|
||||
|
||||
Returns ``(blocks, stats)`` where each block is::
|
||||
|
||||
{"n", "article", "article_id", "score", "importance", "category",
|
||||
"location_name", "lat", "lon", "location_confidence",
|
||||
"text", "position"}
|
||||
|
||||
Geo is best-effort: ``location_name`` is the model's place name
|
||||
(Unknown -> None), ``lat``/``lon`` are clamp_coords-validated model
|
||||
coordinates (None when absent/invalid — the caller may resolve them
|
||||
via the offline gazetteer), ``location_confidence`` is the block's
|
||||
label or "city" when coords came without one.
|
||||
"""
|
||||
text = raw or ""
|
||||
matches = list(_ARTICLE_RE.finditer(text))
|
||||
blocks: list[dict] = []
|
||||
seen: set[int] = set()
|
||||
fallback = 0
|
||||
unattributed = 0
|
||||
size = max(1, int(batch_size))
|
||||
for pos, match in enumerate(matches):
|
||||
try:
|
||||
n = int(match.group(1))
|
||||
except (TypeError, ValueError):
|
||||
unattributed += 1
|
||||
continue
|
||||
if n in seen:
|
||||
unattributed += 1
|
||||
continue
|
||||
seen.add(n)
|
||||
end = matches[pos + 1].start() if pos + 1 < len(matches) else len(text)
|
||||
block_text = text[match.start():end].strip()
|
||||
offset = int(batch_index) * size + n - 1
|
||||
article = articles[offset] if 0 <= offset < len(articles) else None
|
||||
if article is None or not block_text:
|
||||
unattributed += 1
|
||||
continue
|
||||
score, used_fallback = _score_from_block(block_text)
|
||||
fallback += 1 if used_fallback else 0
|
||||
importance = None
|
||||
imp_match = _IMPORTANCE_RE.search(block_text)
|
||||
if imp_match:
|
||||
importance = imp_match.group(1).lower()
|
||||
blocks.append(
|
||||
{
|
||||
"n": n,
|
||||
"article": article,
|
||||
"article_id": article.get("id"),
|
||||
"title": article.get("title"),
|
||||
"score": score,
|
||||
"importance": importance,
|
||||
"category": _category_from_block(block_text),
|
||||
**_geo_from_block(block_text),
|
||||
"text": block_text,
|
||||
"position": offset,
|
||||
}
|
||||
)
|
||||
stats = {
|
||||
"blocks": len(matches),
|
||||
"graded": len(blocks),
|
||||
"fallback": fallback,
|
||||
"unattributed": unattributed,
|
||||
}
|
||||
return blocks, stats
|
||||
|
||||
|
||||
def select_graded(
|
||||
blocks: list[dict],
|
||||
*,
|
||||
min_score: int,
|
||||
top_n: int,
|
||||
fallback_top: int,
|
||||
fallback_min_score: int = 0,
|
||||
) -> tuple[list[dict], bool]:
|
||||
"""Rank blocks best-first and return the ones the reduce phase should see.
|
||||
|
||||
Keeps ``score >= min_score`` capped at ``top_n`` (stable on ties: original
|
||||
order). When nothing clears the bar, returns up to ``fallback_top`` blocks
|
||||
that also clear ``fallback_min_score`` and True; ``fallback_top == 0``, a
|
||||
floor that excludes every block, or no blocks at all yield an empty
|
||||
selection and False.
|
||||
"""
|
||||
ordered = sorted(blocks, key=lambda b: -int(b.get("score") or 0))
|
||||
limit = max(0, int(top_n))
|
||||
clearing = [b for b in ordered if int(b.get("score") or 0) >= int(min_score)]
|
||||
if clearing:
|
||||
return clearing[:limit], False
|
||||
fallback_limit = max(0, int(fallback_top))
|
||||
if fallback_limit <= 0:
|
||||
return [], False
|
||||
floor = int(fallback_min_score)
|
||||
floor_clearing = [b for b in ordered if int(b.get("score") or 0) >= floor]
|
||||
if not floor_clearing:
|
||||
return [], False
|
||||
return floor_clearing[:fallback_limit], True
|
||||
|
||||
|
||||
def join_blocks(blocks: list[dict]) -> str:
|
||||
"""Reduce-phase DATA text: only these blocks, original text, best-first."""
|
||||
return "\n\n".join(b["text"] for b in blocks)
|
||||
|
||||
|
||||
# ── Syndication dedupe (pure string work — no LLM, no DB) ──────────────────
|
||||
|
||||
DEFAULT_DEDUPE_SIMILARITY = 0.85
|
||||
|
||||
# Wire copy carries the station at the end of the headline: " - KCCI", " | CNN".
|
||||
_SOURCE_SEPARATORS = (" - ", " | ", " — ", " – ")
|
||||
_MAX_SUFFIX_CHARS = 40
|
||||
_MAX_SUFFIX_WORDS = 4
|
||||
_NON_ALNUM_RE = re.compile(r"[^a-z0-9]+")
|
||||
_DIGIT_RE = re.compile(r"\d")
|
||||
|
||||
|
||||
def normalize_title(title) -> str:
|
||||
"""Comparable headline form: lowercase, source suffix stripped, words only.
|
||||
|
||||
A trailing `` - KCCI`` / `` | CNN`` / `` — AP`` marker is removed when the
|
||||
tail is short (<= 40 chars and <= 4 words) **and carries no digits**, so
|
||||
``Story - KCCI`` and ``Story | WTAE`` land on the same key while serial
|
||||
titles (``… – Part 1`` / ``… – Part 2``, ``… — Day 5``) stay distinct.
|
||||
Titles that are None, empty or non-string normalise to ``""`` and never
|
||||
match anything.
|
||||
"""
|
||||
if title is None:
|
||||
return ""
|
||||
if not isinstance(title, str):
|
||||
title = str(title)
|
||||
text = title.strip().lower()
|
||||
cut = -1
|
||||
for separator in _SOURCE_SEPARATORS:
|
||||
idx = text.rfind(separator)
|
||||
if idx <= 0:
|
||||
continue
|
||||
tail = text[idx + len(separator):].strip()
|
||||
if (
|
||||
len(tail) <= _MAX_SUFFIX_CHARS
|
||||
and 0 < len(tail.split()) <= _MAX_SUFFIX_WORDS
|
||||
and not _DIGIT_RE.search(tail)
|
||||
):
|
||||
cut = max(cut, idx)
|
||||
if cut > 0:
|
||||
text = text[:cut]
|
||||
return " ".join(_NON_ALNUM_RE.sub(" ", text).split())
|
||||
|
||||
|
||||
# Headline must clear this to take an article URL. Above the
|
||||
# "storm hits Texas" vs "storm hits Tennessee" band (~0.67) so a near-miss
|
||||
# cannot steal another story's URL. A tie stores "" — a wrong URL is worse
|
||||
# than a blank one.
|
||||
ARTICLE_URL_MIN_SIMILARITY = 0.85
|
||||
# Word-sequence containment only counts when the shorter side is specific.
|
||||
_URL_CONTAIN_MIN_WORDS = 4
|
||||
|
||||
|
||||
def _contains_word_sequence(outer: str, inner: str) -> bool:
|
||||
outer_words = outer.split()
|
||||
inner_words = inner.split()
|
||||
if len(inner_words) < _URL_CONTAIN_MIN_WORDS or len(inner_words) > len(outer_words):
|
||||
return False
|
||||
width = len(inner_words)
|
||||
return any(
|
||||
outer_words[i : i + width] == inner_words
|
||||
for i in range(len(outer_words) - width + 1)
|
||||
)
|
||||
|
||||
|
||||
def article_url_for_row(row: dict, articles: list | None) -> str:
|
||||
"""URL of the selected article this ticker/map row refers to, else ``""``.
|
||||
|
||||
Matches the row headline to an article title. Never reads the model's
|
||||
``url`` field. A null, missing, or non-string article url stores ``""``.
|
||||
Two articles that score the same (or no article that clears the bar)
|
||||
store ``""`` so a headline cannot be wired to the wrong story.
|
||||
"""
|
||||
if not isinstance(row, dict):
|
||||
return ""
|
||||
headline = normalize_title(row.get("headline"))
|
||||
if not headline:
|
||||
return ""
|
||||
best_score = 0.0
|
||||
best: list[dict] = []
|
||||
for article in articles or []:
|
||||
if not isinstance(article, dict):
|
||||
continue
|
||||
title = normalize_title(article.get("title"))
|
||||
if not title:
|
||||
continue
|
||||
if headline == title:
|
||||
score = 1.0
|
||||
elif _contains_word_sequence(headline, title) or _contains_word_sequence(title, headline):
|
||||
score = 0.95
|
||||
else:
|
||||
score = title_similarity(headline, title)
|
||||
if score + 1e-9 < ARTICLE_URL_MIN_SIMILARITY:
|
||||
continue
|
||||
if score > best_score + 1e-9:
|
||||
best_score = score
|
||||
best = [article]
|
||||
elif abs(score - best_score) <= 1e-9:
|
||||
best.append(article)
|
||||
if len(best) != 1:
|
||||
return ""
|
||||
url = best[0].get("url")
|
||||
if not isinstance(url, str):
|
||||
return ""
|
||||
return url.strip()
|
||||
|
||||
|
||||
def title_similarity(normalised_left: str, normalised_right: str) -> float:
|
||||
"""0..1 story-similarity of two already-normalised titles.
|
||||
|
||||
Max of word-set Jaccard (word order and repetition do not matter) and the
|
||||
``difflib`` ratio over the *word sequence* (so near-verbatim rewrites
|
||||
score high, while short headlines differing only in a name — "story 1" vs
|
||||
"story 2", "storm hits Texas" vs "storm hits Tennessee" — stay low).
|
||||
"""
|
||||
if not normalised_left or not normalised_right:
|
||||
return 0.0
|
||||
if normalised_left == normalised_right:
|
||||
return 1.0
|
||||
words_left = normalised_left.split()
|
||||
words_right = normalised_right.split()
|
||||
set_left, set_right = set(words_left), set(words_right)
|
||||
union = set_left | set_right
|
||||
jaccard = len(set_left & set_right) / len(union) if union else 0.0
|
||||
ratio = difflib.SequenceMatcher(None, words_left, words_right).ratio()
|
||||
return max(jaccard, ratio)
|
||||
|
||||
|
||||
def _block_title(block: dict):
|
||||
"""Title of a graded block: the parsed key, else the nested article row."""
|
||||
title = block.get("title")
|
||||
if title is None:
|
||||
article = block.get("article")
|
||||
if isinstance(article, dict):
|
||||
title = article.get("title")
|
||||
return title
|
||||
|
||||
|
||||
def _block_score(block: dict) -> int:
|
||||
try:
|
||||
return int(block.get("score") or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _block_position(block: dict, fallback: int) -> int:
|
||||
position = block.get("position")
|
||||
return position if isinstance(position, int) else fallback
|
||||
|
||||
|
||||
def _categories_conflict(left: dict, right: dict) -> bool:
|
||||
"""True when both blocks carry a category and the two differ."""
|
||||
cat_left = str(left.get("category") or "").strip().lower()
|
||||
cat_right = str(right.get("category") or "").strip().lower()
|
||||
return bool(cat_left) and bool(cat_right) and cat_left != cat_right
|
||||
|
||||
|
||||
def _numbers_conflict(left: str, right: str) -> bool:
|
||||
"""True when the two titles disagree on any number.
|
||||
|
||||
Syndicated wire copy is verbatim, so a differing figure ("… – Part 1" vs
|
||||
"… – Part 2", "12 dead" vs "21 dead", horoscope date boilerplate) means a
|
||||
different story — never collapse it on string similarity alone.
|
||||
"""
|
||||
digits_left = {word for word in left.split() if _DIGIT_RE.search(word)}
|
||||
digits_right = {word for word in right.split() if _DIGIT_RE.search(word)}
|
||||
return digits_left != digits_right
|
||||
|
||||
|
||||
def dedupe_blocks(
|
||||
blocks: list[dict],
|
||||
*,
|
||||
similarity: float = DEFAULT_DEDUPE_SIMILARITY,
|
||||
enabled: bool = True,
|
||||
) -> tuple[list[dict], dict]:
|
||||
"""Collapse syndicated copies of one story into a single representative block.
|
||||
|
||||
Blocks are visited best-score-first (ties -> earliest position), so each
|
||||
cluster's representative is its highest-scoring block and a dropped block
|
||||
never survives. Matching is against the representative only (star
|
||||
clustering, no transitive chaining); two titles match when their normalised
|
||||
forms are equal or ``title_similarity`` clears ``similarity``. Blocks whose
|
||||
categories are both set and different are never merged, and neither are
|
||||
titles that disagree on any number (wire copy is verbatim; a different
|
||||
figure is a different story). Blocks without a usable title stay unique.
|
||||
Never raises: empty/None input and malformed blocks are tolerated.
|
||||
|
||||
Returns ``(kept_blocks, stats)``; kept blocks keep their original order.
|
||||
``stats["duplicate_blocks"]`` holds one record per dropped block::
|
||||
|
||||
{"index", "article_id", "position", "score", "title",
|
||||
"duplicate_of", "duplicate_of_position", "similarity", "block"}
|
||||
"""
|
||||
items = [block for block in (blocks or []) if isinstance(block, dict)]
|
||||
try:
|
||||
threshold = float(similarity)
|
||||
except (TypeError, ValueError):
|
||||
threshold = DEFAULT_DEDUPE_SIMILARITY
|
||||
threshold = min(1.0, max(0.0, threshold))
|
||||
stats = {
|
||||
"input": len(items),
|
||||
"kept": len(items),
|
||||
"duplicates": 0,
|
||||
"threshold": threshold,
|
||||
"duplicate_blocks": [],
|
||||
}
|
||||
if not enabled or len(items) < 2:
|
||||
return list(items), stats
|
||||
|
||||
ranked = sorted(
|
||||
range(len(items)),
|
||||
key=lambda i: (-_block_score(items[i]), _block_position(items[i], i), i),
|
||||
)
|
||||
# groups: representative index -> normalised representative title
|
||||
groups: list[dict] = []
|
||||
for index in ranked:
|
||||
block = items[index]
|
||||
norm = normalize_title(_block_title(block))
|
||||
match: tuple[dict, float] | None = None
|
||||
if norm:
|
||||
for group in groups:
|
||||
rep_norm = group["norm"]
|
||||
if (
|
||||
not rep_norm
|
||||
or _categories_conflict(block, items[group["index"]])
|
||||
or _numbers_conflict(norm, rep_norm)
|
||||
):
|
||||
continue
|
||||
score = 1.0 if norm == rep_norm else title_similarity(norm, rep_norm)
|
||||
if score >= threshold:
|
||||
match = (group, score)
|
||||
break
|
||||
if match is None:
|
||||
groups.append({"index": index, "norm": norm})
|
||||
continue
|
||||
group, score = match
|
||||
rep = items[group["index"]]
|
||||
stats["duplicate_blocks"].append(
|
||||
{
|
||||
"index": index,
|
||||
"article_id": block.get("article_id"),
|
||||
"position": _block_position(block, index),
|
||||
"score": _block_score(block),
|
||||
"title": _block_title(block),
|
||||
"duplicate_of": rep.get("article_id"),
|
||||
"duplicate_of_position": _block_position(rep, group["index"]),
|
||||
"similarity": round(score, 4),
|
||||
"block": block,
|
||||
}
|
||||
)
|
||||
|
||||
dropped = {record["index"] for record in stats["duplicate_blocks"]}
|
||||
kept = [block for index, block in enumerate(items) if index not in dropped]
|
||||
stats["kept"] = len(kept)
|
||||
stats["duplicates"] = len(stats["duplicate_blocks"])
|
||||
return kept, stats
|
||||
|
|
|
|||
|
|
@ -8,10 +8,6 @@ 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:
|
||||
|
|
@ -21,37 +17,20 @@ def chat(prompt, *, api_key, model, base_url, json_mode=False) -> str:
|
|||
"Authorization": f"Bearer {api_key}",
|
||||
"User-Agent": os.environ.get("OSINT_USER_AGENT") or _DEFAULT_UA,
|
||||
}
|
||||
max_tokens = 8192 if json_mode else 4096
|
||||
timeout = 120.0 if json_mode else 60.0
|
||||
messages = [{"role": "user", "content": prompt}]
|
||||
if json_mode:
|
||||
messages = [
|
||||
{"role": "system", "content": _JSON_SYSTEM},
|
||||
{"role": "user", "content": prompt},
|
||||
]
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"temperature": 0.2,
|
||||
"max_tokens": max_tokens,
|
||||
"max_tokens": 4096,
|
||||
}
|
||||
if json_mode:
|
||||
payload["response_format"] = {"type": "json_object"}
|
||||
last_content = ""
|
||||
try:
|
||||
for attempt in range(2):
|
||||
with httpx.Client(timeout=timeout) as client:
|
||||
with httpx.Client(timeout=60.0) as client:
|
||||
resp = client.post(url, headers=headers, json=payload)
|
||||
if resp.status_code == 401 or resp.status_code >= 500:
|
||||
return ""
|
||||
data = resp.json()
|
||||
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
|
||||
return data["choices"][0]["message"]["content"]
|
||||
except Exception:
|
||||
return ""
|
||||
|
|
|
|||
|
|
@ -1,97 +1,37 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Scheduler loop for the news summarizer.
|
||||
"""Scheduler loop for the news summarizer — every NEWS_SUMMARIZE_INTERVAL_S.
|
||||
|
||||
15-minute analyst (NEWS_SUMMARIZE_INTERVAL_S, default 900s) plus a daily
|
||||
recap at 23:00 in TZ (default America/New_York) over the last 24 hours.
|
||||
|
||||
Serial: a slow LLM pass never overlaps the next.
|
||||
Default 900s (15 minutes). Serial: a slow LLM pass never overlaps the next.
|
||||
|
||||
Env (all optional, 12-factor):
|
||||
NEWS_SUMMARIZE_INTERVAL_S seconds between analyst runs (default 900)
|
||||
NEWS_SUMMARIZE_INTERVAL_S seconds between runs (default 900)
|
||||
NEWS_SUMMARIZE_RUN_ON_START "1" to summarize once immediately on boot (default 1)
|
||||
NEWS_RECAP_HOUR / MINUTE wall-clock recap time (default 23:00)
|
||||
TZ IANA tz (default America/New_York)
|
||||
NOUS_API_KEY optional in env; Keys UI / api_keys also works
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
logger = logging.getLogger("news.summarizer.scheduler")
|
||||
|
||||
INTERVAL_S = max(1, int(os.getenv("NEWS_SUMMARIZE_INTERVAL_S", "900")))
|
||||
RUN_ON_START = os.getenv("NEWS_SUMMARIZE_RUN_ON_START", "1").lower() in ("1", "true", "yes")
|
||||
DEFAULT_TZ = "America/New_York"
|
||||
DEFAULT_RECAP_HOUR = 23
|
||||
DEFAULT_RECAP_MINUTE = 0
|
||||
|
||||
|
||||
def _tz() -> ZoneInfo:
|
||||
name = (os.getenv("TZ") or DEFAULT_TZ).strip() or DEFAULT_TZ
|
||||
return ZoneInfo(name)
|
||||
|
||||
|
||||
def recap_hour_minute() -> tuple[int, int]:
|
||||
hour = int(os.getenv("NEWS_RECAP_HOUR", str(DEFAULT_RECAP_HOUR)))
|
||||
minute = int(os.getenv("NEWS_RECAP_MINUTE", str(DEFAULT_RECAP_MINUTE)))
|
||||
return hour, minute
|
||||
|
||||
|
||||
def next_recap_datetime(
|
||||
now: datetime, hour: int | None = None, minute: int | None = None
|
||||
) -> datetime:
|
||||
"""Next 23:00 (or hour/minute) strictly after *now* in now's timezone."""
|
||||
if now.tzinfo is None:
|
||||
now = now.replace(tzinfo=_tz())
|
||||
env_h, env_m = recap_hour_minute()
|
||||
hour = env_h if hour is None else hour
|
||||
minute = env_m if minute is None else minute
|
||||
candidate = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
||||
if now >= candidate:
|
||||
candidate += timedelta(days=1)
|
||||
return candidate
|
||||
|
||||
|
||||
def next_event(
|
||||
now: datetime,
|
||||
last_periodic: datetime | None,
|
||||
interval_s: int,
|
||||
hour: int = DEFAULT_RECAP_HOUR,
|
||||
minute: int = DEFAULT_RECAP_MINUTE,
|
||||
) -> tuple[datetime, str]:
|
||||
"""Return (when, 'recap'|'interval') for the sooner of recap vs interval."""
|
||||
recap_at = next_recap_datetime(now, hour=hour, minute=minute)
|
||||
periodic_at = now if last_periodic is None else last_periodic + timedelta(seconds=interval_s)
|
||||
if recap_at <= periodic_at:
|
||||
return recap_at, "recap"
|
||||
return periodic_at, "interval"
|
||||
|
||||
|
||||
def run_summarize(*, recap: bool = False) -> None:
|
||||
kind = "recap" if recap else "interval"
|
||||
logger.info(
|
||||
"%s starting at %s", kind, datetime.now().isoformat(timespec="seconds")
|
||||
)
|
||||
env = os.environ.copy()
|
||||
if recap:
|
||||
env["NEWS_RECAP"] = "1"
|
||||
else:
|
||||
env.pop("NEWS_RECAP", None)
|
||||
def run_summarize() -> None:
|
||||
logger.info("summarize starting at %s", datetime.datetime.now().isoformat(timespec="seconds"))
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[sys.executable, "summarizer.py"], cwd="/app", env=env
|
||||
)
|
||||
logger.info("%s finished rc=%s", kind, proc.returncode)
|
||||
proc = subprocess.run([sys.executable, "summarizer.py"], cwd="/app")
|
||||
logger.info("summarize finished rc=%s", proc.returncode)
|
||||
except Exception: # noqa: BLE001 — keep the loop alive across failures
|
||||
logger.exception("%s failed", kind)
|
||||
logger.exception("summarize failed")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
|
@ -99,32 +39,16 @@ def main() -> None:
|
|||
logger.warning(
|
||||
"NOUS_API_KEY unset in env — will read api_keys on each run; idle if both empty"
|
||||
)
|
||||
tz = _tz()
|
||||
hour, minute = recap_hour_minute()
|
||||
logger.info(
|
||||
"news summarizer loop starting (interval_s=%s, run_on_start=%s, recap=%02d:%02d %s)",
|
||||
INTERVAL_S, RUN_ON_START, hour, minute, tz,
|
||||
"news summarizer loop starting (interval_s=%s, run_on_start=%s)",
|
||||
INTERVAL_S, RUN_ON_START,
|
||||
)
|
||||
last_periodic: datetime | None = None
|
||||
if RUN_ON_START:
|
||||
run_summarize(recap=False)
|
||||
last_periodic = datetime.now(tz)
|
||||
run_summarize()
|
||||
while True:
|
||||
now = datetime.now(tz)
|
||||
when, kind = next_event(
|
||||
now, last_periodic, INTERVAL_S, hour=hour, minute=minute
|
||||
)
|
||||
sleep_s = max(1, (when - now).total_seconds())
|
||||
logger.info("next %s in %ss", kind, int(sleep_s))
|
||||
time.sleep(sleep_s)
|
||||
now = datetime.now(tz)
|
||||
if kind == "recap":
|
||||
run_summarize(recap=True)
|
||||
# Recap covers the 15-min window; don't immediately fire interval.
|
||||
last_periodic = now
|
||||
else:
|
||||
run_summarize(recap=False)
|
||||
last_periodic = now
|
||||
logger.info("next summarize in %ss", INTERVAL_S)
|
||||
time.sleep(INTERVAL_S)
|
||||
run_summarize()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
|
|
@ -14,18 +14,15 @@ of each summarize_news() — env wins, else api_keys / app_settings:
|
|||
NOUS_API_KEY Nous Portal key (else api_keys.name='NOUS_API_KEY')
|
||||
NOUS_BASE_URL default https://inference-api.nousresearch.com/v1
|
||||
SUMMARY_MODEL default Hermes-4.3-36B (else app_settings)
|
||||
SUMMARY_MIN_SCORE map-score a block needs to reach the reduce brief (60)
|
||||
SUMMARY_TOP_N max distinct blocks passed to reduce (12)
|
||||
SUMMARY_FALLBACK_TOP blocks used when nothing clears MIN_SCORE (3)
|
||||
SUMMARY_FALLBACK_MIN_SCORE score floor for that fallback set (40)
|
||||
SUMMARY_DEDUPE "0" disables syndication dedupe (default on)
|
||||
SUMMARY_DEDUPE_SIMILARITY normalised-title similarity for one story (0.85)
|
||||
BATCH_SIZE articles per map-phase batch (default 50)
|
||||
SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set)
|
||||
NEWS_RECAP "1" for the 23:00 daily recap (24h window, recap prompt)
|
||||
NEWS_SUMMARIZE_FORCE "1" to ignore the interval/recap idempotency skip
|
||||
TZ IANA tz for recap-day bounds (default America/New_York)
|
||||
INCLUDE_FUTURES legacy; ignored — prompts never inject futures data
|
||||
NEWS_SUMMARIZE_FORCE "1" to ignore the interval idempotency skip
|
||||
INCLUDE_FUTURES "1" to prepend live futures prices (default 0)
|
||||
|
||||
The futures/markets coupling from the original pipeline is gated behind
|
||||
INCLUDE_FUTURES and OFF by default — it is irrelevant to the OSINT dashboard
|
||||
and pulled yfinance into the image. Re-enable by installing yfinance and
|
||||
setting INCLUDE_FUTURES=1.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
|
@ -33,24 +30,10 @@ from __future__ import annotations
|
|||
import logging
|
||||
import os
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import psycopg2
|
||||
|
||||
from gazetteer import fill_block_geo
|
||||
from intel import (
|
||||
GEO_CONFIDENCES,
|
||||
article_url_for_row,
|
||||
clamp_coords,
|
||||
clean_location_name,
|
||||
dedupe_blocks,
|
||||
join_blocks,
|
||||
parse_map_scores,
|
||||
parse_reduce_json,
|
||||
select_graded,
|
||||
select_map,
|
||||
select_ticker,
|
||||
)
|
||||
from intel import parse_reduce_json, select_map, select_ticker
|
||||
from nous_client import chat
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
|
|
@ -69,58 +52,6 @@ DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1"
|
|||
DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B"
|
||||
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50"))
|
||||
|
||||
# Map-phase grading knobs (operator sets them in the cluster ConfigMap).
|
||||
DEFAULT_SUMMARY_MIN_SCORE = 60
|
||||
DEFAULT_SUMMARY_TOP_N = 12
|
||||
DEFAULT_SUMMARY_FALLBACK_TOP = 3
|
||||
DEFAULT_SUMMARY_FALLBACK_MIN_SCORE = 40
|
||||
|
||||
# Syndication dedupe (pure string work, runs before the threshold/cap).
|
||||
DEFAULT_SUMMARY_DEDUPE_SIMILARITY = 0.85
|
||||
_FALSY = ("0", "false", "no", "off")
|
||||
|
||||
|
||||
def _env_int(name: str, default: int) -> int:
|
||||
raw = (os.getenv(name) or "").strip()
|
||||
if not raw:
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
logger.warning("Invalid %s=%r — using default %s", name, raw, default)
|
||||
return default
|
||||
|
||||
|
||||
def _env_float(name: str, default: float) -> float:
|
||||
raw = (os.getenv(name) or "").strip()
|
||||
if not raw:
|
||||
return default
|
||||
try:
|
||||
return float(raw)
|
||||
except ValueError:
|
||||
logger.warning("Invalid %s=%r — using default %s", name, raw, default)
|
||||
return default
|
||||
|
||||
|
||||
def dedupe_config() -> tuple[bool, float]:
|
||||
"""(enabled, similarity) from env. SUMMARY_DEDUPE=0 skips dedupe entirely."""
|
||||
enabled = (os.getenv("SUMMARY_DEDUPE") or "1").strip().lower() not in _FALSY
|
||||
similarity = _env_float(
|
||||
"SUMMARY_DEDUPE_SIMILARITY", DEFAULT_SUMMARY_DEDUPE_SIMILARITY
|
||||
)
|
||||
return enabled, min(1.0, max(0.0, similarity))
|
||||
|
||||
|
||||
def selection_config() -> tuple[int, int, int, int]:
|
||||
"""(min_score, top_n, fallback_top, fallback_min_score) from env, per run."""
|
||||
min_score = max(0, min(100, _env_int("SUMMARY_MIN_SCORE", DEFAULT_SUMMARY_MIN_SCORE)))
|
||||
top_n = max(0, _env_int("SUMMARY_TOP_N", DEFAULT_SUMMARY_TOP_N))
|
||||
fallback_top = max(0, _env_int("SUMMARY_FALLBACK_TOP", DEFAULT_SUMMARY_FALLBACK_TOP))
|
||||
fallback_min_score = max(
|
||||
0, min(100, _env_int("SUMMARY_FALLBACK_MIN_SCORE", DEFAULT_SUMMARY_FALLBACK_MIN_SCORE))
|
||||
)
|
||||
return min_score, top_n, fallback_top, fallback_min_score
|
||||
|
||||
|
||||
def _summary_window_minutes() -> int:
|
||||
hours = (os.getenv("SUMMARY_WINDOW_HOURS") or "").strip()
|
||||
|
|
@ -136,18 +67,6 @@ 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")
|
||||
|
||||
|
|
@ -165,41 +84,28 @@ FUTURES_TICKERS = {
|
|||
MAP_PROMPT_DEFAULT = """\
|
||||
You are a precise, factual OSINT news processor. Your ONLY source of information is the articles provided below. Do NOT add external knowledge, assumptions, training data, or invented facts.
|
||||
|
||||
Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. Extract every article; the Score below decides what reaches the operator brief.
|
||||
|
||||
Write every field in English. Translate if the article is not English.
|
||||
|
||||
Grade every article with this rubric before writing anything else in its block:
|
||||
|
||||
- 90–100 — breaking geopolitical/military/security event or major disaster, immediate consequence
|
||||
- 70–89 — significant national/international politics, conflict, security, infrastructure or disaster news
|
||||
- 40–69 — notable regional/economic/tech/health story with real consequences
|
||||
- 10–39 — routine, minor or single-incident crime; local interest
|
||||
- 0–9 — noise: sport, celebrity, entertainment, market/commodity tape, promotional or event-calendar/schedule listings
|
||||
|
||||
For EACH article in the batch:
|
||||
1. Score: the integer 0-100 from the rubric above, first line of the block.
|
||||
2. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
||||
3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit. Confidence: how precise that location is — exact (a specific site/address), city, region, or country. Never invent a place.
|
||||
4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
||||
5. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
||||
6. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
|
||||
7. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none. Keep it consistent with the Score.
|
||||
1. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
||||
2. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit.
|
||||
3. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
||||
4. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
||||
5. OSINT signal: if the article describes an event with geopolitical, security, military, economic, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
|
||||
6. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none.
|
||||
|
||||
If several articles cover the same story, add one short batch-level note at the end: "Batch theme: [one sentence]".
|
||||
|
||||
Output format — strictly one block per article, Score and Importance first:
|
||||
Output format — strictly one block per article:
|
||||
|
||||
Article 1:
|
||||
- Score: <0-100>
|
||||
- Importance: critical|high|medium|low|none
|
||||
- Fact bullet 1
|
||||
- Fact bullet 2
|
||||
- Location: ...
|
||||
- Confidence: exact|city|region|country
|
||||
- Entities: ...
|
||||
- Category: ...
|
||||
- OSINT signal: ...
|
||||
- Importance: ...
|
||||
- Lat: ...
|
||||
- Lon: ...
|
||||
|
||||
|
|
@ -211,56 +117,21 @@ Articles in this batch:
|
|||
"""
|
||||
|
||||
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, set summary_en to exactly: "No qualifying impactful or unusual events in the recent hourly news data." and use empty ticker and map_items arrays. AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING.
|
||||
|
||||
Always write a real summary_en that recaps the most important stories present in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
|
||||
|
||||
DATA is pre-filtered by score and ordered best-first. Lead with the highest-scoring breaking stories and rank them honestly by importance — never promote an item above its score. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short.
|
||||
|
||||
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.
|
||||
All text in English.
|
||||
|
||||
Demand a single JSON object (no markdown fences) with this exact shape:
|
||||
|
||||
{
|
||||
"summary_en": "English markdown brief of the provided stories",
|
||||
"summary_en": "English markdown brief or the no-qualifying-events sentence",
|
||||
"ticker": [{"headline": "", "importance": "critical", "url": "", "location_name": ""}],
|
||||
"map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}]
|
||||
}
|
||||
|
||||
ticker: 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.
|
||||
ticker: only critical and high, max 12, ≤140 chars, no markdown.
|
||||
map_items: only critical and high where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20.
|
||||
summary_en: English markdown brief for an operator HUD.
|
||||
|
||||
DATA:
|
||||
{final_input}
|
||||
|
|
@ -392,7 +263,6 @@ def ensure_tables() -> None:
|
|||
batch_timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
ALTER TABLE article_summaries ADD COLUMN IF NOT EXISTS model TEXT;
|
||||
ALTER TABLE article_summaries ADD COLUMN IF NOT EXISTS kind TEXT;
|
||||
CREATE TABLE IF NOT EXISTS news_items (
|
||||
id SERIAL PRIMARY KEY,
|
||||
summary_id INTEGER REFERENCES article_summaries(id) ON DELETE CASCADE,
|
||||
|
|
@ -412,27 +282,6 @@ def ensure_tables() -> None:
|
|||
CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox
|
||||
ON news_items (lon, lat)
|
||||
WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL;
|
||||
CREATE TABLE IF NOT EXISTS article_scores (
|
||||
article_id INTEGER NOT NULL,
|
||||
summary_id INTEGER,
|
||||
score INTEGER NOT NULL,
|
||||
category TEXT,
|
||||
selected BOOLEAN NOT NULL,
|
||||
model TEXT,
|
||||
duplicate_of INTEGER,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (article_id, created_at)
|
||||
);
|
||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER;
|
||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_name TEXT;
|
||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lat DOUBLE PRECISION;
|
||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lon DOUBLE PRECISION;
|
||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_confidence TEXT;
|
||||
CREATE INDEX IF NOT EXISTS ix_article_scores_summary
|
||||
ON article_scores (summary_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_article_scores_geo_bbox
|
||||
ON article_scores (lon, lat)
|
||||
WHERE lat IS NOT NULL AND lon IS NOT NULL;
|
||||
"""
|
||||
try:
|
||||
conn = psycopg2.connect(**DB_CONFIG)
|
||||
|
|
@ -445,31 +294,24 @@ def ensure_tables() -> None:
|
|||
logger.error("Error ensuring news tables: %s", exc)
|
||||
|
||||
|
||||
def get_recent_news(window_minutes: int | None = None) -> list[dict]:
|
||||
"""Fetch articles from the look-back window ``(now - window, now]``.
|
||||
|
||||
The upper bound is deliberate: future-dated rows (event listings, bad
|
||||
scrape timestamps) must not be re-graded every interval. Rows with a NULL
|
||||
timestamp have never matched the lower bound and still do not.
|
||||
"""
|
||||
mins = window_minutes if window_minutes is not None else effective_window_minutes()
|
||||
def get_recent_news() -> list[dict]:
|
||||
"""Fetch articles from the last SUMMARY_WINDOW_MINUTES (content > 100 chars)."""
|
||||
query = """
|
||||
SELECT id, title, content, url, domain
|
||||
SELECT title, content, url, domain
|
||||
FROM articles
|
||||
WHERE timestamp > NOW() - make_interval(mins => %s)
|
||||
AND timestamp <= NOW()
|
||||
AND content IS NOT NULL AND length(content) > 100
|
||||
ORDER BY timestamp DESC;
|
||||
"""
|
||||
try:
|
||||
conn = psycopg2.connect(**DB_CONFIG)
|
||||
cur = conn.cursor()
|
||||
cur.execute(query, (mins,))
|
||||
cur.execute(query, (SUMMARY_WINDOW_MINUTES,))
|
||||
rows = cur.fetchall()
|
||||
cur.close()
|
||||
conn.close()
|
||||
return [
|
||||
{"id": r[0], "title": r[1], "content": r[2], "url": r[3], "domain": r[4]}
|
||||
{"title": r[0], "content": r[1], "url": r[2], "domain": r[3]}
|
||||
for r in rows
|
||||
]
|
||||
except Exception as exc: # noqa: BLE001
|
||||
|
|
@ -498,51 +340,14 @@ def _already_summarized_this_interval() -> bool:
|
|||
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 ``""``.
|
||||
"""
|
||||
def save_batch(summary_en: str, model: str, ticker: list, map_items: list) -> None:
|
||||
"""Insert the master brief plus flagged ticker/map rows."""
|
||||
ticker_rows = select_ticker(ticker or [])
|
||||
map_rows = select_map(map_items or [])
|
||||
text = (summary_en or "").strip()
|
||||
if len(text) < 10 and not ticker_rows and not map_rows:
|
||||
logger.info("Summary too short or empty. Skipping save.")
|
||||
return None
|
||||
return
|
||||
insert_item = """
|
||||
INSERT INTO news_items (
|
||||
summary_id, kind, headline, importance, location_name,
|
||||
|
|
@ -553,8 +358,8 @@ def save_batch(
|
|||
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),
|
||||
"INSERT INTO article_summaries (summary_text, model) VALUES (%s, %s) RETURNING id",
|
||||
(text, model),
|
||||
)
|
||||
summary_id = cur.fetchone()[0]
|
||||
for row in ticker_rows:
|
||||
|
|
@ -570,7 +375,7 @@ def save_batch(
|
|||
None,
|
||||
None,
|
||||
None,
|
||||
article_url_for_row(row, articles),
|
||||
row.get("url"),
|
||||
),
|
||||
)
|
||||
for row in map_rows:
|
||||
|
|
@ -586,87 +391,18 @@ def save_batch(
|
|||
row.get("lon"),
|
||||
row.get("location_confidence"),
|
||||
row.get("category"),
|
||||
article_url_for_row(row, articles),
|
||||
row.get("url"),
|
||||
),
|
||||
)
|
||||
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),
|
||||
"Master summary saved id=%s model=%s ticker=%d map=%d",
|
||||
summary_id, model, 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
|
||||
try:
|
||||
conn = psycopg2.connect(**DB_CONFIG)
|
||||
cur = conn.cursor()
|
||||
cur.executemany(
|
||||
"INSERT INTO article_scores "
|
||||
"(article_id, summary_id, score, category, selected, model, duplicate_of, "
|
||||
" location_name, lat, lon, location_confidence) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
||||
rows,
|
||||
)
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
logger.info(
|
||||
"article_scores persisted rows=%d selected=%d duplicates=%d geo=%d summary_id=%s",
|
||||
len(rows), sum(1 for r in rows if r[4]),
|
||||
sum(1 for r in rows if r[6] is not None),
|
||||
sum(1 for r in rows if r[8] is not None), summary_id,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("Error persisting article_scores (run continues): %s", exc)
|
||||
|
||||
|
||||
# ── Orchestration ──────────────────────────────────────────────────────────
|
||||
|
|
@ -677,35 +413,26 @@ def build_map_prompt(batch: list[dict]) -> str:
|
|||
for a in batch
|
||||
)
|
||||
template = os.getenv("MAP_PROMPT", MAP_PROMPT_DEFAULT)
|
||||
prefix = build_futures_context() + "\n" if INCLUDE_FUTURES else ""
|
||||
try:
|
||||
return template.format(batch_text=batch_text)
|
||||
return prefix + template.format(batch_text=batch_text)
|
||||
except KeyError:
|
||||
return template
|
||||
return prefix + template
|
||||
|
||||
|
||||
def build_master_prompt(final_input: str, recap: bool = False) -> str:
|
||||
if recap:
|
||||
template = os.getenv("RECAP_PROMPT", RECAP_PROMPT_DEFAULT)
|
||||
else:
|
||||
def build_master_prompt(final_input: str) -> str:
|
||||
template = os.getenv("SUMMARY_PROMPT", SUMMARY_PROMPT_DEFAULT)
|
||||
if "{final_input}" in template:
|
||||
return template.replace("{final_input}", final_input)
|
||||
return template
|
||||
prefix = build_futures_context() + "\n" if INCLUDE_FUTURES else ""
|
||||
try:
|
||||
return prefix + template.format(final_input=final_input)
|
||||
except KeyError:
|
||||
return prefix + template
|
||||
|
||||
|
||||
def summarize_news() -> None:
|
||||
"""Map-reduce summarize recent articles and store brief + ticker + map."""
|
||||
recap = is_recap_run()
|
||||
window = effective_window_minutes(recap=recap)
|
||||
ensure_tables()
|
||||
if recap:
|
||||
if _already_recapped_today():
|
||||
logger.info(
|
||||
"Skipping recap: article_summaries already has daily_recap today "
|
||||
"(set NEWS_SUMMARIZE_FORCE=1 to override)"
|
||||
)
|
||||
return
|
||||
elif _already_summarized_this_interval():
|
||||
if _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)",
|
||||
|
|
@ -720,106 +447,41 @@ def summarize_news() -> None:
|
|||
logger.warning("NOUS_API_KEY unset in env and api_keys — idle this run")
|
||||
return
|
||||
|
||||
articles = get_recent_news(window)
|
||||
articles = get_recent_news()
|
||||
if not articles:
|
||||
logger.info("No new articles found in the last %s min.", window)
|
||||
logger.info("No new articles found in the last %s min.", SUMMARY_WINDOW_MINUTES)
|
||||
return
|
||||
|
||||
min_score, top_n, fallback_top, fallback_min_score = selection_config()
|
||||
logger.info(
|
||||
"Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s, "
|
||||
"min_score=%d, top_n=%d, fallback_top=%d, fallback_min_score=%d)...",
|
||||
len(articles), model, BATCH_SIZE, recap, window,
|
||||
min_score, top_n, fallback_top, fallback_min_score,
|
||||
"Processing %d articles with %s (batch_size=%d, futures=%s)...",
|
||||
len(articles), model, BATCH_SIZE, INCLUDE_FUTURES,
|
||||
)
|
||||
|
||||
graded: list[dict] = []
|
||||
partial_summaries: list[str] = []
|
||||
for i in range(0, len(articles), BATCH_SIZE):
|
||||
batch = articles[i : i + BATCH_SIZE]
|
||||
batch_index = i // BATCH_SIZE
|
||||
logger.info(
|
||||
"map batch %d/%d (%d articles)",
|
||||
batch_index + 1, -(-len(articles) // BATCH_SIZE), len(batch),
|
||||
i // BATCH_SIZE + 1, -(-len(articles) // BATCH_SIZE), len(batch),
|
||||
)
|
||||
response = call_llm(
|
||||
summary = call_llm(
|
||||
build_map_prompt(batch),
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
base_url=base_url,
|
||||
json_mode=False,
|
||||
)
|
||||
if not response:
|
||||
continue
|
||||
blocks, stats = parse_map_scores(
|
||||
response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE
|
||||
)
|
||||
# Best-effort proximate geo: place-name-only blocks get offline
|
||||
# gazetteer coords (confidence "approx"); misses stay coord-less.
|
||||
for block in blocks:
|
||||
fill_block_geo(block)
|
||||
logger.info(
|
||||
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d, geo=%d)",
|
||||
batch_index + 1, stats["graded"], len(batch),
|
||||
stats["fallback"], stats["unattributed"],
|
||||
sum(1 for b in blocks if b.get("lat") is not None),
|
||||
)
|
||||
graded.extend(blocks)
|
||||
if summary:
|
||||
partial_summaries.append(summary)
|
||||
|
||||
if not graded:
|
||||
logger.warning("No article blocks parsed from the map phase — nothing to reduce.")
|
||||
final_input = "\n\n".join(partial_summaries)
|
||||
if not final_input.strip():
|
||||
logger.warning("No partial summaries produced — nothing to reduce.")
|
||||
return
|
||||
|
||||
dedupe_enabled, dedupe_similarity = dedupe_config()
|
||||
distinct, dedupe_stats = dedupe_blocks(
|
||||
graded, similarity=dedupe_similarity, enabled=dedupe_enabled
|
||||
)
|
||||
duplicate_blocks = [record["block"] for record in dedupe_stats["duplicate_blocks"]]
|
||||
for record in dedupe_stats["duplicate_blocks"]:
|
||||
record["block"]["duplicate_of"] = record["duplicate_of"]
|
||||
if dedupe_enabled:
|
||||
logger.info(
|
||||
"dedupe %d -> %d (kept %d, duplicates %d)",
|
||||
dedupe_stats["input"], dedupe_stats["kept"],
|
||||
dedupe_stats["kept"], dedupe_stats["duplicates"],
|
||||
)
|
||||
else:
|
||||
logger.info("dedupe skipped (SUMMARY_DEDUPE=0)")
|
||||
|
||||
selected, used_fallback = select_graded(
|
||||
distinct,
|
||||
min_score=min_score,
|
||||
top_n=top_n,
|
||||
fallback_top=fallback_top,
|
||||
fallback_min_score=fallback_min_score,
|
||||
)
|
||||
selected_positions = {block["position"] for block in selected}
|
||||
for block in distinct:
|
||||
block["selected"] = block["position"] in selected_positions
|
||||
for block in duplicate_blocks:
|
||||
# The representative carries the selection; a wire copy never does.
|
||||
block["selected"] = False
|
||||
if used_fallback:
|
||||
logger.warning(
|
||||
"No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d "
|
||||
"with score >= %d (max score %d)",
|
||||
min_score, len(selected), fallback_min_score,
|
||||
max(b["score"] for b in graded),
|
||||
)
|
||||
logger.info(
|
||||
"selected %d/%d distinct articles for reduce (scores=%s)",
|
||||
len(selected), len(distinct), [b["score"] for b in selected],
|
||||
)
|
||||
|
||||
final_input = join_blocks(selected)
|
||||
if not final_input.strip():
|
||||
logger.warning(
|
||||
"Selection is empty (min_score=%d, fallback_top=%d, "
|
||||
"fallback_min_score=%d) — reduce gets empty DATA.",
|
||||
min_score, fallback_top, fallback_min_score,
|
||||
)
|
||||
|
||||
logger.info("reduce phase over %d partial summaries", len(partial_summaries))
|
||||
master_raw = call_llm(
|
||||
build_master_prompt(final_input, recap=recap),
|
||||
build_master_prompt(final_input),
|
||||
api_key=api_key,
|
||||
model=model,
|
||||
base_url=base_url,
|
||||
|
|
@ -829,20 +491,7 @@ def summarize_news() -> None:
|
|||
logger.warning("Reduce phase returned empty — nothing to persist.")
|
||||
return
|
||||
parsed = parse_reduce_json(master_raw)
|
||||
selected_articles = [
|
||||
block["article"]
|
||||
for block in selected
|
||||
if isinstance(block.get("article"), dict)
|
||||
]
|
||||
summary_id = save_batch(
|
||||
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)
|
||||
save_batch(parsed["summary_en"], model, parsed["ticker"], parsed["map_items"])
|
||||
|
||||
|
||||
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)
|
||||
|
|
@ -32,16 +32,6 @@ def test_select_ticker_keeps_critical_high_caps_12():
|
|||
assert len(out) == 12
|
||||
assert all(r["importance"] in ("critical", "high") for r in out)
|
||||
|
||||
|
||||
def test_select_ticker_falls_back_to_medium_low_when_nothing_flagged():
|
||||
rows = [
|
||||
{"headline": "shop theft", "importance": "low"},
|
||||
{"headline": "highway crash", "importance": "medium"},
|
||||
{"headline": "none", "importance": "none"},
|
||||
]
|
||||
out = select_ticker(rows)
|
||||
assert [r["headline"] for r in out] == ["highway crash", "shop theft"]
|
||||
|
||||
def test_select_map_requires_valid_coords_and_flag():
|
||||
items = [
|
||||
{"headline": "A", "importance": "critical", "lat": 50.45, "lon": 30.52, "location_name": "Kyiv"},
|
||||
|
|
|
|||
|
|
@ -67,33 +67,6 @@ 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):
|
||||
|
|
|
|||
|
|
@ -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,15 +1,11 @@
|
|||
#!/usr/bin/env bash
|
||||
# Recreate selected OSINT compose services WITHOUT bouncing Postgres.
|
||||
# Recreate the OSINT compose stack without container_name collisions.
|
||||
# Named volumes (osint-dashboard_osint-pgdata, camera-snapshots) are kept —
|
||||
# never pass -v to `compose down`.
|
||||
#
|
||||
# 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)
|
||||
# Usage: scripts/compose-reup.sh
|
||||
# Env: COMPOSE_PROJECT_NAME (default osint-dashboard)
|
||||
# COMPOSE_PROFILES (default ingest)
|
||||
# FORCE_RECREATE_DB=1 also recreate db
|
||||
# COMPOSE_PROFILES (default ingest — nats/ingester/news/cameras)
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
|
|
@ -18,57 +14,29 @@ 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
|
||||
NAMES=(
|
||||
osint-dashboard
|
||||
osint-db
|
||||
osint-nats
|
||||
osint-ingester
|
||||
osint-camera-scraper
|
||||
osint-news-scraper
|
||||
osint-news-summarizer
|
||||
)
|
||||
|
||||
echo "compose-reup: project=${COMPOSE_PROJECT_NAME} profile=${PROFILE} dir=${ROOT}"
|
||||
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
|
||||
# Stop compose-owned containers first. Foreign/name-pinned leftovers survive this.
|
||||
docker compose --profile "${PROFILE}" down --remove-orphans || 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}"
|
||||
# Drop any leftover name-pinned containers compose does not own (the
|
||||
# "Conflict. The container name is already in use" failure mode).
|
||||
for c in "${NAMES[@]}"; do
|
||||
if docker inspect "$c" >/dev/null 2>&1; then
|
||||
echo "compose-reup: removing leftover ${c}"
|
||||
docker rm -f "$c" >/dev/null
|
||||
fi
|
||||
done
|
||||
|
||||
docker compose --profile "${PROFILE}" up -d --no-build --no-deps "${SVCS[@]}"
|
||||
docker compose --profile "${PROFILE}" up -d --no-build "$@"
|
||||
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).
|
||||
os.environ.setdefault("DB_NULL_POOL", "1")
|
||||
|
||||
# ── Single-admin auth test configuration ────────────────────────────────────
|
||||
# Admin routes are denied unless a signed session cookie is present, so the
|
||||
# suite needs known credentials + a signing key. Tests that exercise the
|
||||
# "auth not configured" path monkeypatch these away.
|
||||
ADMIN_TEST_USER = "admin"
|
||||
ADMIN_TEST_PASSWORD = "test-admin-password"
|
||||
ADMIN_TEST_SECRET = "test-admin-session-secret-not-for-production"
|
||||
|
||||
from auth import COOKIE_NAME, create_session_token, hash_password, reset_failures # noqa: E402
|
||||
|
||||
os.environ.setdefault("ADMIN_USER", ADMIN_TEST_USER)
|
||||
os.environ.setdefault("ADMIN_PASSWORD_HASH", hash_password(ADMIN_TEST_PASSWORD))
|
||||
os.environ.setdefault("ADMIN_SESSION_SECRET", ADMIN_TEST_SECRET)
|
||||
|
||||
import asyncpg # noqa: E402
|
||||
|
||||
pytestmark = []
|
||||
|
||||
|
||||
def admin_cookies() -> dict[str, str]:
|
||||
"""A valid admin session cookie value for in-process API calls."""
|
||||
return {COOKIE_NAME: create_session_token(os.environ["ADMIN_USER"])}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_login_limiter():
|
||||
"""The login limiter is process-global; never leak failures between tests."""
|
||||
reset_failures()
|
||||
yield
|
||||
reset_failures()
|
||||
|
||||
|
||||
def _db_reachable() -> bool:
|
||||
try:
|
||||
import asyncio
|
||||
|
|
|
|||
|
|
@ -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 main import app
|
||||
|
||||
from conftest import admin_cookies
|
||||
|
||||
BASE = "http://test"
|
||||
|
||||
|
||||
async def _get(path: str) -> httpx.Response:
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||||
client.cookies.update(admin_cookies())
|
||||
return await client.get(path)
|
||||
|
||||
|
||||
async def _post(path: str, payload: dict | None) -> httpx.Response:
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||||
client.cookies.update(admin_cookies())
|
||||
return await client.post(path, json=payload)
|
||||
|
||||
|
||||
|
|
@ -79,35 +75,3 @@ def test_vessels_subscribe_rejects_bad_bbox():
|
|||
assert resp.status_code == 422, bad
|
||||
# Explicit null bbox is the "reset to env default" path (still 200).
|
||||
assert asyncio.run(_post("/api/vessels/subscribe", {"bbox": None})).status_code == 200
|
||||
|
||||
|
||||
def test_aircraft_photo_requires_hex_or_reg():
|
||||
assert asyncio.run(_get("/api/aircraft/photo")).status_code == 422
|
||||
|
||||
|
||||
def test_aircraft_photo_rejects_bad_hex():
|
||||
# hex must be exactly 6 hex chars
|
||||
resp = asyncio.run(_get("/api/aircraft/photo?hex=xyz1234"))
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_aircraft_photo_returns_photo(monkeypatch):
|
||||
async def fake(hex_code=None, reg=None):
|
||||
return {"id": "1", "src": "https://t.plnspttrs.net/a_280.jpg",
|
||||
"link": "https://www.planespotters.net/photo/1/x", "photographer": "A"}
|
||||
|
||||
monkeypatch.setattr("main.fetch_planespotters_photo", fake)
|
||||
resp = asyncio.run(_get("/api/aircraft/photo?hex=e8027e"))
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["src"].startswith("https://t.plnspttrs.net/")
|
||||
assert "max-age" in (resp.headers.get("cache-control") or "").lower()
|
||||
|
||||
|
||||
def test_aircraft_photo_404_when_no_photo(monkeypatch):
|
||||
async def fake(hex_code=None, reg=None):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr("main.fetch_planespotters_photo", fake)
|
||||
resp = asyncio.run(_get("/api/aircraft/photo?reg=D-ABCD"))
|
||||
assert resp.status_code == 404
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ from __future__ import annotations
|
|||
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import asyncpg
|
||||
import httpx
|
||||
|
|
@ -68,14 +68,14 @@ def _seed_article(title: str, url: str, domain: str, ts: str, content: str = "bo
|
|||
asyncio.run(run())
|
||||
|
||||
|
||||
def _seed_summary(text: str, ts: str, model: str | None = None, kind: str | None = None) -> int:
|
||||
def _seed_summary(text: str, ts: str, model: str | None = None) -> int:
|
||||
async def run() -> int:
|
||||
conn = await asyncpg.connect(**_conn_kwargs())
|
||||
try:
|
||||
row = await conn.fetchrow(
|
||||
"INSERT INTO article_summaries (summary_text, batch_timestamp, model, kind) "
|
||||
"VALUES ($1, $2, $3, $4) RETURNING id",
|
||||
text, datetime.fromisoformat(ts), model, kind,
|
||||
"INSERT INTO article_summaries (summary_text, batch_timestamp, model) "
|
||||
"VALUES ($1, $2, $3) RETURNING id",
|
||||
text, datetime.fromisoformat(ts), model,
|
||||
)
|
||||
return int(row["id"])
|
||||
finally:
|
||||
|
|
@ -157,70 +157,6 @@ def test_api_news_since_filter(clean_news):
|
|||
assert body[0]["title"] == "after"
|
||||
|
||||
|
||||
@requires_db
|
||||
def test_api_news_excludes_future_dated_rows(clean_news):
|
||||
"""Future-dated event listings must not pin the top of the feed."""
|
||||
now = datetime.now(timezone.utc)
|
||||
future = now + timedelta(days=5)
|
||||
recent = now - timedelta(hours=1)
|
||||
_seed_article("recent", "https://a.example/recent", "a.example", recent.isoformat())
|
||||
_seed_article("future", "https://a.example/future", "a.example", future.isoformat())
|
||||
|
||||
body = _get("/api/news").json()
|
||||
assert [a["title"] for a in body] == ["recent"]
|
||||
|
||||
# limit still caps the (post-filter) result set
|
||||
_seed_article("recent2", "https://a.example/recent2", "a.example", (now - timedelta(hours=2)).isoformat())
|
||||
_seed_article("recent3", "https://a.example/recent3", "a.example", (now - timedelta(hours=3)).isoformat())
|
||||
limited = _get("/api/news?limit=2").json()
|
||||
assert [a["title"] for a in limited] == ["recent", "recent2"]
|
||||
|
||||
|
||||
@requires_db
|
||||
def test_api_news_unwraps_stored_cdata_title(clean_news):
|
||||
"""Dirty rows are fixed on read. A plain title, and HTML that is not a
|
||||
CDATA wrapper, are returned unchanged. No UPDATE of historical rows.
|
||||
"""
|
||||
stored = "\n <![CDATA[Hello]]> "
|
||||
_seed_article(
|
||||
stored,
|
||||
"https://www.excelsior.com.mx/cdata",
|
||||
"www.excelsior.com.mx",
|
||||
"2026-08-24T18:00:00+00:00",
|
||||
)
|
||||
_seed_article(
|
||||
"Hello",
|
||||
"https://a.example/plain",
|
||||
"a.example",
|
||||
"2026-08-24T17:00:00+00:00",
|
||||
)
|
||||
_seed_article(
|
||||
"<b>Keep</b>",
|
||||
"https://a.example/html",
|
||||
"a.example",
|
||||
"2026-08-24T16:00:00+00:00",
|
||||
)
|
||||
|
||||
body = _get("/api/news").json()
|
||||
by_url = {row["url"]: row["title"] for row in body}
|
||||
assert by_url["https://www.excelsior.com.mx/cdata"] == "Hello"
|
||||
assert by_url["https://a.example/plain"] == "Hello"
|
||||
assert by_url["https://a.example/html"] == "<b>Keep</b>"
|
||||
|
||||
# Read-path only: the stored row stays dirty.
|
||||
async def _stored_title() -> str:
|
||||
conn = await asyncpg.connect(**_conn_kwargs())
|
||||
try:
|
||||
return await conn.fetchval(
|
||||
"SELECT title FROM articles WHERE url = $1",
|
||||
"https://www.excelsior.com.mx/cdata",
|
||||
)
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
assert asyncio.run(_stored_title()) == stored
|
||||
|
||||
|
||||
@requires_db
|
||||
def test_api_news_summaries_contract(clean_news):
|
||||
_seed_summary("master summary markdown…", "2026-08-24T18:05:00+00:00")
|
||||
|
|
@ -228,21 +164,9 @@ def test_api_news_summaries_contract(clean_news):
|
|||
assert isinstance(body, list)
|
||||
assert len(body) == 1
|
||||
s = body[0]
|
||||
assert set(s.keys()) == {"id", "summary_text", "batch_timestamp", "model", "kind"}
|
||||
assert set(s.keys()) == {"id", "summary_text", "batch_timestamp", "model"}
|
||||
assert s["summary_text"] == "master summary markdown…"
|
||||
assert s["batch_timestamp"].startswith("2026-08-24T18:05")
|
||||
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
|
||||
|
|
@ -294,21 +218,6 @@ def test_api_news_ticker_returns_only_flagged(clean_news):
|
|||
assert item["url"] == "https://example.com/ticker"
|
||||
|
||||
|
||||
@requires_db
|
||||
def test_api_news_ticker_falls_back_to_lesser_when_nothing_flagged(clean_news):
|
||||
sid = _seed_summary("quiet brief", "2026-08-27T18:05:00+00:00", "Hermes-4.3-36B")
|
||||
_seed_news_item(
|
||||
sid, "ticker", "Shop theft downtown", "low",
|
||||
location_name="Raleigh", url="https://example.com/theft",
|
||||
)
|
||||
resp = _get("/api/news/ticker")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert len(body) == 1
|
||||
assert body[0]["headline"] == "Shop theft downtown"
|
||||
assert body[0]["importance"] == "low"
|
||||
|
||||
|
||||
@requires_db
|
||||
def test_api_news_map_returns_only_flagged_with_coords(clean_news):
|
||||
_seed_flagged_items()
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
@ -9,7 +9,7 @@ import asyncpg
|
|||
import httpx
|
||||
import pytest
|
||||
|
||||
from conftest import admin_cookies, requires_db
|
||||
from conftest import requires_db
|
||||
|
||||
from main import app
|
||||
|
||||
|
|
@ -51,7 +51,6 @@ def _request(method: str, path: str, json: dict | None = None) -> httpx.Response
|
|||
async def _run() -> httpx.Response:
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||||
client.cookies.update(admin_cookies())
|
||||
return await client.request(method, path, json=json)
|
||||
|
||||
return asyncio.run(_run())
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
@ -7,27 +7,36 @@ import asyncio
|
|||
import bg_jobs
|
||||
|
||||
|
||||
def test_bg_jobs_has_no_pps_cap():
|
||||
assert not any(name.endswith("_PPS_CAP") for name in dir(bg_jobs))
|
||||
def test_schedule_masscan_pass_returns_without_awaiting_scan(monkeypatch):
|
||||
started = {"n": 0}
|
||||
|
||||
async def slow_pass():
|
||||
started["n"] += 1
|
||||
await asyncio.sleep(30)
|
||||
|
||||
monkeypatch.setattr(bg_jobs, "_run_masscan_capped", slow_pass)
|
||||
bg_jobs._masscan_task = None
|
||||
|
||||
async def run():
|
||||
launched = bg_jobs.schedule_masscan_pass()
|
||||
assert launched is True
|
||||
# Must not have blocked for the 30s pass.
|
||||
assert bg_jobs._masscan_task is not None
|
||||
assert not bg_jobs._masscan_task.done()
|
||||
launched2 = bg_jobs.schedule_masscan_pass()
|
||||
assert launched2 is False # already running
|
||||
bg_jobs._masscan_task.cancel()
|
||||
try:
|
||||
await bg_jobs._masscan_task
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
bg_jobs._masscan_task = None
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_camera_preview_has_no_public_feed_probe():
|
||||
import camera_preview
|
||||
|
||||
assert not hasattr(camera_preview, "probe_public_feed")
|
||||
assert not hasattr(camera_preview, "_http_feed_url")
|
||||
|
||||
|
||||
def test_ingest_routes_exclude_active_discovery():
|
||||
from main import app
|
||||
|
||||
ingest = [
|
||||
getattr(r, "path", "")
|
||||
for r in app.routes
|
||||
if getattr(r, "path", "").startswith("/api/ingest/")
|
||||
]
|
||||
assert "/api/ingest/fires" in ingest
|
||||
assert all("scan" not in path for path in ingest)
|
||||
def test_masscan_rate_cap_is_200():
|
||||
assert bg_jobs.MASSCAN_PPS_CAP == 200
|
||||
|
||||
|
||||
def test_schedule_ffmpeg_snapshot_is_a_task_not_inline(monkeypatch):
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
@ -1,152 +0,0 @@
|
|||
"""Layer rail hides Vessels and FIRMS only when /api/stats says the key is unset."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
HTML = (ROOT / "app/static/index.html").read_text()
|
||||
|
||||
|
||||
def _between(start: str, end: str) -> str:
|
||||
return HTML.split(start, 1)[1].split(end, 1)[0]
|
||||
|
||||
|
||||
def _feed_fns() -> str:
|
||||
return _between("function applyFeedConfig", "async function pollLayerStats")
|
||||
|
||||
|
||||
def _layer_chunk(elem_id: str) -> str:
|
||||
idx = HTML.index(f'id="{elem_id}"')
|
||||
start = HTML.rfind('<div class="lp-layer"', 0, idx)
|
||||
assert start != -1, elem_id
|
||||
end = HTML.find('<div class="lp-layer"', idx)
|
||||
if end == -1:
|
||||
end = idx + 400
|
||||
return HTML[start:end]
|
||||
|
||||
|
||||
def test_hide_keyed_on_feeds_configured_not_counts():
|
||||
js = _feed_fns()
|
||||
assert "function applyFeedConfig" not in js # sliced after the name
|
||||
assert "feeds.vessels" in js
|
||||
assert "feeds.fires" in js
|
||||
assert "configured === false" in js
|
||||
assert "lp-vessels-on" in js
|
||||
assert "lp-fires-on" in js
|
||||
for stay in ("lp-incidents-on", "lp-perim-on", "lp-trains-on", "lp-ac-on"):
|
||||
assert stay not in js, stay
|
||||
assert "=== 0" not in js
|
||||
assert ".closest('.lp-layer')" in js
|
||||
assert "row.hidden = hide" in js
|
||||
assert "display = hide ? 'none'" in js
|
||||
poll = _between("async function pollLayerStats", "function hideSwpcChip")
|
||||
assert "applyFeedConfig(s)" in poll
|
||||
assert 'class="lp-layer"' in _layer_chunk("lp-vessels-on")
|
||||
assert 'class="lp-layer"' in _layer_chunk("lp-fires-on")
|
||||
assert "FIRMS Fires" in _layer_chunk("lp-fires-on")
|
||||
assert "Vessels" in _layer_chunk("lp-vessels-on")
|
||||
assert "WFIGS" not in _layer_chunk("lp-fires-on")
|
||||
|
||||
|
||||
def test_payloads_hide_only_unconfigured_vessel_and_firms_rows():
|
||||
"""Run the real functions against stats payloads. Count 0 is not a hide signal."""
|
||||
src = "function applyFeedConfig" + _feed_fns()
|
||||
harness = r"""
|
||||
const fs = require('fs');
|
||||
const src = fs.readFileSync(process.argv[2], 'utf8');
|
||||
const cases = JSON.parse(fs.readFileSync(process.argv[3], 'utf8'));
|
||||
const IDS = ['lp-vessels-on','lp-fires-on','lp-incidents-on','lp-perim-on','lp-trains-on'];
|
||||
function makeDoc() {
|
||||
const byId = {};
|
||||
function node(className, id) {
|
||||
const el = {
|
||||
id: id || '',
|
||||
className,
|
||||
hidden: false,
|
||||
style: { display: '' },
|
||||
parentElement: null,
|
||||
closest(sel) {
|
||||
const want = sel.replace(/^\./, '');
|
||||
let n = this;
|
||||
while (n) {
|
||||
if ((n.className || '').split(/\s+/).includes(want)) return n;
|
||||
n = n.parentElement;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
if (id) byId[id] = el;
|
||||
return el;
|
||||
}
|
||||
for (const id of IDS) {
|
||||
const row = node('lp-layer');
|
||||
const input = node('', id);
|
||||
input.parentElement = row;
|
||||
}
|
||||
global.document = { getElementById(id) { return byId[id] || null; } };
|
||||
}
|
||||
eval(src);
|
||||
const out = {};
|
||||
for (const [name, payload] of Object.entries(cases)) {
|
||||
makeDoc();
|
||||
applyFeedConfig(payload);
|
||||
out[name] = {};
|
||||
for (const id of IDS) {
|
||||
const row = document.getElementById(id).closest('.lp-layer');
|
||||
out[name][id] = { hidden: row.hidden, display: row.style.display };
|
||||
}
|
||||
}
|
||||
process.stdout.write(JSON.stringify(out));
|
||||
"""
|
||||
cases = {
|
||||
"both_false": {
|
||||
"vessels": 0,
|
||||
"fires": 0,
|
||||
"feeds": {"vessels": {"configured": False}, "fires": {"configured": False}},
|
||||
},
|
||||
"both_true": {
|
||||
"vessels": 0,
|
||||
"fires": 0,
|
||||
"feeds": {"vessels": {"configured": True}, "fires": {"configured": True}},
|
||||
},
|
||||
"no_feeds": {"vessels": 0, "fires": 0, "trains": 0},
|
||||
"counts_only_zero": {"vessels": 0, "fires": 0},
|
||||
"vessels_only_unset": {
|
||||
"feeds": {"vessels": {"configured": False}, "fires": {"configured": True}},
|
||||
},
|
||||
}
|
||||
scratch = Path("/home/lancelot/.hermes/profiles/frontend/cache/scratch")
|
||||
scratch.mkdir(parents=True, exist_ok=True)
|
||||
src_path = scratch / "t_617c8a08-feed-fns.js"
|
||||
cases_path = scratch / "t_617c8a08-feed-cases.json"
|
||||
harness_path = scratch / "t_617c8a08-feed-harness.js"
|
||||
src_path.write_text(src)
|
||||
cases_path.write_text(json.dumps(cases))
|
||||
harness_path.write_text(harness)
|
||||
proc = subprocess.run(
|
||||
["node", str(harness_path), str(src_path), str(cases_path)],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
got = json.loads(proc.stdout)
|
||||
hidden = {"hidden": True, "display": "none"}
|
||||
shown = {"hidden": False, "display": ""}
|
||||
stay = ("lp-incidents-on", "lp-perim-on", "lp-trains-on")
|
||||
|
||||
assert got["both_false"]["lp-vessels-on"] == hidden
|
||||
assert got["both_false"]["lp-fires-on"] == hidden
|
||||
for eid in stay:
|
||||
assert got["both_false"][eid] == shown, eid
|
||||
|
||||
for name in ("both_true", "no_feeds", "counts_only_zero"):
|
||||
for eid in ("lp-vessels-on", "lp-fires-on", *stay):
|
||||
assert got[name][eid] == shown, (name, eid)
|
||||
|
||||
assert got["vessels_only_unset"]["lp-vessels-on"] == hidden
|
||||
assert got["vessels_only_unset"]["lp-fires-on"] == shown
|
||||
for eid in stay:
|
||||
assert got["vessels_only_unset"][eid] == shown, eid
|
||||
|
|
@ -213,55 +213,3 @@ def test_ingest_fire_rows_one_execute_one_commit(monkeypatch):
|
|||
assert inserted == 3
|
||||
assert session.executes == 1
|
||||
assert session.commits == 1
|
||||
|
||||
|
||||
def test_fire_insert_chunk_stays_under_asyncpg_bind_limit():
|
||||
"""asyncpg caps bind params at 32767 — a 93k-row INSERT dies."""
|
||||
from ingestor import FIRE_INSERT_CHUNK, FIRE_ROW_BIND_PARAMS
|
||||
|
||||
assert FIRE_INSERT_CHUNK * FIRE_ROW_BIND_PARAMS < 32767
|
||||
assert FIRE_INSERT_CHUNK >= 500
|
||||
|
||||
|
||||
def test_ingest_fire_rows_chunks_when_over_limit(monkeypatch):
|
||||
from ingestor import ingest_fire_rows
|
||||
import ingestor
|
||||
|
||||
class _Session:
|
||||
def __init__(self):
|
||||
self.executes = 0
|
||||
self.commits = 0
|
||||
self.rowcount = 0
|
||||
|
||||
async def execute(self, *a, **k):
|
||||
self.executes += 1
|
||||
self.rowcount = 2 if self.executes < 3 else 1
|
||||
return self
|
||||
|
||||
async def commit(self):
|
||||
self.commits += 1
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
session = _Session()
|
||||
monkeypatch.setattr(ingestor, "async_session", lambda: session)
|
||||
monkeypatch.setattr(ingestor, "FIRE_INSERT_CHUNK", 2)
|
||||
|
||||
async def no_corr(*a, **k):
|
||||
return []
|
||||
|
||||
monkeypatch.setattr("fire_aircraft.correlate_and_notify", no_corr)
|
||||
monkeypatch.setattr("geofence.record_and_notify", no_corr)
|
||||
|
||||
msgs = [
|
||||
make_fire_msg(latitude=39.1 + i * 0.01, longitude=-121.1)
|
||||
for i in range(5)
|
||||
]
|
||||
inserted = asyncio.run(ingest_fire_rows(msgs))
|
||||
assert inserted == 5
|
||||
assert session.executes == 3
|
||||
assert session.commits == 1
|
||||
|
|
|
|||
|
|
@ -131,100 +131,6 @@ def test_ingest_fires_uses_keystore_key(monkeypatch):
|
|||
assert any("VIIRS_NOAA21_NRT" in u for u in captured["urls"])
|
||||
|
||||
|
||||
def _reset_firms_poll_state():
|
||||
from upstream_cache import firms_cache
|
||||
import fire_sources
|
||||
|
||||
firms_cache.clear()
|
||||
if hasattr(fire_sources, "_csv_digest"):
|
||||
fire_sources._csv_digest.clear()
|
||||
if hasattr(fire_sources, "_seen_ids"):
|
||||
fire_sources._seen_ids.clear()
|
||||
|
||||
|
||||
def _fake_firms_http(monkeypatch, bodies_by_call: list[str] | None = None, body: str = SAMPLE_CSV):
|
||||
hits = {"n": 0}
|
||||
|
||||
class FakeResp:
|
||||
def __init__(self, text):
|
||||
self.text = text
|
||||
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, **kw):
|
||||
pass
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
return False
|
||||
|
||||
async def get(self, url):
|
||||
idx = hits["n"]
|
||||
hits["n"] += 1
|
||||
if bodies_by_call is not None:
|
||||
text = bodies_by_call[min(idx, len(bodies_by_call) - 1)]
|
||||
else:
|
||||
text = body
|
||||
return FakeResp(text)
|
||||
|
||||
monkeypatch.setenv("FIRMS_MAP_KEY", "k" * 32)
|
||||
monkeypatch.setattr("fire_sources.FIRMS_DATASETS", ["VIIRS_NOAA20_NRT"])
|
||||
monkeypatch.setattr("fire_sources.httpx.AsyncClient", FakeClient)
|
||||
return hits
|
||||
|
||||
|
||||
def test_ingest_fires_skips_unchanged_csv(monkeypatch):
|
||||
"""Same FIRMS CSV must not be re-parsed into a 100k-row ON CONFLICT insert."""
|
||||
_reset_firms_poll_state()
|
||||
hits = _fake_firms_http(monkeypatch)
|
||||
persisted = []
|
||||
|
||||
async def fake_persist(points):
|
||||
persisted.append(len(points))
|
||||
return len(points)
|
||||
|
||||
monkeypatch.setattr("fire_sources.persist_hotspots", fake_persist)
|
||||
|
||||
assert asyncio.run(ingest_fires()) == 5
|
||||
assert persisted == [5]
|
||||
firms_cache_hits = hits["n"]
|
||||
persisted.clear()
|
||||
assert asyncio.run(ingest_fires()) == 0
|
||||
assert persisted == []
|
||||
# TTL cache may skip HTTP; either way we must not persist again.
|
||||
assert hits["n"] >= firms_cache_hits
|
||||
|
||||
|
||||
def test_ingest_fires_persists_only_new_hotspots(monkeypatch):
|
||||
"""When the CSV grows, persist the delta — not the whole 2-day dump."""
|
||||
_reset_firms_poll_state()
|
||||
extra = (
|
||||
SAMPLE_CSV
|
||||
+ "16.00000,-12.00000,340.00,0.40,0.40,2025-06-06,1500,N20,VIIRS,h,2.0NRT,310.00,8.00,D\n"
|
||||
)
|
||||
hits = _fake_firms_http(monkeypatch, bodies_by_call=[SAMPLE_CSV, extra])
|
||||
persisted = []
|
||||
|
||||
async def fake_persist(points):
|
||||
persisted.append([p["latitude"] for p in points])
|
||||
return len(points)
|
||||
|
||||
monkeypatch.setattr("fire_sources.persist_hotspots", fake_persist)
|
||||
|
||||
from upstream_cache import firms_cache
|
||||
|
||||
assert asyncio.run(ingest_fires()) == 5
|
||||
firms_cache.clear() # force the next poll to see the grown CSV
|
||||
persisted.clear()
|
||||
assert asyncio.run(ingest_fires()) == 1
|
||||
assert persisted == [[16.0]]
|
||||
assert hits["n"] == 2
|
||||
|
||||
|
||||
def _async_return(value):
|
||||
async def inner():
|
||||
return value
|
||||
|
|
|
|||
|
|
@ -14,11 +14,6 @@ def test_summarizer_dockerfile_copies_intel_modules():
|
|||
assert "nous_client.py" in df
|
||||
|
||||
|
||||
def test_news_panel_pins_daily_recap():
|
||||
assert "kind=daily_recap" in HTML
|
||||
assert "DAILY RECAP" in HTML
|
||||
|
||||
|
||||
def test_nginx_ws_snippet_has_upgrade_headers():
|
||||
conf = (ROOT / "deploy/osint-ws.nginx.conf").read_text()
|
||||
assert "proxy_http_version 1.1" in conf
|
||||
|
|
@ -47,40 +42,3 @@ def test_ws_reconnect_uses_backoff():
|
|||
def test_check_health_treats_degraded_status():
|
||||
fn = HTML.split("async function checkHealth")[1].split("/* ═══════════════ NAV")[0]
|
||||
assert "degraded" in fn.lower() or "d.status" in fn
|
||||
|
||||
|
||||
def test_chokepoint_presets_in_toolbar():
|
||||
assert 'id="chokepoint-btns"' in HTML
|
||||
assert 'id="chokepoint-select"' in HTML
|
||||
assert "loadChokepoints()" in HTML
|
||||
assert "/api/map/chokepoints" in HTML
|
||||
assert "function applyChokepoint" in HTML
|
||||
for name in ("Hormuz", "Bab el-Mandeb", "Suez", "Malacca", "Taiwan"):
|
||||
assert name in HTML
|
||||
|
||||
|
||||
def test_chokepoint_skips_aisstream_subscribe_outside_conus():
|
||||
load = HTML.split("async function loadVessels")[1].split("async function toggleStorms")[0]
|
||||
assert "intersectsConus()" in load
|
||||
assert "api/vessels/subscribe" in load
|
||||
assert "src=${encodeURIComponent(vesselSrcPref)}" in load or "&src=" in load
|
||||
apply = HTML.split("function applyChokepoint")[1].split("function currentBBox")[0]
|
||||
assert "vesselapi" in apply
|
||||
assert "lp-vessels-on" in apply
|
||||
assert "lp-sentinel-on" in apply
|
||||
assert "map.setView" in apply
|
||||
assert "minlat,minlon,maxlat,maxlon" in HTML.split("function chokepointLeafletBounds")[1][:400]
|
||||
|
||||
|
||||
def test_news_ticker_polls_more_often_than_summarizer_cycle():
|
||||
assert "NEWS_REFRESH_MS" in HTML
|
||||
# Summarizer is 15 min; ticker should refresh on a shorter cadence so
|
||||
# lesser-news fills show up without waiting for the next brief.
|
||||
line = [ln for ln in HTML.splitlines() if "NEWS_REFRESH_MS" in ln][0]
|
||||
assert "900000" not in line
|
||||
|
||||
|
||||
def test_phone_chokepoints_use_select_not_buttons():
|
||||
mobile = HTML.split("@media (max-width: 820px)")[1].split("@media (prefers-reduced-motion")[0]
|
||||
assert "#chokepoint-select { display: block; }" in mobile
|
||||
assert ".chokepoint-btns { display: none; }" in mobile or "#chokepoint-label, .chokepoint-btns { display: none; }" in mobile
|
||||
|
|
|
|||
|
|
@ -1,199 +0,0 @@
|
|||
"""GDELT DOC 2.0 quota handling: no http retry on 429, backoff, prose bodies.
|
||||
|
||||
GDELT answers ``429`` with a plain-text "Please limit requests to one every 5
|
||||
seconds" body and no Retry-After header. The ingester must not spend a second
|
||||
request from the same IP on a status error, and must stop calling until the
|
||||
backoff window expires instead of raising a traceback every cycle.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_backoff(monkeypatch):
|
||||
import sources
|
||||
|
||||
sources._gdelt_clear_backoff()
|
||||
monkeypatch.setattr(sources, "GDELT_BACKOFF_BASE", 300)
|
||||
monkeypatch.setattr(sources, "GDELT_BACKOFF_MAX", 1800)
|
||||
# These tests cover the DOC 2.0 path, which is now the fallback behind the
|
||||
# 15-minute bulk GKG file (tests/test_gdelt_bulk.py covers that path).
|
||||
monkeypatch.setattr(sources, "GDELT_BULK_ENABLED", False)
|
||||
yield
|
||||
sources._gdelt_clear_backoff()
|
||||
|
||||
|
||||
class _FakeClient:
|
||||
"""Stands in for httpx.AsyncClient; records every GET it is asked for."""
|
||||
|
||||
def __init__(self, responses, calls):
|
||||
self._responses = list(responses)
|
||||
self._calls = calls
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
return False
|
||||
|
||||
async def get(self, url, params=None):
|
||||
self._calls.append(url)
|
||||
resp = self._responses.pop(0)
|
||||
resp.request = httpx.Request("GET", url)
|
||||
return resp
|
||||
|
||||
|
||||
def _install(monkeypatch, responses):
|
||||
import sources
|
||||
|
||||
calls: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
sources.httpx, "AsyncClient", lambda **kw: _FakeClient(responses, calls)
|
||||
)
|
||||
return calls
|
||||
|
||||
|
||||
def _no_publish(monkeypatch):
|
||||
import sources
|
||||
|
||||
published: list[str] = []
|
||||
|
||||
async def _fake(subject, event):
|
||||
published.append(subject)
|
||||
|
||||
monkeypatch.setattr(sources, "publish_event", _fake)
|
||||
return published
|
||||
|
||||
|
||||
def test_429_does_not_retry_http_and_starts_backoff(monkeypatch):
|
||||
import sources
|
||||
|
||||
calls = _install(
|
||||
monkeypatch,
|
||||
[httpx.Response(429, text="Please limit requests to one every 5 seconds")],
|
||||
)
|
||||
|
||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
|
||||
assert n == 0
|
||||
assert calls == [sources.GDELT_API] # exactly one request, no http fallback
|
||||
assert sources.gdelt_backoff_remaining() > 250
|
||||
|
||||
|
||||
def test_cycle_skipped_while_backing_off(monkeypatch):
|
||||
import sources
|
||||
|
||||
calls = _install(
|
||||
monkeypatch, [httpx.Response(429, text="Please limit requests to one every 5 seconds")]
|
||||
)
|
||||
asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
assert len(calls) == 1
|
||||
|
||||
# A second cycle inside the window must not touch the network at all.
|
||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
assert n == 0
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_backoff_doubles_then_caps(monkeypatch):
|
||||
import sources
|
||||
|
||||
sources._gdelt_start_backoff()
|
||||
first = sources._gdelt_backoff_secs
|
||||
sources._gdelt_start_backoff()
|
||||
second = sources._gdelt_backoff_secs
|
||||
for _ in range(6):
|
||||
sources._gdelt_start_backoff()
|
||||
|
||||
assert first == 300
|
||||
assert second == 600
|
||||
assert sources._gdelt_backoff_secs == 1800
|
||||
|
||||
|
||||
def test_retry_after_header_is_honoured(monkeypatch):
|
||||
import sources
|
||||
|
||||
_install(monkeypatch, [httpx.Response(429, headers={"Retry-After": "45"}, text="busy")])
|
||||
asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
|
||||
assert 40 <= sources.gdelt_backoff_remaining() <= 45
|
||||
|
||||
|
||||
def test_200_prose_body_treated_as_throttle(monkeypatch):
|
||||
import sources
|
||||
|
||||
calls = _install(
|
||||
monkeypatch,
|
||||
[httpx.Response(200, text="Please limit requests to one every 5 seconds")],
|
||||
)
|
||||
|
||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
|
||||
assert n == 0
|
||||
assert len(calls) == 1
|
||||
assert sources.gdelt_backoff_remaining() > 250
|
||||
|
||||
|
||||
def test_success_publishes_and_clears_backoff(monkeypatch):
|
||||
import sources
|
||||
|
||||
sources._gdelt_start_backoff()
|
||||
sources._gdelt_clear_backoff()
|
||||
published = _no_publish(monkeypatch)
|
||||
_install(
|
||||
monkeypatch,
|
||||
[
|
||||
httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"articles": [
|
||||
{
|
||||
"url": "https://example.com/a",
|
||||
"title": "Protest",
|
||||
"domain": "example.com",
|
||||
"seendate": "20261121T120000Z",
|
||||
"language": "English",
|
||||
"sourcecountry": "United States",
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
|
||||
assert n == 1
|
||||
assert published == ["events.gdelt"]
|
||||
assert sources.gdelt_backoff_remaining() == 0
|
||||
|
||||
|
||||
def test_transport_error_still_falls_back_to_http(monkeypatch):
|
||||
import sources
|
||||
|
||||
class _BoomClient(_FakeClient):
|
||||
async def get(self, url, params=None):
|
||||
self._calls.append(url)
|
||||
if url.startswith("https://"):
|
||||
raise httpx.ConnectError("tls handshake failed")
|
||||
resp = self._responses.pop(0)
|
||||
resp.request = httpx.Request("GET", url)
|
||||
return resp
|
||||
|
||||
calls: list[str] = []
|
||||
responses = [httpx.Response(200, json={"articles": []})]
|
||||
monkeypatch.setattr(
|
||||
sources.httpx, "AsyncClient", lambda **kw: _BoomClient(responses, calls)
|
||||
)
|
||||
_no_publish(monkeypatch)
|
||||
|
||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
||||
|
||||
assert n == 0
|
||||
assert calls == [sources.GDELT_API, sources.GDELT_API.replace("https://", "http://", 1)]
|
||||
assert sources.gdelt_backoff_remaining() == 0
|
||||
|
|
@ -1,274 +0,0 @@
|
|||
"""GDELT 15-minute bulk GKG ingest (throttle-free path).
|
||||
|
||||
The DOC 2.0 API is per-IP quota'd (429). The same article coverage is served as
|
||||
static 15-minute files with no key and no quota. These tests pin the mapping
|
||||
from a GKG row into the existing ``events.gdelt`` event shape, the CONFIG-term
|
||||
filter that keeps volume bounded, and the DOC fallback contract.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
LASTUPDATE = """33287 99e984fd826497ae5765484af3b11521 http://data.gdeltproject.org/gdeltv2/20261121234500.export.CSV.zip
|
||||
46052 c09f32f728f695f2bf753540aa92e6ce http://data.gdeltproject.org/gdeltv2/20261121234500.mentions.CSV.zip
|
||||
2361330 0804c7df5b359f177aeff85cad63d539 http://data.gdeltproject.org/gdeltv2/20261121234500.gkg.csv.zip
|
||||
"""
|
||||
|
||||
# GKG row shape (27 tab-separated fields): id, date, collection, common name,
|
||||
# document id, V1Counts, V2Counts, V1Themes, V2Themes, V2Locations, ..., tone,
|
||||
# ..., V2ExtrasXML.
|
||||
GKG_ROW = "\t".join([
|
||||
"20261121234500-11",
|
||||
"20261121234500",
|
||||
"1",
|
||||
"dominicanrepublicpost.com",
|
||||
"https://dominicanrepublicpost.com/protest-in-iowa/",
|
||||
"PROTEST#29000##0######;",
|
||||
"PROTEST#29000##0#######287;",
|
||||
"PROTEST;TAX_FNCACT;VIOLENT_UNREST;",
|
||||
"PROTEST,12;TAX_FNCACT,4;",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"-4.75,0.5,6.1,7.2,18.3,0,206",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
(
|
||||
"<PAGE_AUTHORS>Gary Stevens</PAGE_AUTHORS>"
|
||||
"<PAGE_PRECISEPUBTIMESTAMP>20261121211600</PAGE_PRECISEPUBTIMESTAMP>"
|
||||
"<PAGE_TITLE>Protest in Iowa & Nebraska</PAGE_TITLE>"
|
||||
),
|
||||
])
|
||||
|
||||
LOCATIONS_ROW = "\t".join([
|
||||
"20261121234500-12", "20261121234500", "1", "wkzo.com",
|
||||
"https://wkzo.com/power-outage/",
|
||||
"", "", "POWER_OUTAGE;CYBER_ATTACK;", "POWER_OUTAGE,9;", "",
|
||||
"", "", "", "", "", "-2.0,0.1,1.0,1.0,1.0,0,10", "", "", "", "", "", "", "",
|
||||
"", "", "", "<PAGE_TITLE>Power outage hits grid</PAGE_TITLE>",
|
||||
])
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _reset_bulk_state(monkeypatch):
|
||||
import sources
|
||||
|
||||
monkeypatch.setattr(sources, "_gdelt_bulk_last_file", None)
|
||||
monkeypatch.setattr(sources, "GDELT_BULK_MAX_EVENTS", 100)
|
||||
sources._gdelt_clear_backoff()
|
||||
yield
|
||||
sources._gdelt_clear_backoff()
|
||||
|
||||
|
||||
def _gkg_zip(rows: list[str]) -> bytes:
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr("20261121234500.gkg.csv", "\n".join(rows) + "\n")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
class _FakeClient:
|
||||
def __init__(self, index_text: str, archive: bytes | None, calls: list[str], fail_archive=False):
|
||||
self._index_text = index_text
|
||||
self._archive = archive
|
||||
self._calls = calls
|
||||
self._fail_archive = fail_archive
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
return False
|
||||
|
||||
async def get(self, url, params=None, **kw):
|
||||
self._calls.append(url)
|
||||
request = httpx.Request("GET", url)
|
||||
if url.endswith("lastupdate.txt"):
|
||||
return httpx.Response(200, text=self._index_text, request=request)
|
||||
if self._fail_archive:
|
||||
raise httpx.TransportError("boom")
|
||||
return httpx.Response(200, content=self._archive or b"", request=request)
|
||||
|
||||
|
||||
def _install(monkeypatch, index_text=LASTUPDATE, archive=None, fail_archive=False):
|
||||
import sources
|
||||
|
||||
calls: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
sources.httpx, "AsyncClient",
|
||||
lambda **kw: _FakeClient(index_text, archive, calls, fail_archive),
|
||||
)
|
||||
return calls
|
||||
|
||||
|
||||
def _collect(monkeypatch):
|
||||
import sources
|
||||
|
||||
published: list[dict] = []
|
||||
|
||||
async def _fake_publish(subject, events):
|
||||
assert subject == "events.gdelt"
|
||||
published.extend(events)
|
||||
return len(events)
|
||||
|
||||
monkeypatch.setattr(sources, "_publish_unknown", _fake_publish)
|
||||
return published
|
||||
|
||||
|
||||
def _no_network(monkeypatch):
|
||||
"""Fail the run if anything reaches the DOC 2.0 API."""
|
||||
import sources
|
||||
|
||||
async def _boom(*a, **kw):
|
||||
raise AssertionError("DOC API must not be called when bulk data lands")
|
||||
|
||||
monkeypatch.setattr(sources, "_ingest_gdelt_doc", _boom)
|
||||
|
||||
|
||||
def test_query_terms_from_config_string():
|
||||
import sources
|
||||
|
||||
assert sources.gdelt_query_terms("") == [
|
||||
"unrest", "protest", "outage", "cyber", "power outage",
|
||||
]
|
||||
assert sources.gdelt_query_terms('(flood OR "power outage")') == [
|
||||
"flood", "power outage",
|
||||
]
|
||||
|
||||
|
||||
def test_select_gdelt_bulk_url_picks_gkg_and_forces_https():
|
||||
import sources
|
||||
|
||||
picked = sources.select_gdelt_bulk_url(LASTUPDATE)
|
||||
assert picked == (
|
||||
"20261121234500.gkg.csv.zip",
|
||||
"https://data.gdeltproject.org/gdeltv2/20261121234500.gkg.csv.zip",
|
||||
)
|
||||
assert sources.select_gdelt_bulk_url("") is None
|
||||
|
||||
|
||||
def test_parse_gkg_row_maps_into_event_shape():
|
||||
import sources
|
||||
|
||||
terms = sources.gdelt_query_terms("")
|
||||
event = sources.parse_gkg_row(GKG_ROW.split("\t"), terms, "20261121234500.gkg.csv.zip")
|
||||
|
||||
assert event["source_type"] == "gdel-t2"
|
||||
assert event["url"] == "https://dominicanrepublicpost.com/protest-in-iowa/"
|
||||
assert event["title"] == "Protest in Iowa & Nebraska"
|
||||
assert event["body"] == "dominicanrepublicpost.com"
|
||||
# Publish time comes from PAGE_PRECISEPUBTIMESTAMP, not the window stamp.
|
||||
assert event["source_timestamp"] == "2026-11-21T21:16:00+00:00"
|
||||
assert "protest" in event["tags"] and "VIOLENT_UNREST" in event["tags"]
|
||||
assert event["raw"]["bulk_file"] == "20261121234500.gkg.csv.zip"
|
||||
assert event["raw"]["tone"] == pytest.approx(-4.75 / 4249.0)
|
||||
# No V2Locations in this row -> no fake geo.
|
||||
assert event["location_lat"] is None and event["location_lon"] is None
|
||||
|
||||
|
||||
def test_parse_gkg_row_reads_geo_from_v2locations():
|
||||
import sources
|
||||
|
||||
row = GKG_ROW.split("\t")
|
||||
row[9] = (
|
||||
"4#Middletown, Iowa, United States#US#IA#40.8284#-91.259#-1834425"
|
||||
";1#United States#US#US#39.8283#-98.5795#US"
|
||||
)
|
||||
event = sources.parse_gkg_row(row, sources.gdelt_query_terms(""))
|
||||
assert event["location_lat"] == pytest.approx(40.8284)
|
||||
assert event["location_lon"] == pytest.approx(-91.259)
|
||||
assert event["location_name"] == "Middletown, Iowa, United States"
|
||||
|
||||
|
||||
def test_gkg_location_tolerates_short_and_bad_forms():
|
||||
import sources
|
||||
|
||||
# adm2 slot dropped: lat/lon are still the last two before the feature id.
|
||||
assert sources._gkg_location("2#California, United States#US#USCA#36.17#-119.746#CA") == (
|
||||
pytest.approx(36.17), pytest.approx(-119.746), "California, United States",
|
||||
)
|
||||
assert sources._gkg_location("")[0] is None
|
||||
assert sources._gkg_location("1#Nowhere#US#US#999#999#X")[0] is None
|
||||
|
||||
|
||||
def test_parse_gkg_row_drops_rows_without_query_terms():
|
||||
import sources
|
||||
|
||||
row = GKG_ROW.split("\t")
|
||||
row[7] = "SPORTS;ENTERTAINMENT;"
|
||||
assert sources.parse_gkg_row(row, sources.gdelt_query_terms("")) is None
|
||||
|
||||
row = GKG_ROW.split("\t")
|
||||
row[4] = ""
|
||||
assert sources.parse_gkg_row(row, sources.gdelt_query_terms("")) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ingest_gdelt_bulk_publishes_filtered_rows_and_skips_repeat(monkeypatch):
|
||||
import sources
|
||||
|
||||
_install(monkeypatch, archive=_gkg_zip([GKG_ROW, LOCATIONS_ROW]))
|
||||
published = _collect(monkeypatch)
|
||||
_no_network(monkeypatch)
|
||||
|
||||
count = await sources.ingest_gdelt()
|
||||
assert count == 2
|
||||
assert {e["url"] for e in published} == {
|
||||
"https://dominicanrepublicpost.com/protest-in-iowa/",
|
||||
"https://wkzo.com/power-outage/",
|
||||
}
|
||||
# Second cycle: same file, nothing new fetched or published.
|
||||
before = len(published)
|
||||
assert await sources.ingest_gdelt() == 0
|
||||
assert len(published) == before
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ingest_gdelt_bulk_caps_events_per_file(monkeypatch):
|
||||
import sources
|
||||
|
||||
rows = []
|
||||
for i in range(5):
|
||||
row = GKG_ROW.split("\t")
|
||||
row[0] = f"20261121234500-{i}"
|
||||
row[4] = f"https://example.com/story-{i}"
|
||||
rows.append("\t".join(row))
|
||||
_install(monkeypatch, archive=_gkg_zip(rows))
|
||||
published = _collect(monkeypatch)
|
||||
_no_network(monkeypatch)
|
||||
|
||||
assert await sources.ingest_gdelt_bulk(max_events=2) == 2
|
||||
assert len(published) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ingest_gdelt_falls_back_to_doc_when_bulk_fails(monkeypatch):
|
||||
import sources
|
||||
|
||||
_install(monkeypatch, fail_archive=True)
|
||||
calls = {"doc": 0}
|
||||
|
||||
async def _doc(query="", max_articles=50):
|
||||
calls["doc"] += 1
|
||||
return 7
|
||||
|
||||
monkeypatch.setattr(sources, "_ingest_gdelt_doc", _doc)
|
||||
assert await sources.ingest_gdelt() == 7
|
||||
assert calls["doc"] == 1
|
||||
|
|
@ -51,33 +51,23 @@ def test_matching_geofences_only_active_hits():
|
|||
assert matching_geofences(-122.4, 37.7, fences) == []
|
||||
|
||||
|
||||
FENCE_ID = "11111111-1111-1111-1111-111111111111"
|
||||
NC_VIEW = (-80.0, 35.0, -78.0, 36.0)
|
||||
SF_VIEW = (-123.0, 37.0, -121.0, 38.0)
|
||||
def test_geofence_alert_fans_out_only_to_viewport_clients():
|
||||
mgr = ConnectionManager()
|
||||
q_nc = mgr.register("nc")
|
||||
q_sf = mgr.register("sf")
|
||||
mgr.set_viewport("nc", (-80.0, 35.0, -78.0, 36.0))
|
||||
mgr.set_viewport("sf", (-123.0, 37.0, -121.0, 38.0))
|
||||
|
||||
|
||||
def _alert_payload(gid=FENCE_ID):
|
||||
return {
|
||||
"geofence_id": gid,
|
||||
async def run():
|
||||
payload = {
|
||||
"geofence_id": "a",
|
||||
"geofence_name": "NC",
|
||||
"source_kind": "ais",
|
||||
"entity_id": "366123456",
|
||||
"lat": 35.5,
|
||||
"lon": -79.0,
|
||||
}
|
||||
|
||||
|
||||
def test_geofence_alert_fans_out_only_to_viewport_clients():
|
||||
mgr = ConnectionManager()
|
||||
q_nc = mgr.register("nc")
|
||||
q_sf = mgr.register("sf")
|
||||
mgr.set_viewport("nc", NC_VIEW)
|
||||
mgr.set_viewport("sf", SF_VIEW)
|
||||
|
||||
async def run():
|
||||
n = await mgr.publish_point(
|
||||
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
|
||||
)
|
||||
n = await mgr.publish_point("geofence_alert", payload, lat=35.5, lon=-79.0)
|
||||
assert n == 1
|
||||
msg = q_nc.get_nowait()
|
||||
assert msg["type"] == "geofence_alert"
|
||||
|
|
@ -87,109 +77,6 @@ def test_geofence_alert_fans_out_only_to_viewport_clients():
|
|||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_off_viewport_watch_receives_geofence_alert():
|
||||
mgr = ConnectionManager()
|
||||
q_sf = mgr.register("sf")
|
||||
mgr.set_viewport("sf", SF_VIEW)
|
||||
mgr.set_watched_geofences("sf", [FENCE_ID])
|
||||
|
||||
async def run():
|
||||
n = await mgr.publish_point(
|
||||
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
|
||||
)
|
||||
assert n == 1
|
||||
msg = q_sf.get_nowait()
|
||||
assert msg["type"] == "geofence_alert"
|
||||
assert msg["payload"]["geofence_id"] == FENCE_ID
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_off_viewport_without_watch_does_not_receive_geofence_alert():
|
||||
mgr = ConnectionManager()
|
||||
q_sf = mgr.register("sf")
|
||||
mgr.set_viewport("sf", SF_VIEW)
|
||||
|
||||
async def run():
|
||||
n = await mgr.publish_point(
|
||||
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
|
||||
)
|
||||
assert n == 0
|
||||
assert q_sf.empty()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_on_viewport_receives_geofence_alert_without_watch():
|
||||
mgr = ConnectionManager()
|
||||
q_nc = mgr.register("nc")
|
||||
mgr.set_viewport("nc", NC_VIEW)
|
||||
|
||||
async def run():
|
||||
n = await mgr.publish_point(
|
||||
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
|
||||
)
|
||||
assert n == 1
|
||||
assert q_nc.get_nowait()["type"] == "geofence_alert"
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_ais_stays_viewport_only_even_when_watching():
|
||||
mgr = ConnectionManager()
|
||||
q_sf = mgr.register("sf")
|
||||
mgr.set_viewport("sf", SF_VIEW)
|
||||
mgr.set_watched_geofences("sf", [FENCE_ID])
|
||||
|
||||
async def run():
|
||||
n = await mgr.publish_point("ais", {"id": "366123456"}, lat=35.5, lon=-79.0)
|
||||
assert n == 0
|
||||
assert q_sf.empty()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_invalid_watch_uuids_ignored_empty_list_clears():
|
||||
mgr = ConnectionManager()
|
||||
q = mgr.register("sf")
|
||||
mgr.set_viewport("sf", SF_VIEW)
|
||||
mgr.set_watched_geofences("sf", ["not-a-uuid", FENCE_ID, "also-bad"])
|
||||
|
||||
async def run():
|
||||
n = await mgr.publish_point(
|
||||
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
|
||||
)
|
||||
assert n == 1
|
||||
q.get_nowait()
|
||||
mgr.set_watched_geofences("sf", [])
|
||||
n2 = await mgr.publish_point(
|
||||
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
|
||||
)
|
||||
assert n2 == 0
|
||||
assert q.empty()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_unregister_clears_watched_geofences():
|
||||
mgr = ConnectionManager()
|
||||
q = mgr.register("sf")
|
||||
mgr.set_viewport("sf", SF_VIEW)
|
||||
mgr.set_watched_geofences("sf", [FENCE_ID])
|
||||
mgr.unregister("sf")
|
||||
q2 = mgr.register("sf")
|
||||
mgr.set_viewport("sf", SF_VIEW)
|
||||
|
||||
async def run():
|
||||
n = await mgr.publish_point(
|
||||
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
|
||||
)
|
||||
assert n == 0
|
||||
assert q2.empty()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_record_and_notify_queries_postgis_when_cache_empty(monkeypatch):
|
||||
"""FIRMS ingest in the ingester has an empty in-process cache — still ST_Intersects."""
|
||||
import geofence
|
||||
|
|
@ -247,598 +134,3 @@ def test_record_and_notify_queries_postgis_when_cache_empty(monkeypatch):
|
|||
inserts = [p for p in executed if isinstance(p, dict)]
|
||||
assert inserts and inserts[0]["source_kind"] == "firms"
|
||||
assert "commit" in executed
|
||||
|
||||
|
||||
def test_list_alerts_sql_filters(monkeypatch):
|
||||
captured: dict = {}
|
||||
|
||||
class FakeResult:
|
||||
def mappings(self):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return []
|
||||
|
||||
class FakeSession:
|
||||
async def execute(self, stmt, params=None):
|
||||
captured["sql"] = str(stmt)
|
||||
captured["params"] = params
|
||||
return FakeResult()
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(geofence, "async_session", FakeSession)
|
||||
from datetime import datetime, timezone
|
||||
|
||||
since = datetime(2026, 8, 28, tzinfo=timezone.utc)
|
||||
until = datetime(2026, 8, 29, tzinfo=timezone.utc)
|
||||
|
||||
async def run():
|
||||
return await geofence.list_alerts(
|
||||
geofence_id=FENCE_ID, since=since, until=until,
|
||||
source_kind="firms", limit=5,
|
||||
)
|
||||
|
||||
assert asyncio.run(run()) == []
|
||||
sql = captured["sql"].lower()
|
||||
assert "geofence_id" in sql
|
||||
assert "created_at >=" in sql
|
||||
assert "created_at <=" in sql
|
||||
assert "source_kind" in sql
|
||||
assert captured["params"]["geofence_id"] == FENCE_ID
|
||||
assert captured["params"]["source_kind"] == "firms"
|
||||
assert captured["params"]["limit"] == 5
|
||||
|
||||
|
||||
def test_alembic_fence_created_index_exists():
|
||||
from pathlib import Path
|
||||
text = Path(__file__).resolve().parent.parent.joinpath(
|
||||
"alembic/versions/011_geofence_alerts_fence.py",
|
||||
).read_text()
|
||||
assert "ix_geofence_alerts_fence_created" in text
|
||||
assert "010_bbox_gist" in text
|
||||
|
||||
|
||||
def test_snapshot_at_404_when_fence_missing(monkeypatch):
|
||||
geofence._cache.clear()
|
||||
|
||||
async def boom():
|
||||
raise RuntimeError("db down")
|
||||
|
||||
monkeypatch.setattr(geofence, "refresh_cache", boom)
|
||||
|
||||
async def run():
|
||||
from datetime import datetime, timezone
|
||||
return await geofence.snapshot_at(
|
||||
FENCE_ID, datetime(2026, 8, 28, 12, 4, tzinfo=timezone.utc),
|
||||
)
|
||||
|
||||
assert asyncio.run(run()) is None
|
||||
|
||||
|
||||
def test_snapshot_queries_st_intersects(monkeypatch):
|
||||
geofence._cache[:] = [{
|
||||
"id": FENCE_ID, "name": "NC", "geojson": NC_BOX, "active": True,
|
||||
}]
|
||||
sqls: list[str] = []
|
||||
|
||||
class FakeResult:
|
||||
def mappings(self):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return []
|
||||
|
||||
class FakeSession:
|
||||
async def execute(self, stmt, params=None):
|
||||
sqls.append(str(stmt))
|
||||
return FakeResult()
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(geofence, "async_session", FakeSession)
|
||||
|
||||
async def run():
|
||||
from datetime import datetime, timezone
|
||||
return await geofence.snapshot_at(
|
||||
FENCE_ID, datetime(2026, 8, 28, 12, 4, 30, tzinfo=timezone.utc),
|
||||
)
|
||||
|
||||
body = asyncio.run(run())
|
||||
assert body["aircraft"] == []
|
||||
assert body["vessels"] == []
|
||||
assert body["fires"] == []
|
||||
blob = "\n".join(sqls).lower()
|
||||
assert "st_intersects" in blob
|
||||
assert "aircraft_tracks_1min" in blob
|
||||
assert "vessel_tracks_1min" in blob
|
||||
assert "from fires" in blob
|
||||
|
||||
|
||||
def _reset_geofence_state():
|
||||
geofence._cache.clear()
|
||||
geofence._recent_hits.clear()
|
||||
geofence._notified_once.clear()
|
||||
|
||||
|
||||
class _MapResult:
|
||||
def __init__(self, rows):
|
||||
self._rows = rows
|
||||
self.rowcount = 1
|
||||
self.inserted_primary_key = ["evt-1"]
|
||||
|
||||
def mappings(self):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return self._rows
|
||||
|
||||
def first(self):
|
||||
return self._rows[0] if self._rows else None
|
||||
|
||||
|
||||
def _fence_session(inserts, cameras, news, already=None):
|
||||
"""Fake session: evidence queries return rows; inserts are recorded."""
|
||||
already_rows = [] if already is None else already
|
||||
|
||||
class Sess:
|
||||
async def execute(self, stmt, params=None):
|
||||
sql = str(stmt).lower()
|
||||
if "insert into geofence_alerts" in sql:
|
||||
inserts.append(params or {})
|
||||
return _MapResult([])
|
||||
if "from cameras" in sql:
|
||||
return _MapResult(cameras)
|
||||
if "from news_items" in sql and "kind = 'map'" not in sql and "kind = " not in sql:
|
||||
return _MapResult(news)
|
||||
if "from geofence_alerts" in sql:
|
||||
return _MapResult(already_rows)
|
||||
return _MapResult([])
|
||||
|
||||
async def commit(self):
|
||||
inserts.append("commit")
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
return Sess
|
||||
|
||||
|
||||
def _install_polygon(monkeypatch, inserts, cameras=None, news=None, already=None):
|
||||
_reset_geofence_state()
|
||||
fence = {"id": FENCE_ID, "name": "NC", "geojson": NC_BOX, "active": True}
|
||||
|
||||
async def fake_st(lon, lat):
|
||||
return matching_geofences(lon, lat, [fence])
|
||||
|
||||
monkeypatch.setattr(geofence, "st_intersects", fake_st)
|
||||
if cameras is None:
|
||||
cameras = [{
|
||||
"id": "cam-1",
|
||||
"name": "Dock",
|
||||
"snapshot_url": "rtsp://agency.example/stream",
|
||||
}]
|
||||
if news is None:
|
||||
news = [{
|
||||
"headline": "Quake felt",
|
||||
"url": "https://example.com/q",
|
||||
"importance": "high",
|
||||
}]
|
||||
monkeypatch.setattr(
|
||||
geofence, "async_session",
|
||||
lambda: _fence_session(inserts, cameras, news, already)(),
|
||||
)
|
||||
return fence
|
||||
|
||||
|
||||
def _alert_rows(inserts):
|
||||
return [p for p in inserts if isinstance(p, dict)]
|
||||
|
||||
|
||||
def _evidence(row):
|
||||
import json
|
||||
return json.loads(row["payload"])["evidence"]
|
||||
|
||||
|
||||
def test_camera_evidence_never_copies_agency_or_rtsp_url():
|
||||
from geofence import _CAMERAS_INSIDE_SQL, camera_evidence
|
||||
assert "snapshot_url" not in _CAMERAS_INSIDE_SQL.lower()
|
||||
row = camera_evidence({
|
||||
"id": "abc",
|
||||
"name": "",
|
||||
"snapshot_url": "rtsp://agency.example/live",
|
||||
"location_name": "ignored-when-name-set",
|
||||
})
|
||||
assert row == {
|
||||
"id": "abc",
|
||||
"name": "",
|
||||
"snapshot_url": "/api/cameras/abc/snapshot",
|
||||
}
|
||||
assert "rtsp" not in row["snapshot_url"]
|
||||
assert not row["snapshot_url"].startswith("http")
|
||||
|
||||
|
||||
def test_evidence_caps_and_empty_arrays():
|
||||
from datetime import datetime, timezone
|
||||
from geofence import evidence_pack
|
||||
now = datetime(2026, 8, 28, 12, 4, tzinfo=timezone.utc)
|
||||
cams = [{"id": f"c{i}", "name": f"n{i}"} for i in range(8)]
|
||||
news = [
|
||||
{"headline": f"h{i}", "url": "", "importance": ""} for i in range(6)
|
||||
]
|
||||
pack = evidence_pack(FENCE_ID, now, cams, news)
|
||||
assert len(pack["cameras"]) == 5
|
||||
assert len(pack["news"]) == 3
|
||||
empty = evidence_pack(FENCE_ID, now, [], [])
|
||||
assert empty["cameras"] == []
|
||||
assert empty["news"] == []
|
||||
assert empty["snapshot"] == f"/api/geofences/{FENCE_ID}/at?ts=2026-08-28T12:04:00Z"
|
||||
|
||||
|
||||
def test_inside_writes_evidence_outside_writes_nothing(monkeypatch):
|
||||
"""Polygon fixture: inside → 1 row + evidence; outside → 0. Each new kind."""
|
||||
import json
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
from tracks import parse_timestamp
|
||||
|
||||
for kind, entity in (
|
||||
("earthquake", "ci1"),
|
||||
("fire_incident", "IRWIN-1"),
|
||||
("news", "42"),
|
||||
):
|
||||
inserts: list = []
|
||||
_install_polygon(monkeypatch, inserts)
|
||||
|
||||
async def run(k=kind, eid=entity):
|
||||
inside = await geofence.record_and_notify(
|
||||
source_kind=k, entity_id=eid, lat=35.5, lon=-79.0,
|
||||
payload={"label": "inside"},
|
||||
)
|
||||
outside = await geofence.record_and_notify(
|
||||
source_kind=k, entity_id=eid + "-out", lat=37.7, lon=-122.4,
|
||||
payload={"label": "outside"},
|
||||
)
|
||||
return inside, outside
|
||||
|
||||
n_in, n_out = asyncio.run(run())
|
||||
rows = _alert_rows(inserts)
|
||||
assert n_out == 0
|
||||
assert rows and len(rows) == 1, kind
|
||||
assert rows[0]["source_kind"] == kind
|
||||
ev = json.loads(rows[0]["payload"])["evidence"]
|
||||
assert set(ev) == {"cameras", "news", "snapshot"}
|
||||
assert set(ev["cameras"][0]) == {"id", "name", "snapshot_url"}
|
||||
assert set(ev["news"][0]) == {"headline", "url", "importance"}
|
||||
assert ev["cameras"][0]["id"] == "cam-1"
|
||||
assert ev["cameras"][0]["name"] == "Dock"
|
||||
assert ev["cameras"][0]["snapshot_url"] == "/api/cameras/cam-1/snapshot"
|
||||
assert ev["news"][0] == {
|
||||
"headline": "Quake felt",
|
||||
"url": "https://example.com/q",
|
||||
"importance": "high",
|
||||
}
|
||||
assert ev["snapshot"].startswith(f"/api/geofences/{FENCE_ID}/at?ts=")
|
||||
assert "rtsp" not in json.dumps(ev)
|
||||
assert "http" not in ev["cameras"][0]["snapshot_url"]
|
||||
qs = parse_qs(urlsplit(ev["snapshot"]).query)
|
||||
assert "ts" in qs and "timestamp" not in qs
|
||||
assert parse_timestamp(qs["ts"][0]) is not None
|
||||
assert n_in == 0 or n_in >= 0 # WS fan-out may be 0 with no clients
|
||||
|
||||
|
||||
def test_firms_hit_omits_evidence(monkeypatch):
|
||||
inserts: list = []
|
||||
_install_polygon(monkeypatch, inserts)
|
||||
|
||||
async def run():
|
||||
return await geofence.record_and_notify(
|
||||
source_kind="firms", entity_id="35.5,-79.0,N",
|
||||
lat=35.5, lon=-79.0, payload={"satellite": "N"},
|
||||
)
|
||||
|
||||
asyncio.run(run())
|
||||
rows = _alert_rows(inserts)
|
||||
import json
|
||||
body = json.loads(rows[0]["payload"])
|
||||
assert "evidence" not in body
|
||||
assert body["satellite"] == "N"
|
||||
|
||||
|
||||
def test_same_entity_inside_five_minutes_is_one_row(monkeypatch):
|
||||
inserts: list = []
|
||||
_install_polygon(monkeypatch, inserts)
|
||||
|
||||
async def run():
|
||||
a = await geofence.record_and_notify(
|
||||
source_kind="fire_incident", entity_id="IRWIN-1",
|
||||
lat=35.5, lon=-79.0, payload={"label": "Foster"},
|
||||
)
|
||||
b = await geofence.record_and_notify(
|
||||
source_kind="fire_incident", entity_id="IRWIN-1",
|
||||
lat=35.5, lon=-79.0, payload={"label": "Foster"},
|
||||
)
|
||||
return a, b
|
||||
|
||||
asyncio.run(run())
|
||||
assert len(_alert_rows(inserts)) == 1
|
||||
|
||||
|
||||
def test_skip_existing_does_not_renotify_after_cooldown(monkeypatch):
|
||||
"""A later poll of the same incident id must not insert again."""
|
||||
inserts: list = []
|
||||
already = []
|
||||
_install_polygon(monkeypatch, inserts, already=already)
|
||||
|
||||
async def run():
|
||||
await geofence.record_and_notify(
|
||||
source_kind="fire_incident", entity_id="IRWIN-9",
|
||||
lat=35.5, lon=-79.0, skip_existing=True,
|
||||
)
|
||||
geofence._recent_hits.clear()
|
||||
geofence._notified_once.clear()
|
||||
already.append({"one": 1})
|
||||
await geofence.record_and_notify(
|
||||
source_kind="fire_incident", entity_id="IRWIN-9",
|
||||
lat=35.5, lon=-79.0, skip_existing=True,
|
||||
)
|
||||
|
||||
asyncio.run(run())
|
||||
assert len(_alert_rows(inserts)) == 1
|
||||
|
||||
|
||||
def test_camera_kind_is_refused(monkeypatch):
|
||||
inserts: list = []
|
||||
called = {"st": 0}
|
||||
_install_polygon(monkeypatch, inserts)
|
||||
|
||||
async def fake_st(lon, lat):
|
||||
called["st"] += 1
|
||||
return [{"id": FENCE_ID, "name": "NC", "active": True}]
|
||||
|
||||
monkeypatch.setattr(geofence, "st_intersects", fake_st)
|
||||
|
||||
async def run():
|
||||
return await geofence.record_and_notify(
|
||||
source_kind="camera", entity_id="cam-1", lat=35.5, lon=-79.0,
|
||||
)
|
||||
|
||||
assert asyncio.run(run()) == 0
|
||||
assert called["st"] == 0
|
||||
assert _alert_rows(inserts) == []
|
||||
|
||||
|
||||
def test_camera_publish_and_insert_do_not_notify(monkeypatch):
|
||||
import camera_scraper
|
||||
import ingestor
|
||||
import run_camera_service
|
||||
from datetime import datetime, timezone
|
||||
|
||||
called = []
|
||||
|
||||
async def fake_record(**kwargs):
|
||||
called.append(kwargs)
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
|
||||
|
||||
class Sess:
|
||||
async def execute(self, stmt, params=None):
|
||||
return _MapResult([])
|
||||
|
||||
async def commit(self):
|
||||
return None
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(camera_scraper, "async_session", lambda: Sess())
|
||||
|
||||
async def upsert():
|
||||
return await camera_scraper.upsert_cameras([{
|
||||
"source_url": "http://cam.example/snap",
|
||||
"discovery_source": "test",
|
||||
"location_lat": 35.5,
|
||||
"location_lon": -79.0,
|
||||
"location_name": "Dock",
|
||||
"snapshot_url": "rtsp://agency.example/stream",
|
||||
}])
|
||||
|
||||
assert asyncio.run(upsert()) == 1
|
||||
assert called == []
|
||||
|
||||
monkeypatch.setattr(ingestor, "async_session", lambda: Sess())
|
||||
|
||||
async def ingest_cam():
|
||||
return await ingestor.ingest_event({
|
||||
"source_type": "camera",
|
||||
"title": "Open camera",
|
||||
"url": "http://cam.example/snap",
|
||||
"location_lat": 35.5,
|
||||
"location_lon": -79.0,
|
||||
"location_name": "Dock",
|
||||
"source_timestamp": "2026-08-28T12:00:00+00:00",
|
||||
})
|
||||
|
||||
assert asyncio.run(ingest_cam()) == "evt-1"
|
||||
assert called == []
|
||||
|
||||
now = datetime(2026, 8, 28, 12, tzinfo=timezone.utc)
|
||||
|
||||
class Pub:
|
||||
async def publish(self, *a, **k):
|
||||
return None
|
||||
|
||||
class NC:
|
||||
def jetstream(self):
|
||||
return Pub()
|
||||
|
||||
async def close(self):
|
||||
return None
|
||||
|
||||
class _Nats:
|
||||
@staticmethod
|
||||
async def connect(*a, **k):
|
||||
return NC()
|
||||
|
||||
class CamSess:
|
||||
async def execute(self, stmt, params=None):
|
||||
return _MapResult([{
|
||||
"vendor": "x",
|
||||
"source_url": "http://cam.example/snap",
|
||||
"location_lat": 35.5,
|
||||
"location_lon": -79.0,
|
||||
"location_name": "Dock",
|
||||
"discovery_source": "test",
|
||||
"url_hash": "abc",
|
||||
"snapshot_url": "rtsp://agency.example/stream",
|
||||
"device_type": "rtsp",
|
||||
"first_seen": now,
|
||||
"last_seen": now,
|
||||
}])
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(run_camera_service, "nats", _Nats)
|
||||
monkeypatch.setattr(run_camera_service, "async_session", lambda: CamSess())
|
||||
|
||||
async def publish():
|
||||
return await run_camera_service.publish_new_cameras()
|
||||
|
||||
assert asyncio.run(publish()) == 1
|
||||
assert called == []
|
||||
assert all(c.get("source_kind") != "camera" for c in called)
|
||||
|
||||
|
||||
def test_fire_poll_inside_notifies_outside_does_not(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def fake_load(bbox):
|
||||
assert bbox == "-80.0,35.0,-78.0,36.0"
|
||||
return [
|
||||
{
|
||||
"id": "In Fire", "lat": 35.5, "lon": -79.0, "label": "In Fire",
|
||||
"extra": {"irwin_id": "IRWIN-IN", "src": "wfigs"},
|
||||
},
|
||||
{
|
||||
"id": "Out Fire", "lat": 37.7, "lon": -122.4, "label": "Out Fire",
|
||||
"extra": {"irwin_id": "IRWIN-OUT", "src": "wfigs"},
|
||||
},
|
||||
]
|
||||
|
||||
async def fake_record(**kwargs):
|
||||
calls.append(kwargs)
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr("live_layers.load_fire_incidents", fake_load)
|
||||
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
|
||||
fence = {"id": FENCE_ID, "name": "NC", "geojson": NC_BOX, "active": True}
|
||||
|
||||
async def run():
|
||||
return await geofence.poll_fire_incidents([fence])
|
||||
|
||||
assert asyncio.run(run()) == 1
|
||||
assert len(calls) == 1
|
||||
assert calls[0]["source_kind"] == "fire_incident"
|
||||
assert calls[0]["entity_id"] == "IRWIN-IN"
|
||||
assert calls[0]["skip_existing"] is True
|
||||
|
||||
|
||||
def test_ingest_earthquake_notifies_camera_message_does_not(monkeypatch):
|
||||
import ingestor
|
||||
|
||||
calls = []
|
||||
|
||||
async def fake_record(**kwargs):
|
||||
calls.append(kwargs)
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
|
||||
|
||||
class Sess:
|
||||
async def execute(self, stmt, params=None):
|
||||
return _MapResult([])
|
||||
|
||||
async def commit(self):
|
||||
return None
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(ingestor, "async_session", lambda: Sess())
|
||||
|
||||
async def run():
|
||||
qid = await ingestor.ingest_event({
|
||||
"source_type": "earthquake",
|
||||
"title": "M 2.1",
|
||||
"url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci1",
|
||||
"location_lat": 35.5,
|
||||
"location_lon": -79.0,
|
||||
"raw": {"usgs_id": "ci1"},
|
||||
"source_timestamp": "2026-08-28T12:00:00+00:00",
|
||||
})
|
||||
cid = await ingestor.ingest_event({
|
||||
"source_type": "camera",
|
||||
"title": "cam",
|
||||
"url": "http://cam.example/a",
|
||||
"location_lat": 35.5,
|
||||
"location_lon": -79.0,
|
||||
"source_timestamp": "2026-08-28T12:00:00+00:00",
|
||||
})
|
||||
return qid, cid
|
||||
|
||||
qid, cid = asyncio.run(run())
|
||||
assert qid == "evt-1"
|
||||
assert cid == "evt-1"
|
||||
assert len(calls) == 1
|
||||
assert calls[0]["source_kind"] == "earthquake"
|
||||
assert calls[0]["entity_id"] == "ci1"
|
||||
assert calls[0]["lat"] == 35.5
|
||||
assert calls[0]["lon"] == -79.0
|
||||
|
||||
|
||||
def test_news_scan_reads_pins_without_summarizer(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def fake_rows(sql, params):
|
||||
assert "news_items" in sql
|
||||
assert "kind = 'map'" in sql
|
||||
return [{
|
||||
"id": "9", "headline": "Bridge", "url": "https://n.example/b",
|
||||
"importance": "critical", "lat": 35.5, "lon": -79.0,
|
||||
}]
|
||||
|
||||
async def fake_record(**kwargs):
|
||||
calls.append(kwargs)
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr(geofence, "_rows", fake_rows)
|
||||
monkeypatch.setattr(geofence, "record_and_notify", fake_record)
|
||||
|
||||
async def run():
|
||||
return await geofence.scan_news_pins()
|
||||
|
||||
assert asyncio.run(run()) == 1
|
||||
assert calls[0]["source_kind"] == "news"
|
||||
assert calls[0]["entity_id"] == "9"
|
||||
assert calls[0]["skip_existing"] is True
|
||||
|
|
|
|||
|
|
@ -1,207 +0,0 @@
|
|||
"""Geofence layer panel: draw, watch, inbox, delete (HTML contract)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
HTML = (ROOT / "app/static/index.html").read_text()
|
||||
|
||||
|
||||
def test_geofence_panel_has_list_and_delete_hook():
|
||||
assert 'id="gf-draw"' in HTML
|
||||
assert 'id="gf-list"' in HTML
|
||||
assert "function deleteGeofence" in HTML
|
||||
assert "method: 'DELETE'" in HTML or 'method: "DELETE"' in HTML
|
||||
assert "/api/geofences/" in HTML
|
||||
|
||||
|
||||
def test_load_geofences_renders_delete_controls():
|
||||
js = HTML.split("async function loadGeofences", 1)[1].split(
|
||||
"async function loadFireAircraftHits", 1
|
||||
)[0]
|
||||
assert "gf-list" in js
|
||||
assert "deleteGeofence" in js
|
||||
assert "onEachFeature" in js
|
||||
assert "bindPopup" in js
|
||||
|
||||
|
||||
def test_finish_cancel_draw_controls():
|
||||
assert 'id="gf-finish"' in HTML
|
||||
assert 'id="gf-cancel"' in HTML
|
||||
assert "function cancelGeofenceDraw" in HTML
|
||||
assert "function onGfClose" in HTML
|
||||
|
||||
|
||||
def test_watch_geofences_ws_payload():
|
||||
assert "watch_geofences" in HTML
|
||||
assert "function sendWatchGeofences" in HTML
|
||||
|
||||
|
||||
def test_geofence_alert_inbox():
|
||||
assert 'id="gf-inbox"' in HTML
|
||||
assert "/api/geofence-alerts" in HTML
|
||||
assert "function loadGfInbox" in HTML
|
||||
assert "function pushGfInbox" in HTML
|
||||
|
||||
|
||||
def test_delete_geofence_still_present():
|
||||
assert "function deleteGeofence" in HTML
|
||||
assert "method: 'DELETE'" in HTML or 'method: "DELETE"' in HTML
|
||||
|
||||
|
||||
def test_fence_dvr_at_endpoint():
|
||||
assert "/at?timestamp=" in HTML or "/at?timestamp=${" in HTML
|
||||
assert "function dvrScrubFence" in HTML
|
||||
assert "gfSelectedId" in HTML
|
||||
|
||||
|
||||
def _inbox_src() -> str:
|
||||
news = HTML.split("function newsEsc", 1)[1].split("function newsTimeAgo", 1)[0]
|
||||
inbox = HTML.split("function gfHitTime", 1)[1].split("function onGfHitClick", 1)[0]
|
||||
return "function newsEsc" + news + "function gfHitTime" + inbox
|
||||
|
||||
|
||||
def _render_inbox(hits: list) -> list[dict]:
|
||||
harness = r"""
|
||||
const fs = require('fs');
|
||||
const src = fs.readFileSync(process.argv[2], 'utf8');
|
||||
const hits = JSON.parse(fs.readFileSync(process.argv[3], 'utf8'));
|
||||
var gfNameById = {};
|
||||
function makeBox() {
|
||||
const kids = [];
|
||||
const box = {
|
||||
children: kids,
|
||||
prepend(el) { kids.unshift(el); },
|
||||
removeChild(el) {
|
||||
const i = kids.indexOf(el);
|
||||
if (i >= 0) kids.splice(i, 1);
|
||||
},
|
||||
};
|
||||
global.document = {
|
||||
getElementById(id) { return id === 'gf-inbox' ? box : null; },
|
||||
createElement() {
|
||||
return { type: '', className: '', dataset: {}, innerHTML: '', onclick: null };
|
||||
},
|
||||
};
|
||||
return box;
|
||||
}
|
||||
eval(src);
|
||||
const out = [];
|
||||
for (const hit of hits) {
|
||||
const box = makeBox();
|
||||
pushGfInbox(hit);
|
||||
const el = box.children[0];
|
||||
out.push({
|
||||
html: el ? el.innerHTML : '',
|
||||
hasOnclick: !!(el && typeof el.onclick === 'function'),
|
||||
});
|
||||
}
|
||||
process.stdout.write(JSON.stringify(out));
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td)
|
||||
src_path = root / "inbox.js"
|
||||
hits_path = root / "hits.json"
|
||||
harness_path = root / "harness.js"
|
||||
src_path.write_text(_inbox_src())
|
||||
hits_path.write_text(json.dumps(hits))
|
||||
harness_path.write_text(harness)
|
||||
proc = subprocess.run(
|
||||
["node", str(harness_path), str(src_path), str(hits_path)],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert proc.returncode == 0, proc.stderr
|
||||
return json.loads(proc.stdout)
|
||||
|
||||
|
||||
def test_push_gf_inbox_evidence_pack():
|
||||
"""Second line from payload.evidence; missing evidence stays the one-liner."""
|
||||
linked = {
|
||||
"geofence_name": "Yard",
|
||||
"source_kind": "news",
|
||||
"entity_id": "n-1",
|
||||
"created_at": "2026-11-14T05:00:00Z",
|
||||
"payload": {
|
||||
"evidence": {
|
||||
"cameras": [
|
||||
{"id": "c1", "name": "North Gate", "snapshot_url": "rtsp://camera/1"},
|
||||
{"id": "c2", "name": "South Gate", "snapshot_url": "/api/cameras/c2/snapshot"},
|
||||
],
|
||||
"news": [{"headline": "Fence brief", "url": "https://ex.com/1", "importance": "high"}],
|
||||
"snapshot": "/api/geofences/g1/at?ts=2026-11-14T05:00:00Z",
|
||||
}
|
||||
},
|
||||
}
|
||||
text_news = {
|
||||
"geofence_name": "Yard",
|
||||
"source_kind": "earthquake",
|
||||
"entity_id": "eq-9",
|
||||
"payload": {
|
||||
"evidence": {
|
||||
"cameras": [],
|
||||
"news": [{"headline": "Silent quake", "url": "", "importance": ""}],
|
||||
}
|
||||
},
|
||||
}
|
||||
bare = {
|
||||
"geofence_name": "Old Fence",
|
||||
"source_kind": "adsb",
|
||||
"entity_id": "abc123",
|
||||
"payload": {"icao": "abc123"},
|
||||
}
|
||||
top_level = {
|
||||
"geofence_name": "Top",
|
||||
"source_kind": "fire_incident",
|
||||
"entity_id": "fi-1",
|
||||
"evidence": {
|
||||
"cameras": [{"id": "c9", "name": "Lot Cam", "snapshot_url": "rtsp://camera/1"}],
|
||||
"news": [{"headline": "Lot fire", "url": "https://ex.com/1", "importance": ""}],
|
||||
},
|
||||
}
|
||||
as_string = {
|
||||
"geofence_name": "String Fence",
|
||||
"source_kind": "news",
|
||||
"entity_id": "s1",
|
||||
"payload": json.dumps({
|
||||
"evidence": {
|
||||
"cameras": [{"id": "c3", "name": "Cam A", "snapshot_url": "rtsp://camera/1"}],
|
||||
"news": [{"headline": "From string", "url": "https://ex.com/1", "importance": ""}],
|
||||
}
|
||||
}),
|
||||
}
|
||||
rendered = _render_inbox([linked, text_news, bare, top_level, as_string])
|
||||
html, quiet, plain, fallback, parsed = [row["html"] for row in rendered]
|
||||
|
||||
assert "2 cams" in html
|
||||
assert "North Gate" in html
|
||||
assert 'href="https://ex.com/1"' in html
|
||||
assert 'target="_blank"' in html
|
||||
assert 'rel="noopener"' in html
|
||||
assert "stopPropagation" in html
|
||||
assert "rtsp://camera/1" not in html
|
||||
assert rendered[0]["hasOnclick"]
|
||||
|
||||
assert "Silent quake" in quiet
|
||||
assert "<a" not in quiet
|
||||
assert "Yard" in quiet
|
||||
|
||||
assert "Old Fence" in plain
|
||||
assert "adsb" in plain
|
||||
assert "abc123" in plain
|
||||
assert "cams" not in plain
|
||||
assert "<br>" not in plain
|
||||
assert rendered[2]["hasOnclick"]
|
||||
|
||||
assert "1 cams" in fallback
|
||||
assert 'href="https://ex.com/1"' in fallback
|
||||
assert "rtsp://camera/1" not in fallback
|
||||
|
||||
assert "1 cams" in parsed
|
||||
assert "From string" in parsed
|
||||
assert "rtsp://camera/1" not in parsed
|
||||
|
|
@ -1,150 +0,0 @@
|
|||
"""GPSJAM GPS-interference overlay: level mapping, CSV→GeoJSON, API contract."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
|
||||
from live_layers import gpsjam_csv_to_geojson, gpsjam_level, overlay_catalog, _cache
|
||||
from main import app
|
||||
|
||||
BASE = "http://test"
|
||||
|
||||
# A valid H3 resolution-4 cell id (the payload hex column carries these).
|
||||
HEX_A = "8400c57ffffffff"
|
||||
|
||||
CSV = (
|
||||
"hex,count_good_aircraft,count_bad_aircraft\n"
|
||||
f"{HEX_A},0,20\n" # 100*(20-1)/20 = 95 -> high
|
||||
f"{HEX_A},8,2\n" # 100*(2-1)/10 = 10 -> medium
|
||||
f"{HEX_A},98,2\n" # 100*(2-1)/100 = 1 -> low
|
||||
f"{HEX_A},100,0\n" # bad == 0 -> dropped
|
||||
)
|
||||
|
||||
|
||||
async def _get(path: str) -> httpx.Response:
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||||
return await client.get(path)
|
||||
|
||||
|
||||
def test_gpsjam_level_thresholds():
|
||||
assert gpsjam_level(0.0) == "low"
|
||||
assert gpsjam_level(2.0) == "low"
|
||||
assert gpsjam_level(2.1) == "medium"
|
||||
assert gpsjam_level(10.0) == "medium"
|
||||
assert gpsjam_level(10.1) == "high"
|
||||
assert gpsjam_level(95.0) == "high"
|
||||
|
||||
|
||||
def test_gpsjam_csv_to_geojson_levels_and_drop_zero_bad():
|
||||
fc = gpsjam_csv_to_geojson(CSV)
|
||||
assert fc["type"] == "FeatureCollection"
|
||||
assert len(fc["features"]) == 3 # bad==0 row dropped
|
||||
levels = [f["properties"]["level"] for f in fc["features"]]
|
||||
assert levels == ["high", "medium", "low"]
|
||||
for f in fc["features"]:
|
||||
geom = f["geometry"]
|
||||
assert geom["type"] == "Polygon"
|
||||
ring = geom["coordinates"][0]
|
||||
assert len(ring) == 7 # 6 verts + closing point
|
||||
assert ring[0] == ring[-1]
|
||||
assert f["properties"]["hex"] == HEX_A
|
||||
assert set(f["properties"]).issuperset({"level", "percent_bad", "good", "bad", "hex"})
|
||||
|
||||
|
||||
def test_gpsjam_csv_skips_malformed_rows():
|
||||
bad_csv = "hex,count_good_aircraft,count_bad_aircraft\n" \
|
||||
",1,5\n" \
|
||||
f"{HEX_A},x,5\n" \
|
||||
f"{HEX_A},1,notanint\n" \
|
||||
"not_a_cell,1,5\n"
|
||||
fc = gpsjam_csv_to_geojson(bad_csv)
|
||||
assert fc["features"] == []
|
||||
|
||||
|
||||
def test_overlay_catalog_has_gpsjam_stub():
|
||||
entry = overlay_catalog()["gpsjam"]
|
||||
assert entry["kind"] == "geojson"
|
||||
assert entry["endpoint"] == "/api/map/gpsjam"
|
||||
assert "GPSJAM" in entry["attribution"]
|
||||
|
||||
|
||||
def test_map_gpsjam_returns_featurecollection(monkeypatch):
|
||||
async def fake_fetch(date):
|
||||
return {"type": "FeatureCollection", "features": [{"type": "Feature"}]}
|
||||
|
||||
monkeypatch.setattr("main.fetch_gpsjam", fake_fetch)
|
||||
resp = asyncio.run(_get("/api/map/gpsjam?date=2026-08-28"))
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["type"] == "FeatureCollection"
|
||||
assert "max-age" in (resp.headers.get("cache-control") or "").lower()
|
||||
|
||||
|
||||
def test_map_gpsjam_rejects_bad_date():
|
||||
resp = asyncio.run(_get("/api/map/gpsjam?date=08-28-2026"))
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_map_gpsjam_unavailable_on_404(monkeypatch):
|
||||
import httpx as _httpx
|
||||
|
||||
async def fake_fetch(date):
|
||||
exc = _httpx.HTTPStatusError(
|
||||
"404", request=_httpx.Request("GET", "http://x"), response=_httpx.Response(404)
|
||||
)
|
||||
raise exc
|
||||
|
||||
monkeypatch.setattr("main.fetch_gpsjam", fake_fetch)
|
||||
resp = asyncio.run(_get("/api/map/gpsjam?date=2026-08-28"))
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["error"] == "unavailable"
|
||||
assert body["href"] == "https://gpsjam.org/"
|
||||
|
||||
|
||||
def test_map_gpsjam_unavailable_on_empty_features(monkeypatch):
|
||||
async def fake_fetch(date):
|
||||
return {"type": "FeatureCollection", "features": []}
|
||||
|
||||
monkeypatch.setattr("main.fetch_gpsjam", fake_fetch)
|
||||
resp = asyncio.run(_get("/api/map/gpsjam?date=2026-08-28"))
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["error"] == "unavailable"
|
||||
|
||||
|
||||
def test_fetch_gpsjam_hits_http_once_within_ttl(monkeypatch):
|
||||
_cache.clear()
|
||||
hits = {"n": 0}
|
||||
|
||||
class FakeResp:
|
||||
text = CSV
|
||||
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, **kw):
|
||||
pass
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
return False
|
||||
|
||||
async def get(self, url):
|
||||
hits["n"] += 1
|
||||
assert url == "https://gpsjam.org/data/2026-08-28-h3_4.csv"
|
||||
return FakeResp()
|
||||
|
||||
monkeypatch.setattr("live_layers.httpx.AsyncClient", FakeClient)
|
||||
monkeypatch.setattr("live_layers._http", None)
|
||||
|
||||
from live_layers import fetch_gpsjam
|
||||
|
||||
fc1 = asyncio.run(fetch_gpsjam("2026-08-28"))
|
||||
fc2 = asyncio.run(fetch_gpsjam("2026-08-28"))
|
||||
assert len(fc1["features"]) == 3
|
||||
assert fc2 == fc1
|
||||
assert hits["n"] == 1
|
||||
_cache.clear()
|
||||
|
|
@ -3,21 +3,12 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import asyncpg
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from conftest import requires_db
|
||||
from main import app
|
||||
|
||||
BASE = "http://test"
|
||||
_FIXTURE_URLS = (
|
||||
"https://test.invalid/t_ceb74e64/future",
|
||||
"https://test.invalid/t_ceb74e64/fresh",
|
||||
)
|
||||
|
||||
|
||||
async def _get(path: str) -> httpx.Response:
|
||||
|
|
@ -40,67 +31,3 @@ def test_ready_endpoint_exists():
|
|||
body = resp.json()
|
||||
assert "checks" in body
|
||||
assert "status" in body
|
||||
|
||||
|
||||
def _conn_kwargs() -> dict:
|
||||
return {
|
||||
"host": os.environ["DB_HOST"],
|
||||
"port": int(os.environ["DB_PORT"]),
|
||||
"user": os.environ["DB_USER"],
|
||||
"password": os.environ["DB_PASSWORD"],
|
||||
"database": os.environ["DB_NAME"],
|
||||
}
|
||||
|
||||
|
||||
async def _prepare_article_age_fixture() -> None:
|
||||
"""Insert one row at now+6d and one at now-120s. Deletes only those URLs."""
|
||||
conn = await asyncpg.connect(**_conn_kwargs())
|
||||
try:
|
||||
await conn.execute(
|
||||
"DELETE FROM articles WHERE url = ANY($1::text[])",
|
||||
list(_FIXTURE_URLS),
|
||||
)
|
||||
now = datetime.now(timezone.utc)
|
||||
await conn.executemany(
|
||||
"INSERT INTO articles (title, url, content, domain, timestamp) "
|
||||
"VALUES ($1, $2, $3, $4, $5)",
|
||||
[
|
||||
("future", _FIXTURE_URLS[0], "x", "test.invalid", now + timedelta(days=6)),
|
||||
("fresh", _FIXTURE_URLS[1], "x", "test.invalid", now - timedelta(seconds=120)),
|
||||
],
|
||||
)
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
async def _delete_article_age_fixture() -> None:
|
||||
conn = await asyncpg.connect(**_conn_kwargs())
|
||||
try:
|
||||
await conn.execute(
|
||||
"DELETE FROM articles WHERE url = ANY($1::text[])",
|
||||
list(_FIXTURE_URLS),
|
||||
)
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def article_age_rows():
|
||||
asyncio.run(_prepare_article_age_fixture())
|
||||
yield
|
||||
asyncio.run(_delete_article_age_fixture())
|
||||
|
||||
|
||||
@requires_db
|
||||
def test_health_article_age_ignores_future_rows(article_age_rows):
|
||||
"""Future-dated rows must not pin articles.age_s negative.
|
||||
|
||||
Fixture: one row at now+6d, one at now-120s. age_s is the age of the
|
||||
newest timestamp that is not in the future (NULL timestamps do not count).
|
||||
"""
|
||||
body = asyncio.run(_get("/api/health")).json()
|
||||
articles = body["checks"]["articles"]
|
||||
age = articles["age_s"]
|
||||
assert age is not None
|
||||
assert 0 <= age <= 600, articles
|
||||
assert articles["ok"] is True
|
||||
|
|
|
|||
|
|
@ -1,113 +0,0 @@
|
|||
"""Quiet HUD chrome: VIIRS default, collapsed rail, no Orbitron/MKT dashes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
HTML = (ROOT / "app/static/index.html").read_text()
|
||||
|
||||
|
||||
def _attr(html: str, elem_id: str) -> str:
|
||||
chunk = html.split(f'id="{elem_id}"', 1)[1].split(">", 1)[0]
|
||||
return chunk
|
||||
|
||||
|
||||
def test_initmap_prefers_viirs_true_color():
|
||||
init = HTML.split("async function initMap", 1)[1].split("function readMapPrefs", 1)[0]
|
||||
assert "VIIRS_SNPP_CorrectedReflectance_TrueColor" in init
|
||||
assert init.index("VIIRS_SNPP_CorrectedReflectance_TrueColor") < init.index(
|
||||
"MODIS_Terra_CorrectedReflectance_TrueColor"
|
||||
)
|
||||
assert init.index("MODIS_Terra_CorrectedReflectance_TrueColor") < init.index(
|
||||
"BlueMarble_ShadedRelief_Bathymetry"
|
||||
)
|
||||
|
||||
|
||||
def test_orbitron_gone():
|
||||
assert "Orbitron" not in HTML
|
||||
assert "IBM Plex Sans" in HTML
|
||||
assert "IBM Plex Mono" in HTML
|
||||
|
||||
|
||||
def test_lp_note_stripped_from_layer_list():
|
||||
assert 'class="lp-note"' not in HTML
|
||||
body = HTML.split('class="lp-body"', 1)[1].split("lp-legend", 1)[0]
|
||||
assert "lp-note" not in body
|
||||
|
||||
|
||||
def test_default_overlays_basemap_and_firms_only():
|
||||
fires = _attr(HTML, "lp-fires-on")
|
||||
assert "checked" in fires
|
||||
for eid in (
|
||||
"lp-cams-on",
|
||||
"lp-blips-on",
|
||||
"lp-news-on",
|
||||
"lp-radar-on",
|
||||
"lp-alerts-on",
|
||||
"lp-perim-on",
|
||||
"lp-ac-on",
|
||||
"lp-trains-on",
|
||||
"lp-storms-on",
|
||||
):
|
||||
assert "checked" not in _attr(HTML, eid), eid
|
||||
|
||||
|
||||
def test_geofence_markup_before_cameras():
|
||||
assert 'id="gf-draw"' in HTML
|
||||
assert HTML.index('id="gf-draw"') < HTML.index('id="lp-cams-on"')
|
||||
assert HTML.index('id="lp-base-on"') < HTML.index('id="gf-draw"')
|
||||
|
||||
|
||||
def test_parent_geofence_hud_survives():
|
||||
assert "watch_geofences" in HTML
|
||||
assert "function deleteGeofence" in HTML
|
||||
assert 'id="gf-finish"' in HTML
|
||||
assert 'id="gf-cancel"' in HTML
|
||||
assert 'id="gf-inbox"' in HTML
|
||||
|
||||
|
||||
def test_layer_rail_collapsed_on_load():
|
||||
head = HTML.split('class="lp-head"', 1)[1].split("</div>", 1)[0]
|
||||
assert 'aria-expanded="false"' in head
|
||||
assert 'id="layer-panel" class="collapsed"' in HTML
|
||||
|
||||
|
||||
def test_market_ticker_hidden_no_poll():
|
||||
mkt = HTML.split('class="ticker market"', 1)[1].split(">", 1)[0]
|
||||
assert "hidden" in mkt
|
||||
assert "setInterval(probeMarket" not in HTML
|
||||
assert "setInterval(loadMarket" not in HTML
|
||||
init = HTML.split("function initMarketTicker", 1)[1].split("function ", 1)[0]
|
||||
assert "/api/market" in init or "404-poll" in init
|
||||
assert "setInterval" not in init
|
||||
|
||||
|
||||
def test_news_ticker_fills_news_only_dock():
|
||||
css = HTML.split("</style>", 1)[0]
|
||||
compact = css.replace(" ", "").replace("\n", "")
|
||||
assert ".dock.news-only{height:32px;}" in compact
|
||||
assert ".dock.news-only.ticker{height:100%;}" in compact
|
||||
assert ".ticker{display:flex;align-items:stretch;height:50%;" in compact
|
||||
|
||||
|
||||
def test_news_pins_are_circle_markers():
|
||||
js = HTML.split("async function loadNewsPins", 1)[1].split("function refreshLiveOverlays", 1)[0]
|
||||
assert "L.circleMarker" in js
|
||||
assert "fillOpacity: 0.7" in js or "fillOpacity:0.7" in js
|
||||
assert "rotate(45deg)" not in js
|
||||
assert "L.divIcon" not in js
|
||||
|
||||
|
||||
def test_chokepoint_buttons_not_in_toolbar_flow():
|
||||
assert 'id="chokepoint-select"' in HTML
|
||||
css = HTML.split("</style>", 1)[0]
|
||||
assert ".chokepoint-btns { display: none; }" in css or ".chokepoint-btns{display:none" in css.replace(
|
||||
" ", ""
|
||||
)
|
||||
|
||||
|
||||
def test_brand_is_osint_slash():
|
||||
assert "GLOBAL SITUATIONAL AWARENESS TERMINAL" not in HTML
|
||||
assert "OSINT" in HTML
|
||||
assert 'class="accent">//</span>' in HTML
|
||||
|
|
@ -1,90 +0,0 @@
|
|||
"""HUD: layer-rail stats, shortcuts, terminator, zoom-gated cams, SWPC chip."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
HTML = (ROOT / "app/static/index.html").read_text()
|
||||
|
||||
|
||||
def _fn(name: str, nxt: str | None = None) -> str:
|
||||
start = HTML.index(f"function {name}")
|
||||
if nxt:
|
||||
return HTML[start : HTML.index(f"function {nxt}", start + 1)]
|
||||
return HTML[start : start + 4000]
|
||||
|
||||
|
||||
def test_stats_poll_uses_api_then_falls_back():
|
||||
assert "/api/stats" in HTML
|
||||
assert "30000" in HTML.split("pollLayerStats")[1][:2500] or "STATS_POLL_MS" in HTML
|
||||
poll = HTML.split("async function pollLayerStats")[1].split("async function ")[0]
|
||||
assert "404" in poll
|
||||
assert "catch" in poll
|
||||
ids = HTML.split("STATS_COUNT_IDS")[1].split("};")[0]
|
||||
assert "aircraft" in ids and "cameras" in ids and "fires" in ids and "vessels" in ids
|
||||
# Overlay loaders still write array lengths when stats is down.
|
||||
assert "setLayerCount('lp-fires-count'" in HTML or 'setLayerCount("lp-fires-count"' in HTML
|
||||
assert "setLayerCount('lp-cams-count'" in HTML or 'setLayerCount("lp-cams-count"' in HTML
|
||||
assert "setLayerCount('lp-ac-count'" in HTML or 'setLayerCount("lp-ac-count"' in HTML
|
||||
assert "setLayerCount('lp-vessels-count'" in HTML or 'setLayerCount("lp-vessels-count"' in HTML
|
||||
|
||||
|
||||
def test_keyboard_shortcuts_do_not_steal_osiris_fs():
|
||||
keys = HTML.split("function initHudKeys")[1].split("function ")[0]
|
||||
assert "Escape" in keys
|
||||
assert "cheat-sheet" in keys or "toggleCheatSheet" in keys
|
||||
assert "mapResetView" in keys
|
||||
assert "toggleLayerPanel" in keys or "closeLayerPanel" in keys
|
||||
# Do not bind Osiris's conflicting F/S (flights vs fullscreen / search).
|
||||
assert "e.key === 'f'" not in keys.lower()
|
||||
assert "e.key === 's'" not in keys.lower()
|
||||
assert "case 'f'" not in keys.lower()
|
||||
assert "case 's'" not in keys.lower()
|
||||
assert 'id="cheat-sheet"' in HTML
|
||||
assert "?" in keys or "Shift" in keys
|
||||
|
||||
|
||||
def test_terminator_toggle_defaults_off():
|
||||
assert 'id="lp-terminator-on"' in HTML
|
||||
row = HTML.split('id="lp-terminator-on"')[0][-120:] + HTML.split('id="lp-terminator-on"')[1][:80]
|
||||
assert "checked" not in row.split(">")[0]
|
||||
assert "function toggleTerminator" in HTML
|
||||
assert "subsolarPoint" in HTML or "terminator" in HTML.lower()
|
||||
|
||||
|
||||
def test_camera_thumbs_gated_at_zoom_12():
|
||||
assert "CAM_THUMB_MIN_ZOOM" in HTML
|
||||
assert "CAM_THUMB_MIN_ZOOM = 12" in HTML
|
||||
thumb = _fn("camThumb", "camPopupHtml")
|
||||
assert "camThumbsAllowed" in thumb or "CAM_THUMB_MIN_ZOOM" in thumb
|
||||
assert "zoom in for preview" in HTML or "zoom for preview" in HTML
|
||||
assert "preview unavailable" in HTML
|
||||
# RTSP still proxy through snapshot; never emit rtsp hrefs.
|
||||
src = _fn("camSourceLink", "youtubeId")
|
||||
assert "rtsp://" in src
|
||||
assert "href=" not in src.split("rtsp://")[1].split("return")[0] or "Never emit" in src
|
||||
assert 'href="${esc(url)}"' in src or "href=\"${esc(url)}\"" in src
|
||||
assert src.index("rtsp://") < src.index("href=")
|
||||
|
||||
|
||||
def test_swpc_chip_browser_direct_correct_urls():
|
||||
assert 'id="swpc-chip"' in HTML
|
||||
assert "services.swpc.noaa.gov/json/planetary_k_index_1m.json" in HTML
|
||||
assert "services.swpc.noaa.gov/json/goes/primary/xray-flares-latest.json" in HTML
|
||||
assert "services.swpc.noaa.gov/products/alerts.json" in HTML
|
||||
assert "services.swpc.noaa.gov/json/alerts.json" not in HTML
|
||||
sw = HTML.split("async function pollSwpc")[1].split("async function ")[0]
|
||||
assert "hidden" in sw
|
||||
assert "kp_index" in sw
|
||||
assert "90000" in HTML or "SWPC_POLL_MS" in HTML
|
||||
|
||||
|
||||
def test_new_chrome_does_not_cover_mobile_layers_zoom():
|
||||
mobile = HTML.split("@media (max-width: 820px)")[1].split("@media (prefers-reduced-motion")[0]
|
||||
assert "#layer-panel" in mobile
|
||||
assert ".leaflet-top.leaflet-right .leaflet-control-zoom" in mobile
|
||||
assert 'id="cheat-sheet"' in HTML
|
||||
cheat = HTML.split(".cheat-sheet")[1][:500]
|
||||
assert "z-index" in cheat
|
||||
assert "calc(100% - 96px)" in cheat or "96px" in cheat
|
||||
|
|
@ -1,145 +0,0 @@
|
|||
"""GET /api/infrastructure — Overpass nuclear markers."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import httpx
|
||||
|
||||
from live_layers import (
|
||||
normalize_infra_element,
|
||||
overlay_catalog,
|
||||
overpass_nuclear_to_markers,
|
||||
_cache,
|
||||
)
|
||||
from main import app
|
||||
|
||||
BASE = "http://test"
|
||||
|
||||
OVERPASS = {
|
||||
"version": 0.6,
|
||||
"generator": "Overpass API",
|
||||
"elements": [
|
||||
{
|
||||
"type": "node",
|
||||
"id": 12345,
|
||||
"lat": 44.0,
|
||||
"lon": -1.5,
|
||||
"tags": {"name": "Test NPP", "operator": "EDF", "plant:source": "nuclear"},
|
||||
},
|
||||
{
|
||||
"type": "way",
|
||||
"id": 67890,
|
||||
"center": {"lat": 43.5, "lon": -1.25},
|
||||
"tags": {"name": "Test Plant Way", "plant:source": "nuclear"},
|
||||
},
|
||||
{
|
||||
"type": "relation",
|
||||
"id": 999,
|
||||
"center": {"lat": 43.0, "lon": -1.0},
|
||||
"tags": {},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
async def _get(path: str) -> httpx.Response:
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||||
return await client.get(path)
|
||||
|
||||
|
||||
def test_normalize_node_to_marker():
|
||||
m = normalize_infra_element(OVERPASS["elements"][0], "nuclear")
|
||||
assert m["id"] == "node/12345"
|
||||
assert m["name"] == "Test NPP"
|
||||
assert m["lat"] == 44.0
|
||||
assert m["lon"] == -1.5
|
||||
assert m["type"] == "nuclear"
|
||||
assert m["extra"]["operator"] == "EDF"
|
||||
assert "name" not in m["extra"]
|
||||
|
||||
|
||||
def test_way_center_and_unnamed_fallback():
|
||||
way = normalize_infra_element(OVERPASS["elements"][1], "nuclear")
|
||||
assert way["lat"] == 43.5
|
||||
assert way["lon"] == -1.25
|
||||
rel = normalize_infra_element(OVERPASS["elements"][2], "nuclear")
|
||||
assert rel["name"] == "relation/999"
|
||||
|
||||
|
||||
def test_overpass_json_to_markers():
|
||||
markers = overpass_nuclear_to_markers(OVERPASS)
|
||||
assert len(markers) == 3
|
||||
assert markers[0]["id"] == "node/12345"
|
||||
|
||||
|
||||
def test_missing_bbox_400():
|
||||
resp = asyncio.run(_get("/api/infrastructure?types=nuclear"))
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_unknown_type_422():
|
||||
resp = asyncio.run(_get("/api/infrastructure?types=military&bbox=-2,43,-1,44"))
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_map_infrastructure_returns_markers(monkeypatch):
|
||||
async def fake_fetch(types, bbox):
|
||||
return [
|
||||
{"id": "node/1", "name": "X", "lat": 1.0, "lon": 2.0,
|
||||
"type": "nuclear", "extra": {}}
|
||||
]
|
||||
|
||||
monkeypatch.setattr("main.fetch_infrastructure", fake_fetch)
|
||||
resp = asyncio.run(_get("/api/infrastructure?types=nuclear&bbox=-2,43,-1,44"))
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body[0]["name"] == "X"
|
||||
assert body[0]["type"] == "nuclear"
|
||||
assert "max-age" in (resp.headers.get("cache-control") or "").lower()
|
||||
|
||||
|
||||
def test_overlay_catalog_has_infra_nuclear():
|
||||
entry = overlay_catalog()["infra_nuclear"]
|
||||
assert entry["kind"] == "points"
|
||||
assert "nuclear" in entry["endpoint"]
|
||||
|
||||
|
||||
def test_fetch_infrastructure_cache_hit_no_refetch(monkeypatch):
|
||||
_cache.clear()
|
||||
hits = {"n": 0}
|
||||
|
||||
class FakeResp:
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
|
||||
def json(self):
|
||||
return OVERPASS
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, **kw):
|
||||
pass
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *exc):
|
||||
return False
|
||||
|
||||
async def post(self, url, data=None, timeout=None):
|
||||
hits["n"] += 1
|
||||
assert "overpass-api.de" in url
|
||||
assert "plant:source" in data["data"]
|
||||
assert "nuclear" in data["data"]
|
||||
return FakeResp()
|
||||
|
||||
monkeypatch.setattr("live_layers.httpx.AsyncClient", FakeClient)
|
||||
monkeypatch.setattr("live_layers._http", None)
|
||||
|
||||
from live_layers import fetch_infrastructure
|
||||
|
||||
m1 = asyncio.run(fetch_infrastructure("nuclear", "-2,43,-1,44"))
|
||||
m2 = asyncio.run(fetch_infrastructure("nuclear", "-2,43,-1,44"))
|
||||
assert len(m1) == 3
|
||||
assert m2 == m1
|
||||
assert hits["n"] == 1
|
||||
_cache.clear()
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue