Compare commits
77 changed files with 1184 additions and 48526 deletions
48
.env.example
48
.env.example
|
|
@ -31,6 +31,20 @@ NOMINATIM_URL=https://nominatim.openstreetmap.org
|
||||||
NOMINATIM_MIN_INTERVAL=1.1
|
NOMINATIM_MIN_INTERVAL=1.1
|
||||||
SNAPSHOT_TTL_SECONDS=300
|
SNAPSHOT_TTL_SECONDS=300
|
||||||
|
|
||||||
|
# ── masscan active camera discovery (host-level systemd service, NOT compose) ─
|
||||||
|
# Continuous rolling sweep for open RTSP port 554 across a range. Runs on the
|
||||||
|
# Pi host via deploy/osint-masscan.service (needs root + raw sockets). Results
|
||||||
|
# land in the same `cameras` table as the scraper (discovery_source=masscan).
|
||||||
|
# NOTE: 200 pps is the residential-safe default. 1k/10k pps saturated a home
|
||||||
|
# uplink. A full 0.0.0.0/0 sweep at 200 pps takes ~8 months (rolling).
|
||||||
|
MASSCAN_RANGE=0.0.0.0/0
|
||||||
|
MASSCAN_PORTS=554
|
||||||
|
MASSCAN_RATE=200
|
||||||
|
MASSCAN_RETRIES=1
|
||||||
|
MASSCAN_WAIT=0
|
||||||
|
MASSCAN_EXCLUDEFILE=/etc/osint-dashboard/masscan-excludes.txt
|
||||||
|
MASSCAN_FLUSH_EVERY=250
|
||||||
|
|
||||||
# ── NASA FIRMS (active fire / hotspot ingest) ──────────────────────────────
|
# ── NASA FIRMS (active fire / hotspot ingest) ──────────────────────────────
|
||||||
# MAP_KEY is FREE — get one at https://firms.modaps.eosdis.nasa.gov/api/map_key_info/
|
# MAP_KEY is FREE — get one at https://firms.modaps.eosdis.nasa.gov/api/map_key_info/
|
||||||
# (1-minute signup, no payment). Leave blank to keep fire ingest idle.
|
# (1-minute signup, no payment). Leave blank to keep fire ingest idle.
|
||||||
|
|
@ -69,21 +83,6 @@ VESSELAPI_IN_INGEST=0
|
||||||
# (GET/POST/DELETE /api/keys/{name}) — see app/keystore.py. The FIRMS ingestor
|
# (GET/POST/DELETE /api/keys/{name}) — see app/keystore.py. The FIRMS ingestor
|
||||||
# currently reads FIRMS_MAP_KEY from .env (above); wiring the Keys-UI store as
|
# currently reads FIRMS_MAP_KEY from .env (above); wiring the Keys-UI store as
|
||||||
# its lookup/fallback is a planned follow-up.
|
# its lookup/fallback is a planned follow-up.
|
||||||
#
|
|
||||||
# Key management is ADMIN-ONLY (single admin, no user table). Visitors get a
|
|
||||||
# read-only map + news. Configure the three vars below or admin endpoints
|
|
||||||
# answer 403 {"detail": "admin auth not configured"} (fail closed — the public
|
|
||||||
# site keeps working). In the cluster they come from Secret `osint-admin`.
|
|
||||||
# Generate the hash: python app/auth.py hash 'your password'
|
|
||||||
# Generate the secret: python -c 'import secrets; print(secrets.token_urlsafe(48))'
|
|
||||||
ADMIN_USER=
|
|
||||||
ADMIN_PASSWORD_HASH=
|
|
||||||
ADMIN_SESSION_SECRET=
|
|
||||||
# Optional: force the session cookie's Secure flag (1/true/yes) when the app is
|
|
||||||
# reached over plain HTTP behind a TLS-terminating proxy that rewrites
|
|
||||||
# X-Forwarded-Proto to http (the cluster: Cloudflare tunnel -> Cilium Gateway).
|
|
||||||
# Leave unset locally so the cookie works over http://localhost.
|
|
||||||
ADMIN_COOKIE_SECURE=
|
|
||||||
|
|
||||||
# ── News pipeline (scraper + summarizer, profile `ingest`) ────────────────
|
# ── News pipeline (scraper + summarizer, profile `ingest`) ────────────────
|
||||||
# Scraper crawls urls.txt continuously (default 10s between crawls).
|
# Scraper crawls urls.txt continuously (default 10s between crawls).
|
||||||
|
|
@ -98,25 +97,6 @@ NOUS_BASE_URL=https://inference-api.nousresearch.com/v1
|
||||||
# Hermes-4.3-36B remains after a Postgres miss. Env wins when set.
|
# Hermes-4.3-36B remains after a Postgres miss. Env wins when set.
|
||||||
# SUMMARY_MODEL=
|
# SUMMARY_MODEL=
|
||||||
NEWS_BATCH_SIZE=50
|
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
|
SUMMARY_WINDOW_MINUTES=15
|
||||||
# Futures/markets coupling from the upstream pipeline is OFF by default
|
# Futures/markets coupling from the upstream pipeline is OFF by default
|
||||||
# (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable.
|
# (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable.
|
||||||
|
|
|
||||||
|
|
@ -1,28 +1,21 @@
|
||||||
# Build changed OSINT images and publish them to the Forgejo container
|
# Build changed OSINT images, publish to the Forgejo container registry, then
|
||||||
# registry. Deployment is NOT done here: the cluster (homek8s, namespace
|
# redeploy on the Pi runner (docker.sock mounted).
|
||||||
# `osint`) runs amd64 images pinned by tag in apps/base/osint/*.yaml, so the
|
|
||||||
# final step prints the tag to pin and a human opens that manifest PR.
|
|
||||||
#
|
#
|
||||||
# Unchanged images are skipped. Dockerfile.pg / osint-dashboard-pg is NOT
|
# Unchanged images are skipped. Dockerfile.pg / osint-dashboard-pg is NOT
|
||||||
# rebuilt on a normal merge — Postgres stays up. Rebuild it only when
|
# rebuilt or pulled on a normal merge — Postgres stays up. Rebuild it only
|
||||||
# Dockerfile.pg changes, or via workflow_dispatch rebuild_pg.
|
# when Dockerfile.pg changes, or via workflow_dispatch rebuild_pg.
|
||||||
#
|
|
||||||
# Registry endpoints
|
|
||||||
# CI push host: forgejo.forgejo.svc.cluster.local:3000 — plain HTTP
|
|
||||||
# ClusterIP, whitelisted by --insecure-registry on the amd64
|
|
||||||
# runner's dind daemon. 127.0.0.1:3000 stopped working when
|
|
||||||
# Forgejo moved into k8s: inside an in-cluster job pod, loopback
|
|
||||||
# is the pod itself, so login died with "connection refused".
|
|
||||||
# Public pull: forgejo.siriusdevops.com (HTTPS via Cloudflare; kubelet pulls
|
|
||||||
# from here). Do NOT push here — Cloudflare 413s layers ≳100MB.
|
|
||||||
#
|
#
|
||||||
|
# Public pull host: forgejo.siriusdevops.com (NOT ghcr.io)
|
||||||
|
# CI push host: 127.0.0.1:3000 — Cloudflare 413s layers ≳100MB on the public
|
||||||
|
# hostname, even from the Pi (hairpins out through the tunnel).
|
||||||
# Images (public names):
|
# Images (public names):
|
||||||
# forgejo.siriusdevops.com/sirius/osint-dashboard:amd64-<sha12>
|
# forgejo.siriusdevops.com/sirius/osint-dashboard
|
||||||
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg:amd64-<sha12>
|
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg
|
||||||
# forgejo.siriusdevops.com/sirius/osint-news-scraper:amd64-<sha12>
|
# forgejo.siriusdevops.com/sirius/osint-news-scraper
|
||||||
# forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64-<sha12>
|
# forgejo.siriusdevops.com/sirius/osint-news-summarizer
|
||||||
#
|
#
|
||||||
# Optional repo variable FORGEJO_REGISTRY overrides the *public* pull host.
|
# Optional repo variable FORGEJO_REGISTRY overrides the *public* pull host.
|
||||||
|
# Deploy still uses the local docker socket on the runner host (rpi).
|
||||||
|
|
||||||
name: build-and-deploy
|
name: build-and-deploy
|
||||||
|
|
||||||
|
|
@ -42,19 +35,17 @@ on:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }}
|
PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }}
|
||||||
PUSH_REGISTRY: forgejo.forgejo.svc.cluster.local:3000
|
PUSH_REGISTRY: 127.0.0.1:3000
|
||||||
OWNER: sirius
|
OWNER: sirius
|
||||||
|
# Keep compose project/volumes stable on the Pi
|
||||||
|
COMPOSE_PROJECT_NAME: osint-dashboard
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build-push:
|
build-push-deploy:
|
||||||
# `amd64` only exists on siriussec-amd64, which is also the node the
|
runs-on: docker
|
||||||
# workloads run on — so the images are built on the architecture they are
|
permissions:
|
||||||
# pulled to. `runs-on: docker` matched the Pi's arm64 runner, which
|
contents: read
|
||||||
# produced images the amd64 cluster could never run.
|
packages: write
|
||||||
# No job-level `permissions:` block: Forgejo ignores it (it emits a
|
|
||||||
# pre-execution warning) and the push authenticates with the FORGEJO_TOKEN
|
|
||||||
# user PAT instead, because the package registry rejects the Actions token.
|
|
||||||
runs-on: amd64
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: https://code.forgejo.org/actions/checkout@v4
|
uses: https://code.forgejo.org/actions/checkout@v4
|
||||||
|
|
@ -69,6 +60,7 @@ jobs:
|
||||||
SCRAPER=0
|
SCRAPER=0
|
||||||
SUM=0
|
SUM=0
|
||||||
PG=0
|
PG=0
|
||||||
|
COMPOSE=0
|
||||||
|
|
||||||
mark() {
|
mark() {
|
||||||
case "$1" in
|
case "$1" in
|
||||||
|
|
@ -80,6 +72,8 @@ jobs:
|
||||||
SCRAPER=1 ;;
|
SCRAPER=1 ;;
|
||||||
news/summerizer/*)
|
news/summerizer/*)
|
||||||
SUM=1 ;;
|
SUM=1 ;;
|
||||||
|
docker-compose.yml|scripts/compose-reup.sh)
|
||||||
|
COMPOSE=1 ;;
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -114,8 +108,9 @@ jobs:
|
||||||
echo "scraper=$SCRAPER"
|
echo "scraper=$SCRAPER"
|
||||||
echo "summarizer=$SUM"
|
echo "summarizer=$SUM"
|
||||||
echo "pg=$PG"
|
echo "pg=$PG"
|
||||||
|
echo "compose=$COMPOSE"
|
||||||
} >> "$GITHUB_OUTPUT"
|
} >> "$GITHUB_OUTPUT"
|
||||||
echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG"
|
echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG compose=$COMPOSE"
|
||||||
|
|
||||||
- name: Image refs
|
- name: Image refs
|
||||||
id: img
|
id: img
|
||||||
|
|
@ -125,11 +120,10 @@ jobs:
|
||||||
PUB="${PUBLIC_REGISTRY}"
|
PUB="${PUBLIC_REGISTRY}"
|
||||||
OWN="${OWNER}"
|
OWN="${OWNER}"
|
||||||
SHA="${GITHUB_SHA::12}"
|
SHA="${GITHUB_SHA::12}"
|
||||||
TAG="amd64-${SHA}"
|
|
||||||
{
|
{
|
||||||
echo "reg=$PUSH"
|
echo "reg=$PUSH"
|
||||||
echo "pub=$PUB"
|
echo "pub=$PUB"
|
||||||
echo "tag=$TAG"
|
echo "sha=$SHA"
|
||||||
echo "app=$PUSH/$OWN/osint-dashboard"
|
echo "app=$PUSH/$OWN/osint-dashboard"
|
||||||
echo "pg=$PUSH/$OWN/osint-dashboard-pg"
|
echo "pg=$PUSH/$OWN/osint-dashboard-pg"
|
||||||
echo "scraper=$PUSH/$OWN/osint-news-scraper"
|
echo "scraper=$PUSH/$OWN/osint-news-scraper"
|
||||||
|
|
@ -137,69 +131,113 @@ jobs:
|
||||||
} >> "$GITHUB_OUTPUT"
|
} >> "$GITHUB_OUTPUT"
|
||||||
echo "Push registry: $PUSH"
|
echo "Push registry: $PUSH"
|
||||||
echo "Public pull: $PUB"
|
echo "Public pull: $PUB"
|
||||||
echo "Image tag: $TAG"
|
echo "SHA tag: $SHA"
|
||||||
|
|
||||||
- name: Login to Forgejo registry
|
- name: Login to Forgejo registry
|
||||||
if: steps.plan.outputs.app == '1' || steps.plan.outputs.scraper == '1' || steps.plan.outputs.summarizer == '1' || steps.plan.outputs.pg == '1'
|
if: steps.plan.outputs.app == '1' || steps.plan.outputs.scraper == '1' || steps.plan.outputs.summarizer == '1' || steps.plan.outputs.pg == '1'
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
# GITHUB_TOKEN login "succeeds" but blob uploads 401 (Forgejo packages
|
# GITHUB_TOKEN login "succeeds" but blob uploads 401 (Forgejo packages
|
||||||
# reject the Actions token). Use a user PAT.
|
# reject the Actions token). Use a user PAT with write:package.
|
||||||
# The PAT must carry the `write:package` scope: Forgejo mints a push
|
if [ -z "${{ secrets.FORGEJO_TOKEN }}" ]; then
|
||||||
# token even without it and then rejects every blob upload with
|
echo "Missing repo secret FORGEJO_TOKEN (user PAT, not GITHUB_TOKEN)"
|
||||||
# `unauthorized: reqPackageAccess` (routers/api/packages/api.go
|
|
||||||
# reqPackageAccess -> AccessTokenScopeWritePackage).
|
|
||||||
# Name is REGISTRY_TOKEN, not FORGEJO_TOKEN: Forgejo reserves the
|
|
||||||
# FORGEJO_/GITHUB_ prefixes and refuses to create or update them via
|
|
||||||
# the API.
|
|
||||||
if [ -z "${{ secrets.REGISTRY_TOKEN }}" ]; then
|
|
||||||
echo "Missing repo secret REGISTRY_TOKEN (user PAT with write:package, not GITHUB_TOKEN)"
|
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "${{ secrets.REGISTRY_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \
|
echo "${{ secrets.FORGEJO_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \
|
||||||
-u sirius --password-stdin
|
-u sirius --password-stdin
|
||||||
|
|
||||||
- name: Build application image (api / ingester / cameras)
|
- name: Build application image (api / ingester / cameras)
|
||||||
if: steps.plan.outputs.app == '1'
|
if: steps.plan.outputs.app == '1'
|
||||||
run: |
|
run: |
|
||||||
set -ex
|
set -ex
|
||||||
IMG="${{ steps.img.outputs.app }}"
|
APP="${{ steps.img.outputs.app }}"
|
||||||
TAG="${{ steps.img.outputs.tag }}"
|
SHA="${{ steps.img.outputs.sha }}"
|
||||||
docker build -f Dockerfile -t "${IMG}:${TAG}" .
|
docker build -f Dockerfile -t "${APP}:latest" -t "${APP}:${SHA}" \
|
||||||
docker push "${IMG}:${TAG}"
|
-t "localhost/osint-dashboard:latest" .
|
||||||
|
docker push "${APP}:latest"
|
||||||
|
docker push "${APP}:${SHA}"
|
||||||
|
|
||||||
- name: Build news-scraper image
|
- name: Build news-scraper image
|
||||||
if: steps.plan.outputs.scraper == '1'
|
if: steps.plan.outputs.scraper == '1'
|
||||||
run: |
|
run: |
|
||||||
set -ex
|
set -ex
|
||||||
IMG="${{ steps.img.outputs.scraper }}"
|
IMG="${{ steps.img.outputs.scraper }}"
|
||||||
TAG="${{ steps.img.outputs.tag }}"
|
SHA="${{ steps.img.outputs.sha }}"
|
||||||
docker build -f news/scraper/Dockerfile -t "${IMG}:${TAG}" news/scraper
|
docker build -f news/scraper/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \
|
||||||
docker push "${IMG}:${TAG}"
|
-t "localhost/osint-news-scraper:latest" news/scraper
|
||||||
|
docker push "${IMG}:latest"
|
||||||
|
docker push "${IMG}:${SHA}"
|
||||||
|
|
||||||
- name: Build news-summarizer image
|
- name: Build news-summarizer image
|
||||||
if: steps.plan.outputs.summarizer == '1'
|
if: steps.plan.outputs.summarizer == '1'
|
||||||
run: |
|
run: |
|
||||||
set -ex
|
set -ex
|
||||||
IMG="${{ steps.img.outputs.summarizer }}"
|
IMG="${{ steps.img.outputs.summarizer }}"
|
||||||
TAG="${{ steps.img.outputs.tag }}"
|
SHA="${{ steps.img.outputs.sha }}"
|
||||||
docker build -f news/summerizer/Dockerfile -t "${IMG}:${TAG}" news/summerizer
|
docker build -f news/summerizer/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \
|
||||||
docker push "${IMG}:${TAG}"
|
-t "localhost/osint-news-summarizer:latest" news/summerizer
|
||||||
|
docker push "${IMG}:latest"
|
||||||
|
docker push "${IMG}:${SHA}"
|
||||||
|
|
||||||
- name: Build / refresh Timescale+PostGIS image
|
- name: Build / refresh Timescale+PostGIS image
|
||||||
if: steps.plan.outputs.pg == '1'
|
if: steps.plan.outputs.pg == '1'
|
||||||
run: |
|
run: |
|
||||||
set -ex
|
set -ex
|
||||||
IMG="${{ steps.img.outputs.pg }}"
|
PG="${{ steps.img.outputs.pg }}"
|
||||||
TAG="${{ steps.img.outputs.tag }}"
|
SHA="${{ steps.img.outputs.sha }}"
|
||||||
docker build -f Dockerfile.pg -t "${IMG}:${TAG}" .
|
if docker build -f Dockerfile.pg -t "${PG}:latest" -t "${PG}:${SHA}" \
|
||||||
docker push "${IMG}:${TAG}"
|
-t "localhost/osint-dashboard-pg:latest" .; then
|
||||||
|
docker push "${PG}:latest"
|
||||||
|
docker push "${PG}:${SHA}"
|
||||||
|
elif docker image inspect "localhost/osint-dashboard-pg:latest" >/dev/null 2>&1; then
|
||||||
|
echo "WARN: Dockerfile.pg build failed; keeping existing local pg image"
|
||||||
|
else
|
||||||
|
echo "ERROR: cannot build or find osint-dashboard-pg image"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Deploy on runner host (compose)
|
||||||
|
run: |
|
||||||
|
set -ex
|
||||||
|
cd "${GITHUB_WORKSPACE}"
|
||||||
|
APP="${{ steps.plan.outputs.app }}"
|
||||||
|
SCRAPER="${{ steps.plan.outputs.scraper }}"
|
||||||
|
SUM="${{ steps.plan.outputs.summarizer }}"
|
||||||
|
PG="${{ steps.plan.outputs.pg }}"
|
||||||
|
COMPOSE="${{ steps.plan.outputs.compose }}"
|
||||||
|
|
||||||
|
SVCS=()
|
||||||
|
[ "$APP" = "1" ] && SVCS+=(app ingester camera-service)
|
||||||
|
[ "$SCRAPER" = "1" ] && SVCS+=(news-scraper)
|
||||||
|
[ "$SUM" = "1" ] && SVCS+=(news-summarizer)
|
||||||
|
if [ "$COMPOSE" = "1" ]; then
|
||||||
|
# compose/script change: bounce workers so env/command updates apply.
|
||||||
|
# Still do not bounce Postgres.
|
||||||
|
for s in app ingester camera-service news-scraper news-summarizer; do
|
||||||
|
case " ${SVCS[*]} " in
|
||||||
|
*" $s "*) ;;
|
||||||
|
*) SVCS+=("$s") ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
chmod +x scripts/compose-reup.sh
|
||||||
|
if [ "$PG" = "1" ]; then
|
||||||
|
FORCE_RECREATE_DB=1 COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \
|
||||||
|
scripts/compose-reup.sh "${SVCS[@]}" db
|
||||||
|
elif [ "${#SVCS[@]}" -gt 0 ]; then
|
||||||
|
COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \
|
||||||
|
scripts/compose-reup.sh "${SVCS[@]}"
|
||||||
|
else
|
||||||
|
echo "No image or compose changes — leave running containers alone"
|
||||||
|
docker compose --profile ingest ps
|
||||||
|
fi
|
||||||
|
docker image prune -f
|
||||||
|
echo "osint-dashboard deploy done; db image left in place unless pg=1"
|
||||||
|
|
||||||
- name: Summary
|
- name: Summary
|
||||||
if: always()
|
if: always()
|
||||||
run: |
|
run: |
|
||||||
TAG="${{ steps.img.outputs.tag }}"
|
|
||||||
PUB="${{ steps.img.outputs.pub }}"
|
|
||||||
{
|
{
|
||||||
echo "## Image plan"
|
echo "## Image plan"
|
||||||
echo "- app: \`${{ steps.plan.outputs.app }}\`"
|
echo "- app: \`${{ steps.plan.outputs.app }}\`"
|
||||||
|
|
@ -207,23 +245,5 @@ jobs:
|
||||||
echo "- news-summarizer: \`${{ steps.plan.outputs.summarizer }}\`"
|
echo "- news-summarizer: \`${{ steps.plan.outputs.summarizer }}\`"
|
||||||
echo "- pg (Timescale): \`${{ steps.plan.outputs.pg }}\`"
|
echo "- pg (Timescale): \`${{ steps.plan.outputs.pg }}\`"
|
||||||
echo
|
echo
|
||||||
if [ -n "$TAG" ]; then
|
echo "Postgres is rebuilt/pulled only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)."
|
||||||
echo "## Pin in homek8s (apps/base/osint)"
|
|
||||||
echo "Pushed tag: \`${TAG}\`. Set the workload images in"
|
|
||||||
echo "\`apps/base/osint/kustomization.yaml\` to:"
|
|
||||||
echo
|
|
||||||
echo '```yaml'
|
|
||||||
echo "images:"
|
|
||||||
echo " - name: ${PUB}/${OWNER}/osint-dashboard"
|
|
||||||
echo " newTag: ${TAG}"
|
|
||||||
echo " - name: ${PUB}/${OWNER}/osint-news-scraper"
|
|
||||||
echo " newTag: ${TAG}"
|
|
||||||
echo " - name: ${PUB}/${OWNER}/osint-news-summarizer"
|
|
||||||
echo " newTag: ${TAG}"
|
|
||||||
echo '```'
|
|
||||||
else
|
|
||||||
echo "_No tag computed — the earlier steps failed before Image refs._"
|
|
||||||
fi
|
|
||||||
echo
|
|
||||||
echo "Postgres is rebuilt only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)."
|
|
||||||
} >> "$GITHUB_STEP_SUMMARY"
|
} >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
|
||||||
|
|
@ -1,29 +0,0 @@
|
||||||
"""GIST bbox indexes for events/fires map-pan queries.
|
|
||||||
|
|
||||||
Revision ID: 010_bbox_gist
|
|
||||||
Revises: 009_vessels
|
|
||||||
Create Date: 2026-09-01
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
revision = "010_bbox_gist"
|
|
||||||
down_revision = "009_vessels"
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
op.execute(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_events_geom_gist ON events "
|
|
||||||
"USING gist (ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326))"
|
|
||||||
)
|
|
||||||
op.execute(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_fires_geom_gist ON fires "
|
|
||||||
"USING gist (ST_SetSRID(ST_MakePoint(longitude, latitude), 4326))"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.execute("DROP INDEX IF EXISTS ix_fires_geom_gist")
|
|
||||||
op.execute("DROP INDEX IF EXISTS ix_events_geom_gist")
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
"""geofence_alerts (geofence_id, created_at DESC) for fence-scoped hit log
|
|
||||||
|
|
||||||
Revision ID: 011_geofence_alerts_fence
|
|
||||||
Revises: 010_bbox_gist
|
|
||||||
Create Date: 2026-09-01
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
revision = "011_geofence_alerts_fence"
|
|
||||||
down_revision = "010_bbox_gist"
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
op.execute(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_geofence_alerts_fence_created "
|
|
||||||
"ON geofence_alerts (geofence_id, created_at DESC)"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.execute("DROP INDEX IF EXISTS ix_geofence_alerts_fence_created")
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
"""article_scores: per-article map-phase grades for threshold tuning
|
|
||||||
|
|
||||||
Revision ID: 012_article_scores
|
|
||||||
Revises: 011_geofence_alerts_fence
|
|
||||||
Create Date: 2026-11-13
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
revision = "012_article_scores"
|
|
||||||
down_revision = "011_geofence_alerts_fence"
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
op.execute(
|
|
||||||
"""
|
|
||||||
CREATE TABLE IF NOT EXISTS article_scores (
|
|
||||||
article_id INTEGER NOT NULL,
|
|
||||||
summary_id INTEGER,
|
|
||||||
score INTEGER NOT NULL,
|
|
||||||
category TEXT,
|
|
||||||
selected BOOLEAN NOT NULL,
|
|
||||||
model TEXT,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
||||||
PRIMARY KEY (article_id, created_at)
|
|
||||||
)
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
op.execute(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_article_scores_summary "
|
|
||||||
"ON article_scores (summary_id)"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.execute("DROP INDEX IF EXISTS ix_article_scores_summary")
|
|
||||||
op.execute("DROP TABLE IF EXISTS article_scores")
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
"""article_scores.duplicate_of: link a syndicated copy to its representative
|
|
||||||
|
|
||||||
Revision ID: 013_article_scores_duplicate_of
|
|
||||||
Revises: 012_article_scores
|
|
||||||
Create Date: 2026-11-13
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
revision = "013_article_scores_duplicate_of"
|
|
||||||
down_revision = "012_article_scores"
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
op.execute(
|
|
||||||
"ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS duplicate_of")
|
|
||||||
|
|
@ -1,40 +0,0 @@
|
||||||
"""article_scores geo: per-article proximate location for /api/news/blips
|
|
||||||
|
|
||||||
Revision ID: 014_article_scores_geo
|
|
||||||
Revises: 013_article_scores_duplicate_of
|
|
||||||
Create Date: 2026-11-19
|
|
||||||
|
|
||||||
Additive nullable columns on article_scores (every graded article keeps
|
|
||||||
its grading row; geo rides along when derivable). Partial bbox index for
|
|
||||||
the blips endpoint's bbox= filter. Idempotent DDL mirrors the summarizer's
|
|
||||||
ensure_tables so either start order is safe.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from alembic import op
|
|
||||||
|
|
||||||
revision = "014_article_scores_geo"
|
|
||||||
down_revision = "013_article_scores_duplicate_of"
|
|
||||||
branch_labels = None
|
|
||||||
depends_on = None
|
|
||||||
|
|
||||||
|
|
||||||
def upgrade() -> None:
|
|
||||||
op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_name TEXT")
|
|
||||||
op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lat DOUBLE PRECISION")
|
|
||||||
op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lon DOUBLE PRECISION")
|
|
||||||
op.execute(
|
|
||||||
"ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_confidence TEXT"
|
|
||||||
)
|
|
||||||
op.execute(
|
|
||||||
"CREATE INDEX IF NOT EXISTS ix_article_scores_geo_bbox "
|
|
||||||
"ON article_scores (lon, lat) "
|
|
||||||
"WHERE lat IS NOT NULL AND lon IS NOT NULL"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def downgrade() -> None:
|
|
||||||
op.execute("DROP INDEX IF EXISTS ix_article_scores_geo_bbox")
|
|
||||||
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS location_confidence")
|
|
||||||
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS lon")
|
|
||||||
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS lat")
|
|
||||||
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS location_name")
|
|
||||||
589
app/auth.py
589
app/auth.py
|
|
@ -1,589 +0,0 @@
|
||||||
"""Single-admin authentication for the OSINT dashboard.
|
|
||||||
|
|
||||||
The public site stays read-only for anonymous visitors; the one admin (the
|
|
||||||
operator) unlocks API-key management, settings and every state-changing route.
|
|
||||||
|
|
||||||
Design notes
|
|
||||||
------------
|
|
||||||
* **Deny by default.** :class:`AdminAuthMiddleware` inspects every ``/api/*``
|
|
||||||
request. Only the explicit read allowlist below is reachable without a
|
|
||||||
session; everything else needs a valid signed cookie. ``/api/auth/*`` is the
|
|
||||||
bootstrap surface and handles its own checks.
|
|
||||||
* **Fail closed.** With ``ADMIN_PASSWORD_HASH`` or ``ADMIN_SESSION_SECRET``
|
|
||||||
unset/empty, admin endpoints answer ``403 {"detail": "admin auth not
|
|
||||||
configured"}``. There is no default password and no bypass; public reads and
|
|
||||||
the HUD keep working.
|
|
||||||
* **No new dependencies.** Password hashing is stdlib ``hashlib.pbkdf2_hmac``
|
|
||||||
and the session token is an HMAC-SHA256 signature over a base64url JSON
|
|
||||||
payload. Cookies are HttpOnly, SameSite=Lax, Path=/, 7-day lifetime, and
|
|
||||||
``Secure`` when the request arrived over https (``X-Forwarded-Proto``) or
|
|
||||||
when ``ADMIN_COOKIE_SECURE`` is truthy (TLS-only deployments behind an
|
|
||||||
HTTP origin listener, where Envoy normalizes the header to ``http``).
|
|
||||||
* **CSRF.** State-changing admin requests that carry an ``Origin``/``Referer``
|
|
||||||
are rejected when the origin host differs from the request host. Requests
|
|
||||||
without either header (curl, server-to-server) are allowed — the signed,
|
|
||||||
SameSite=Lax session cookie is what authenticates them.
|
|
||||||
|
|
||||||
Environment (exact names, supplied by the ``osint-admin`` Secret):
|
|
||||||
|
|
||||||
``ADMIN_USER``
|
|
||||||
Admin username.
|
|
||||||
``ADMIN_PASSWORD_HASH``
|
|
||||||
``pbkdf2_sha256$<iterations>$<salt_b64>$<hash_b64>``. Generate with::
|
|
||||||
|
|
||||||
python app/auth.py hash 'your password'
|
|
||||||
|
|
||||||
``ADMIN_SESSION_SECRET``
|
|
||||||
HMAC key for session tokens. Generate with::
|
|
||||||
|
|
||||||
python -c 'import secrets; print(secrets.token_urlsafe(48))'
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import base64
|
|
||||||
import hashlib
|
|
||||||
import hmac
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import secrets
|
|
||||||
import time
|
|
||||||
from collections import deque
|
|
||||||
from urllib.parse import parse_qs, urlparse
|
|
||||||
|
|
||||||
from fastapi import APIRouter, Request
|
|
||||||
from fastapi.responses import HTMLResponse, JSONResponse
|
|
||||||
|
|
||||||
# ── Constants ────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
COOKIE_NAME = "osint_session"
|
|
||||||
SESSION_TTL_SECONDS = 7 * 24 * 60 * 60
|
|
||||||
PBKDF2_ALGORITHM = "pbkdf2_sha256"
|
|
||||||
PBKDF2_ITERATIONS = 260_000
|
|
||||||
_ITERATIONS_FLOOR, _ITERATIONS_CEIL = 1_000, 5_000_000
|
|
||||||
|
|
||||||
LOGIN_WINDOW_SECONDS = 15 * 60
|
|
||||||
LOGIN_MAX_FAILURES = 5
|
|
||||||
|
|
||||||
_STATE_CHANGING = frozenset({"POST", "PUT", "PATCH", "DELETE"})
|
|
||||||
|
|
||||||
# ── Public read allowlist ────────────────────────────────────────────────────
|
|
||||||
# Anonymous visitors get the map + news HUD. Every path here was audited as a
|
|
||||||
# pure read (no writes, no spend of a stored API key). Anything absent requires
|
|
||||||
# the admin session.
|
|
||||||
|
|
||||||
PUBLIC_GET_EXACT = frozenset({
|
|
||||||
# core
|
|
||||||
"/api/health",
|
|
||||||
"/api/ready",
|
|
||||||
"/api/stats",
|
|
||||||
# events / sources / entities / alerts / documents
|
|
||||||
"/api/sources",
|
|
||||||
"/api/events",
|
|
||||||
"/api/fires",
|
|
||||||
"/api/entities",
|
|
||||||
"/api/alerts",
|
|
||||||
"/api/documents",
|
|
||||||
# analytics
|
|
||||||
"/api/analytics/summary",
|
|
||||||
"/api/analytics/timeline",
|
|
||||||
"/api/analytics/sentiment/by-source",
|
|
||||||
# cameras
|
|
||||||
"/api/cameras",
|
|
||||||
# news
|
|
||||||
"/api/news",
|
|
||||||
"/api/news/summaries",
|
|
||||||
"/api/news/ticker",
|
|
||||||
"/api/news/map",
|
|
||||||
"/api/news/blips",
|
|
||||||
# map / live layers
|
|
||||||
"/api/map/layers",
|
|
||||||
"/api/map/chokepoints",
|
|
||||||
"/api/map/radar",
|
|
||||||
"/api/map/sentinel1",
|
|
||||||
"/api/map/gpsjam",
|
|
||||||
"/api/map/times",
|
|
||||||
"/api/conflicts",
|
|
||||||
"/api/aircraft",
|
|
||||||
"/api/aircraft/photo",
|
|
||||||
"/api/trains",
|
|
||||||
"/api/vessels",
|
|
||||||
"/api/tracks/range",
|
|
||||||
"/api/satellites",
|
|
||||||
"/api/infrastructure",
|
|
||||||
"/api/place",
|
|
||||||
# geofences (reads only — create/patch/delete stay admin)
|
|
||||||
"/api/geofences",
|
|
||||||
"/api/geofence-alerts",
|
|
||||||
# fire / weather overlays
|
|
||||||
"/api/fire-aircraft",
|
|
||||||
"/api/fire-incidents",
|
|
||||||
"/api/fire-perimeters",
|
|
||||||
"/api/weather-alerts",
|
|
||||||
"/api/storms",
|
|
||||||
})
|
|
||||||
|
|
||||||
PUBLIC_GET_PATTERNS = tuple(re.compile(p) for p in (
|
|
||||||
r"^/api/events/[^/]+$",
|
|
||||||
r"^/api/entities/[^/]+$",
|
|
||||||
r"^/api/entities/[^/]+/events$",
|
|
||||||
r"^/api/cameras/[^/]+$",
|
|
||||||
r"^/api/cameras/[^/]+/(?:snapshot|stream|hls\.m3u8|hlsseg)$",
|
|
||||||
r"^/api/geofences/[^/]+/at$",
|
|
||||||
))
|
|
||||||
|
|
||||||
# POST is only public for the read-only query endpoint.
|
|
||||||
PUBLIC_POST_EXACT = frozenset({"/api/search"})
|
|
||||||
|
|
||||||
|
|
||||||
def is_public(path: str, method: str) -> bool:
|
|
||||||
"""True when ``method path`` may be served without an admin session."""
|
|
||||||
if not path.startswith("/api/"):
|
|
||||||
return True
|
|
||||||
if path.startswith("/api/auth/"):
|
|
||||||
return True
|
|
||||||
norm = path.rstrip("/") or "/"
|
|
||||||
if method in ("GET", "HEAD"):
|
|
||||||
if norm in PUBLIC_GET_EXACT:
|
|
||||||
return True
|
|
||||||
return any(p.match(norm) for p in PUBLIC_GET_PATTERNS)
|
|
||||||
if method == "POST":
|
|
||||||
return norm in PUBLIC_POST_EXACT
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
# ── Config (read per call so tests and reloads pick up env changes) ─────────
|
|
||||||
|
|
||||||
def _env(name: str) -> str:
|
|
||||||
return (os.environ.get(name) or "").strip()
|
|
||||||
|
|
||||||
|
|
||||||
def admin_user() -> str:
|
|
||||||
return _env("ADMIN_USER")
|
|
||||||
|
|
||||||
|
|
||||||
def admin_password_hash() -> str:
|
|
||||||
return _env("ADMIN_PASSWORD_HASH")
|
|
||||||
|
|
||||||
|
|
||||||
def session_secret() -> str:
|
|
||||||
return _env("ADMIN_SESSION_SECRET")
|
|
||||||
|
|
||||||
|
|
||||||
def auth_configured() -> bool:
|
|
||||||
"""Fail closed: both the password hash and the signing key must be set."""
|
|
||||||
return bool(admin_password_hash() and session_secret())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Password hashing (stdlib PBKDF2-SHA256) ─────────────────────────────────
|
|
||||||
|
|
||||||
def _b64e(raw: bytes) -> str:
|
|
||||||
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
|
|
||||||
|
|
||||||
|
|
||||||
def _b64d(text: str) -> bytes:
|
|
||||||
pad = "=" * (-len(text) % 4)
|
|
||||||
return base64.urlsafe_b64decode(text + pad)
|
|
||||||
|
|
||||||
|
|
||||||
def hash_password(password: str, *, iterations: int = PBKDF2_ITERATIONS,
|
|
||||||
salt: bytes | None = None) -> str:
|
|
||||||
"""Return ``pbkdf2_sha256$<iters>$<salt_b64>$<hash_b64>``."""
|
|
||||||
salt = salt if salt is not None else secrets.token_bytes(16)
|
|
||||||
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
|
|
||||||
return f"{PBKDF2_ALGORITHM}${iterations}${_b64e(salt)}${_b64e(dk)}"
|
|
||||||
|
|
||||||
|
|
||||||
def verify_password(password: str, stored: str) -> bool:
|
|
||||||
"""Constant-time check of ``password`` against a stored PBKDF2 string."""
|
|
||||||
if not stored:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
algorithm, iterations_s, salt_b64, hash_b64 = stored.split("$", 3)
|
|
||||||
iterations = int(iterations_s)
|
|
||||||
salt = _b64d(salt_b64)
|
|
||||||
expected = _b64d(hash_b64)
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
return False
|
|
||||||
if algorithm != PBKDF2_ALGORITHM:
|
|
||||||
return False
|
|
||||||
if not (_ITERATIONS_FLOOR <= iterations <= _ITERATIONS_CEIL):
|
|
||||||
return False
|
|
||||||
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
|
|
||||||
return hmac.compare_digest(dk, expected)
|
|
||||||
|
|
||||||
|
|
||||||
def _const_eq(a: str, b: str) -> bool:
|
|
||||||
return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))
|
|
||||||
|
|
||||||
|
|
||||||
# ── Session tokens ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def _sign(body: str, secret: str) -> str:
|
|
||||||
digest = hmac.new(secret.encode("utf-8"), body.encode("ascii"), hashlib.sha256).digest()
|
|
||||||
return _b64e(digest)
|
|
||||||
|
|
||||||
|
|
||||||
def create_session_token(user: str, *, now: float | None = None) -> str:
|
|
||||||
secret = session_secret()
|
|
||||||
if not secret:
|
|
||||||
raise RuntimeError("ADMIN_SESSION_SECRET is not configured")
|
|
||||||
issued = int(now if now is not None else time.time())
|
|
||||||
payload = {"v": 1, "sub": user, "iat": issued, "exp": issued + SESSION_TTL_SECONDS}
|
|
||||||
body = _b64e(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8"))
|
|
||||||
return f"{body}.{_sign(body, secret)}"
|
|
||||||
|
|
||||||
|
|
||||||
def verify_session_token(token: str | None, *, now: float | None = None) -> str | None:
|
|
||||||
"""Return the username for a valid token, else ``None``. Never raises."""
|
|
||||||
if not token or "." not in token:
|
|
||||||
return None
|
|
||||||
secret = session_secret()
|
|
||||||
if not secret:
|
|
||||||
return None
|
|
||||||
body, signature = token.rsplit(".", 1)
|
|
||||||
try:
|
|
||||||
expected = _sign(body, secret)
|
|
||||||
if not hmac.compare_digest(signature.encode("utf-8"), expected.encode("utf-8")):
|
|
||||||
return None
|
|
||||||
except (UnicodeEncodeError, ValueError, TypeError):
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
payload = json.loads(_b64d(body))
|
|
||||||
version = payload["v"]
|
|
||||||
subject = str(payload["sub"])
|
|
||||||
issued = int(payload["iat"])
|
|
||||||
expires = int(payload["exp"])
|
|
||||||
except (ValueError, KeyError, TypeError):
|
|
||||||
return None
|
|
||||||
now_s = int(now if now is not None else time.time())
|
|
||||||
if version != 1:
|
|
||||||
return None
|
|
||||||
if expires <= now_s or issued > now_s + 300:
|
|
||||||
return None
|
|
||||||
expected = admin_user()
|
|
||||||
if not expected or not _const_eq(subject, expected):
|
|
||||||
return None
|
|
||||||
return subject
|
|
||||||
|
|
||||||
|
|
||||||
def current_user(request: Request) -> str | None:
|
|
||||||
"""The authenticated admin username for this request, else ``None``."""
|
|
||||||
if not auth_configured():
|
|
||||||
return None
|
|
||||||
return verify_session_token(request.cookies.get(COOKIE_NAME))
|
|
||||||
|
|
||||||
|
|
||||||
# ── Cookie helpers ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def _is_https(request: Request) -> bool:
|
|
||||||
proto = (request.headers.get("x-forwarded-proto") or "").split(",")[0].strip().lower()
|
|
||||||
if proto:
|
|
||||||
return proto == "https"
|
|
||||||
return request.url.scheme == "https"
|
|
||||||
|
|
||||||
|
|
||||||
_TRUTHY = {"1", "true", "yes"}
|
|
||||||
|
|
||||||
|
|
||||||
def cookie_secure_forced() -> bool:
|
|
||||||
"""``ADMIN_COOKIE_SECURE`` marks the deployment TLS-only.
|
|
||||||
|
|
||||||
Read on every call so tests and restarts pick up env changes; the header
|
|
||||||
inference in :func:`_is_https` stays as the fallback.
|
|
||||||
"""
|
|
||||||
return (os.getenv("ADMIN_COOKIE_SECURE") or "").strip().lower() in _TRUTHY
|
|
||||||
|
|
||||||
|
|
||||||
def set_session_cookie(response, request: Request, token: str) -> None:
|
|
||||||
response.set_cookie(
|
|
||||||
COOKIE_NAME,
|
|
||||||
token,
|
|
||||||
max_age=SESSION_TTL_SECONDS,
|
|
||||||
httponly=True,
|
|
||||||
samesite="lax",
|
|
||||||
secure=cookie_secure_forced() or _is_https(request),
|
|
||||||
path="/",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def clear_session_cookie(response) -> None:
|
|
||||||
response.delete_cookie(COOKIE_NAME, path="/", httponly=True, samesite="lax")
|
|
||||||
|
|
||||||
|
|
||||||
# ── Login rate limiting (in-memory; single replica) ─────────────────────────
|
|
||||||
|
|
||||||
_failures: dict[str, deque[float]] = {}
|
|
||||||
|
|
||||||
|
|
||||||
def client_ip(request: Request) -> str:
|
|
||||||
forwarded = request.headers.get("x-forwarded-for") or ""
|
|
||||||
first = forwarded.split(",")[0].strip()
|
|
||||||
if first:
|
|
||||||
return first
|
|
||||||
return request.client.host if request.client else "unknown"
|
|
||||||
|
|
||||||
|
|
||||||
def _prune(bucket: deque[float], now: float) -> None:
|
|
||||||
while bucket and now - bucket[0] > LOGIN_WINDOW_SECONDS:
|
|
||||||
bucket.popleft()
|
|
||||||
|
|
||||||
|
|
||||||
def rate_limited(ip: str, *, now: float | None = None) -> bool:
|
|
||||||
now_s = time.time() if now is None else now
|
|
||||||
bucket = _failures.get(ip)
|
|
||||||
if not bucket:
|
|
||||||
return False
|
|
||||||
_prune(bucket, now_s)
|
|
||||||
return len(bucket) >= LOGIN_MAX_FAILURES
|
|
||||||
|
|
||||||
|
|
||||||
def record_failure(ip: str, *, now: float | None = None) -> None:
|
|
||||||
now_s = time.time() if now is None else now
|
|
||||||
if len(_failures) > 10_000: # bound memory against IP spraying
|
|
||||||
for key in [k for k, v in _failures.items() if not v or now_s - v[-1] > LOGIN_WINDOW_SECONDS]:
|
|
||||||
_failures.pop(key, None)
|
|
||||||
bucket = _failures.setdefault(ip, deque())
|
|
||||||
_prune(bucket, now_s)
|
|
||||||
bucket.append(now_s)
|
|
||||||
|
|
||||||
|
|
||||||
def reset_failures(ip: str | None = None) -> None:
|
|
||||||
"""Clear the limiter (used by logout success and tests)."""
|
|
||||||
if ip is None:
|
|
||||||
_failures.clear()
|
|
||||||
else:
|
|
||||||
_failures.pop(ip, None)
|
|
||||||
|
|
||||||
|
|
||||||
# ── CSRF (origin host must match the request host when supplied) ────────────
|
|
||||||
|
|
||||||
def origin_allowed(request: Request) -> bool:
|
|
||||||
if request.method.upper() not in _STATE_CHANGING:
|
|
||||||
return True
|
|
||||||
origin = request.headers.get("origin") or request.headers.get("referer")
|
|
||||||
if not origin:
|
|
||||||
return True # no browser context: session cookie is the credential
|
|
||||||
host = (request.headers.get("x-forwarded-host") or request.headers.get("host") or "")
|
|
||||||
host = host.split(",")[0].strip().lower()
|
|
||||||
try:
|
|
||||||
origin_host = urlparse(origin).netloc.strip().lower()
|
|
||||||
except ValueError:
|
|
||||||
return False
|
|
||||||
if not host or not origin_host:
|
|
||||||
return False
|
|
||||||
return origin_host == host
|
|
||||||
|
|
||||||
|
|
||||||
# ── Middleware ───────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def _json_response(status: int, detail: str) -> JSONResponse:
|
|
||||||
return JSONResponse({"detail": detail}, status_code=status)
|
|
||||||
|
|
||||||
|
|
||||||
class AdminAuthMiddleware:
|
|
||||||
"""Deny-by-default gate for ``/api/*`` (pure ASGI; keeps streaming intact)."""
|
|
||||||
|
|
||||||
def __init__(self, app):
|
|
||||||
self.app = app
|
|
||||||
|
|
||||||
async def __call__(self, scope, receive, send):
|
|
||||||
if scope.get("type") != "http":
|
|
||||||
return await self.app(scope, receive, send)
|
|
||||||
path = scope.get("path") or ""
|
|
||||||
method = (scope.get("method") or "GET").upper()
|
|
||||||
if not path.startswith("/api/") or is_public(path, method):
|
|
||||||
return await self.app(scope, receive, send)
|
|
||||||
|
|
||||||
request = Request(scope)
|
|
||||||
if not auth_configured():
|
|
||||||
return await _json_response(403, "admin auth not configured")(scope, receive, send)
|
|
||||||
if current_user(request) is None:
|
|
||||||
return await _json_response(401, "admin authentication required")(scope, receive, send)
|
|
||||||
if not origin_allowed(request):
|
|
||||||
return await _json_response(403, "cross-origin admin request blocked")(scope, receive, send)
|
|
||||||
return await self.app(scope, receive, send)
|
|
||||||
|
|
||||||
|
|
||||||
# ── Auth routes ─────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
router = APIRouter()
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/api/auth/me")
|
|
||||||
async def auth_me(request: Request):
|
|
||||||
"""Always 200 — the HUD uses this to show/hide admin UI."""
|
|
||||||
user = current_user(request)
|
|
||||||
return {"authenticated": user is not None, "admin": user is not None}
|
|
||||||
|
|
||||||
|
|
||||||
async def _read_credentials(request: Request) -> dict:
|
|
||||||
"""Accept form-encoded or JSON bodies (never trust the claimed type)."""
|
|
||||||
raw = await request.body()
|
|
||||||
if not raw:
|
|
||||||
return {}
|
|
||||||
ctype = (request.headers.get("content-type") or "").lower()
|
|
||||||
if "json" in ctype:
|
|
||||||
try:
|
|
||||||
payload = json.loads(raw)
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
return {}
|
|
||||||
return payload if isinstance(payload, dict) else {}
|
|
||||||
if "form" in ctype or "urlencoded" in ctype:
|
|
||||||
try:
|
|
||||||
parsed = parse_qs(raw.decode("utf-8", "replace"))
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
return {}
|
|
||||||
return {k: v[0] for k, v in parsed.items() if v}
|
|
||||||
# Unknown content type: try JSON, then form.
|
|
||||||
try:
|
|
||||||
payload = json.loads(raw)
|
|
||||||
if isinstance(payload, dict):
|
|
||||||
return payload
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
parsed = parse_qs(raw.decode("utf-8", "replace"))
|
|
||||||
except (ValueError, TypeError):
|
|
||||||
return {}
|
|
||||||
return {k: v[0] for k, v in parsed.items() if v}
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/api/auth/login")
|
|
||||||
async def auth_login(request: Request):
|
|
||||||
ip = client_ip(request)
|
|
||||||
if not auth_configured():
|
|
||||||
return _json_response(403, "admin auth not configured")
|
|
||||||
if rate_limited(ip):
|
|
||||||
return _json_response(429, "too many failed login attempts")
|
|
||||||
|
|
||||||
data = await _read_credentials(request)
|
|
||||||
username = str(data.get("username") or data.get("user") or "")
|
|
||||||
password = str(data.get("password") or "")
|
|
||||||
|
|
||||||
user_ok = bool(username) and bool(admin_user()) and _const_eq(username, admin_user())
|
|
||||||
pass_ok = verify_password(password, admin_password_hash())
|
|
||||||
if not (user_ok and pass_ok):
|
|
||||||
record_failure(ip)
|
|
||||||
return _json_response(401, "invalid credentials")
|
|
||||||
|
|
||||||
reset_failures(ip)
|
|
||||||
response = JSONResponse({"authenticated": True, "admin": True})
|
|
||||||
set_session_cookie(response, request, create_session_token(admin_user()))
|
|
||||||
return response
|
|
||||||
|
|
||||||
|
|
||||||
@router.post("/api/auth/logout")
|
|
||||||
async def auth_logout(request: Request):
|
|
||||||
# NOTE: never clear the login limiter here — logout is unauthenticated and
|
|
||||||
# would otherwise let an attacker reset the rate limit between guesses.
|
|
||||||
response = JSONResponse({"authenticated": False, "admin": False})
|
|
||||||
clear_session_cookie(response)
|
|
||||||
return response
|
|
||||||
|
|
||||||
|
|
||||||
_LOGIN_PAGE = """<!doctype html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
<meta name="robots" content="noindex">
|
|
||||||
<title>Admin sign-in · OSINT//</title>
|
|
||||||
<style>
|
|
||||||
:root { --bg:#05070c; --panel:#0b1018; --line:#1c2735; --cyan:#35e0ff; --magenta:#ff2e97; --text:#d7e3f2; --dim:#7d8ea3; }
|
|
||||||
* { box-sizing:border-box; }
|
|
||||||
body { margin:0; min-height:100vh; display:grid; place-items:center; background:
|
|
||||||
radial-gradient(1000px 500px at 50% -10%, rgba(53,224,255,.10), transparent 60%),
|
|
||||||
radial-gradient(700px 400px at 90% 110%, rgba(255,46,151,.08), transparent 60%), var(--bg);
|
|
||||||
color:var(--text); font:15px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
|
|
||||||
.box { width:100%; max-width:360px; padding:2rem 1.6rem; border:1px solid var(--line);
|
|
||||||
border-radius:8px; background:linear-gradient(180deg, var(--panel), #070b12);
|
|
||||||
box-shadow:0 0 0 1px rgba(53,224,255,.06), 0 24px 60px rgba(0,0,0,.6); }
|
|
||||||
.brand { letter-spacing:.24em; font-size:.8rem; color:var(--dim); margin-bottom:1.4rem; }
|
|
||||||
.brand b { color:var(--cyan); }
|
|
||||||
h1 { font-size:1rem; letter-spacing:.12em; margin:0 0 1.2rem; text-transform:uppercase; }
|
|
||||||
label { display:block; font-size:.68rem; letter-spacing:.16em; color:var(--dim);
|
|
||||||
text-transform:uppercase; margin:.9rem 0 .35rem; }
|
|
||||||
input { width:100%; padding:.6rem .7rem; background:#04070d; color:var(--text);
|
|
||||||
border:1px solid var(--line); border-radius:4px; font:inherit; }
|
|
||||||
input:focus { outline:none; border-color:var(--cyan); box-shadow:0 0 0 2px rgba(53,224,255,.14); }
|
|
||||||
button { width:100%; margin-top:1.4rem; padding:.65rem; background:var(--cyan); color:#02121a;
|
|
||||||
border:0; border-radius:4px; font:inherit; font-weight:700; letter-spacing:.12em; cursor:pointer; }
|
|
||||||
button:hover { background:#6becff; }
|
|
||||||
button:disabled { opacity:.5; cursor:default; }
|
|
||||||
.msg { min-height:1.2rem; margin-top:.9rem; font-size:.8rem; color:var(--magenta); }
|
|
||||||
.note { margin-top:1.1rem; font-size:.74rem; color:var(--dim); }
|
|
||||||
a { color:var(--cyan); text-decoration:none; }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<form class="box" id="login-form">
|
|
||||||
<div class="brand">OSINT<b>//</b> ADMIN</div>
|
|
||||||
<h1>Sign in</h1>
|
|
||||||
<label for="username">Username</label>
|
|
||||||
<input id="username" name="username" type="text" autocomplete="username" required autofocus>
|
|
||||||
<label for="password">Password</label>
|
|
||||||
<input id="password" name="password" type="password" autocomplete="current-password" required>
|
|
||||||
<button id="submit" type="submit">AUTHENTICATE</button>
|
|
||||||
<div class="msg" id="msg" role="alert"></div>
|
|
||||||
<div class="note"><a href="/">← Back to dashboard</a></div>
|
|
||||||
</form>
|
|
||||||
<script>
|
|
||||||
const form = document.getElementById('login-form');
|
|
||||||
const msg = document.getElementById('msg');
|
|
||||||
const submit = document.getElementById('submit');
|
|
||||||
form.addEventListener('submit', async (ev) => {
|
|
||||||
ev.preventDefault();
|
|
||||||
msg.textContent = '';
|
|
||||||
submit.disabled = true;
|
|
||||||
try {
|
|
||||||
const r = await fetch('/api/auth/login', {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
|
||||||
body: new URLSearchParams(new FormData(form)),
|
|
||||||
});
|
|
||||||
const data = await r.json().catch(() => ({}));
|
|
||||||
if (r.ok) { window.location.replace('/'); return; }
|
|
||||||
msg.textContent = r.status === 429 ? 'Too many attempts. Try again later.'
|
|
||||||
: (data && data.detail ? String(data.detail) : 'Sign-in failed.');
|
|
||||||
} catch (e) {
|
|
||||||
msg.textContent = 'Network error.';
|
|
||||||
} finally {
|
|
||||||
submit.disabled = false;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
"""
|
|
||||||
|
|
||||||
_NOT_CONFIGURED = ('<div class="msg">Admin auth is not configured on this server. '
|
|
||||||
'Set ADMIN_PASSWORD_HASH and ADMIN_SESSION_SECRET.</div>')
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/login", response_class=HTMLResponse)
|
|
||||||
async def login_page():
|
|
||||||
html = _LOGIN_PAGE
|
|
||||||
if not auth_configured():
|
|
||||||
html = html.replace('<div class="msg" id="msg" role="alert"></div>',
|
|
||||||
_NOT_CONFIGURED.replace('class="msg"', 'class="msg" id="msg" role="alert"'))
|
|
||||||
response = HTMLResponse(html)
|
|
||||||
response.headers["Cache-Control"] = "no-store"
|
|
||||||
return response
|
|
||||||
|
|
||||||
|
|
||||||
# ── CLI: generate a password hash ────────────────────────────────────────────
|
|
||||||
|
|
||||||
def _main(argv: list[str]) -> int:
|
|
||||||
if len(argv) != 2 or argv[0] != "hash":
|
|
||||||
print("usage: python app/auth.py hash '<password>'")
|
|
||||||
return 2
|
|
||||||
print(hash_password(argv[1]))
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
import sys
|
|
||||||
|
|
||||||
raise SystemExit(_main(sys.argv[1:]))
|
|
||||||
|
|
@ -1,19 +1,50 @@
|
||||||
"""Background ffmpeg — never block a FastAPI request on a frame grab.
|
"""Background masscan / ffmpeg — never block a FastAPI request on a scan.
|
||||||
|
|
||||||
ffmpeg frame grabs are scheduled with asyncio.create_task and shared per URL.
|
masscan is capped at 200 pps (home uplink saturates at 1k+). ffmpeg frame
|
||||||
|
grabs are scheduled with asyncio.create_task and shared per URL.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import logging
|
||||||
import shutil
|
import shutil
|
||||||
from cachetools import TTLCache
|
from cachetools import TTLCache
|
||||||
|
|
||||||
|
logger = logging.getLogger("osint.bg_jobs")
|
||||||
|
|
||||||
|
MASSCAN_PPS_CAP = 200
|
||||||
|
|
||||||
|
_masscan_task: asyncio.Task | None = None
|
||||||
_ffmpeg_cache: TTLCache = TTLCache(maxsize=100, ttl=300)
|
_ffmpeg_cache: TTLCache = TTLCache(maxsize=100, ttl=300)
|
||||||
_ffmpeg_tasks: dict[str, asyncio.Task] = {}
|
_ffmpeg_tasks: dict[str, asyncio.Task] = {}
|
||||||
_FFMPEG = shutil.which("ffmpeg")
|
_FFMPEG = shutil.which("ffmpeg")
|
||||||
|
|
||||||
|
|
||||||
|
def schedule_masscan_pass() -> bool:
|
||||||
|
"""Kick one capped masscan pass. Returns False if a pass is already running."""
|
||||||
|
global _masscan_task
|
||||||
|
if _masscan_task is not None and not _masscan_task.done():
|
||||||
|
return False
|
||||||
|
_masscan_task = asyncio.create_task(_run_masscan_capped())
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def _run_masscan_capped() -> None:
|
||||||
|
import masscan_config as cfg
|
||||||
|
from run_masscan_service import _verify_excludefile, run_pass
|
||||||
|
|
||||||
|
orig = cfg.MASSCAN_RATE
|
||||||
|
if orig > MASSCAN_PPS_CAP:
|
||||||
|
logger.warning("capping masscan rate %s pps -> %s", orig, MASSCAN_PPS_CAP)
|
||||||
|
cfg.MASSCAN_RATE = MASSCAN_PPS_CAP
|
||||||
|
try:
|
||||||
|
_verify_excludefile()
|
||||||
|
await run_pass()
|
||||||
|
finally:
|
||||||
|
cfg.MASSCAN_RATE = orig
|
||||||
|
|
||||||
|
|
||||||
def cached_ffmpeg_jpeg(url: str) -> bytes | None:
|
def cached_ffmpeg_jpeg(url: str) -> bytes | None:
|
||||||
return _ffmpeg_cache.get(url)
|
return _ffmpeg_cache.get(url)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -59,8 +59,7 @@ SNAPSHOT_CACHE_DIR = os.getenv("SNAPSHOT_CACHE_DIR", "/data/snapshots")
|
||||||
SNAPSHOT_TTL_SECONDS = int(os.getenv("SNAPSHOT_TTL_SECONDS", "300"))
|
SNAPSHOT_TTL_SECONDS = int(os.getenv("SNAPSHOT_TTL_SECONDS", "300"))
|
||||||
SNAPSHOT_TIMEOUT = float(os.getenv("SNAPSHOT_TIMEOUT", "8.0"))
|
SNAPSHOT_TIMEOUT = float(os.getenv("SNAPSHOT_TIMEOUT", "8.0"))
|
||||||
|
|
||||||
# Retained so an old CAMERA_NATS_SUBJECT env does not surprise operators.
|
# NATS subject cameras are published on (consumed by the shared ingester).
|
||||||
# This service does not publish on it; cameras live in the cameras table.
|
|
||||||
CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera")
|
CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera")
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
"""Resolve a browser-renderable preview for a camera.
|
"""Resolve a browser-renderable preview for a camera.
|
||||||
|
|
||||||
HTTP/MJPEG cameras already expose a snapshot_url the existing proxy can
|
HTTP/MJPEG cameras already expose a snapshot_url the existing proxy can
|
||||||
stream. Some scraper sources store `rtsp://` URLs with no snapshot_url, so
|
stream. masscan finds are stored as `rtsp://IP/` with no snapshot_url, so
|
||||||
the map popup used to skip the <img> entirely and the leftover source link
|
the map popup used to skip the <img> entirely and the leftover source link
|
||||||
handed the browser an rtsp:// URL (which opens VLC).
|
handed the browser an rtsp:// URL (which opens VLC).
|
||||||
|
|
||||||
|
|
@ -42,6 +42,16 @@ _HTTP_PATHS = (
|
||||||
"/tmpfs/auto.jpg",
|
"/tmpfs/auto.jpg",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Browser-playable MJPEG paths the /stream proxy can pass through.
|
||||||
|
_MJPEG_PATHS = (
|
||||||
|
"/mjpg/video.mjpg",
|
||||||
|
"/video.mjpg",
|
||||||
|
"/cgi-bin/mjpg/video.cgi",
|
||||||
|
"/axis-cgi/mjpg/video.cgi",
|
||||||
|
"/nphMotionJpeg",
|
||||||
|
"/mjpeg.cgi",
|
||||||
|
)
|
||||||
|
|
||||||
_FFMPEG = shutil.which("ffmpeg")
|
_FFMPEG = shutil.which("ffmpeg")
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -77,6 +87,55 @@ async def _http_get_image(url: str, timeout: float = 2.5) -> bytes | None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def _http_feed_url(url: str, timeout: float = 2.5) -> str | None:
|
||||||
|
"""Return url if it looks like an unauthenticated image/MJPEG feed."""
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(
|
||||||
|
timeout=timeout, follow_redirects=True,
|
||||||
|
headers={"User-Agent": USER_AGENT},
|
||||||
|
) as c:
|
||||||
|
async with c.stream("GET", url) as r:
|
||||||
|
if r.status_code != 200:
|
||||||
|
return None
|
||||||
|
ctype = (r.headers.get("content-type") or "").lower()
|
||||||
|
if "html" in ctype or ctype.startswith("text/"):
|
||||||
|
return None
|
||||||
|
if any(x in ctype for x in ("image/", "multipart", "mjpeg", "octet-stream")):
|
||||||
|
# Read a little to reject empty/error bodies.
|
||||||
|
chunk = b""
|
||||||
|
async for b in r.aiter_bytes():
|
||||||
|
chunk += b
|
||||||
|
if len(chunk) >= 64:
|
||||||
|
break
|
||||||
|
if len(chunk) < 64:
|
||||||
|
return None
|
||||||
|
if b"html" in chunk[:64].lower():
|
||||||
|
return None
|
||||||
|
return url
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def probe_public_feed(host: str) -> str | None:
|
||||||
|
"""Unauthenticated HTTP still or MJPEG URL for this host, or None.
|
||||||
|
|
||||||
|
Used at masscan ingest time so dead RTSP-only hosts never hit the map.
|
||||||
|
No credentials, no RTSP path-walking (too slow / rarely public).
|
||||||
|
"""
|
||||||
|
urls = [f"http://{host}{p}" for p in _HTTP_PATHS]
|
||||||
|
urls.append(f"http://{host}:8080/shot.jpg")
|
||||||
|
urls.extend(f"http://{host}{p}" for p in _MJPEG_PATHS)
|
||||||
|
results = await asyncio.gather(
|
||||||
|
*(_http_feed_url(u) for u in urls),
|
||||||
|
return_exceptions=True,
|
||||||
|
)
|
||||||
|
for url, hit in zip(urls, results):
|
||||||
|
if isinstance(hit, str) and hit:
|
||||||
|
return hit
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
async def ffmpeg_snapshot(url: str, timeout: float = 8.0) -> bytes | None:
|
async def ffmpeg_snapshot(url: str, timeout: float = 8.0) -> bytes | None:
|
||||||
"""Grab a single JPEG frame from an RTSP URL. None if ffmpeg missing/fails.
|
"""Grab a single JPEG frame from an RTSP URL. None if ffmpeg missing/fails.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,8 @@ Pipeline per cycle:
|
||||||
2. Parse cameras (Insecam-style HTML with embedded lat/lon, or plain-text
|
2. Parse cameras (Insecam-style HTML with embedded lat/lon, or plain-text
|
||||||
`url[|lat,lon|vendor|location]` lines).
|
`url[|lat,lon|vendor|location]` lines).
|
||||||
3. Geocode missing coords via Nominatim at <=1 req/s.
|
3. Geocode missing coords via Nominatim at <=1 req/s.
|
||||||
4. Upsert into the `cameras` table keyed by sha256(url_hash).
|
4. Publish each camera to NATS (`events.camera`) for the shared ingester,
|
||||||
Discovery is not published as an event.
|
and upsert into the `cameras` table keyed by sha256(url_hash).
|
||||||
|
|
||||||
Snapshots are cached locally with a TTL; nothing is fetched more often than
|
Snapshots are cached locally with a TTL; nothing is fetched more often than
|
||||||
the cache allows.
|
the cache allows.
|
||||||
|
|
|
||||||
|
|
@ -107,12 +107,3 @@ VESSELAPI_MAX_CALLS_PER_DAY = int(os.getenv("VESSELAPI_MAX_CALLS_PER_DAY", "5"))
|
||||||
# Run the VesselAPI poller inside the dashboard process (default on, like AIS).
|
# Run the VesselAPI poller inside the dashboard process (default on, like AIS).
|
||||||
VESSELAPI_IN_APP = os.getenv("VESSELAPI_IN_APP", "1").lower() in ("1", "true", "yes")
|
VESSELAPI_IN_APP = os.getenv("VESSELAPI_IN_APP", "1").lower() in ("1", "true", "yes")
|
||||||
VESSELAPI_IN_INGEST = os.getenv("VESSELAPI_IN_INGEST", "0").lower() in ("1", "true", "yes")
|
VESSELAPI_IN_INGEST = os.getenv("VESSELAPI_IN_INGEST", "0").lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
# ADS-B (ADSB.lol, no key). The dashboard's refresh loop follows browser
|
|
||||||
# viewports; with no tab open it persisted nothing and aircraft_positions went
|
|
||||||
# silent for a day. ADSB_WATCH_ENABLED=1 makes the loop sweep the chokepoint
|
|
||||||
# presets while idle, so the hypertable keeps advancing unattended.
|
|
||||||
ADSB_REFRESH_INTERVAL = float(os.getenv("ADSB_REFRESH_INTERVAL", "8"))
|
|
||||||
ADSB_WATCH_ENABLED = os.getenv("ADSB_WATCH_ENABLED", "1").lower() in ("1", "true", "yes")
|
|
||||||
# Idle sweep cadence; 30 s over 5 preset boxes ≈ 0.17 req/s to ADSB.lol.
|
|
||||||
ADSB_WATCH_INTERVAL = float(os.getenv("ADSB_WATCH_INTERVAL", "30"))
|
|
||||||
|
|
|
||||||
527
app/geofence.py
527
app/geofence.py
|
|
@ -7,7 +7,6 @@ in ``geofence_alerts`` and fan out as WS type ``geofence_alert``.
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import logging
|
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
@ -16,19 +15,6 @@ from sqlalchemy import text
|
||||||
|
|
||||||
from database import async_session
|
from database import async_session
|
||||||
|
|
||||||
logger = logging.getLogger("osint.geofence")
|
|
||||||
|
|
||||||
# New hit kinds. adsb/ais/firms omit ``evidence``; these three must include it.
|
|
||||||
# ``camera`` is never a hit kind.
|
|
||||||
EVIDENCE_KINDS = frozenset({"earthquake", "fire_incident", "news"})
|
|
||||||
_CAMERA_CAP = 5
|
|
||||||
_NEWS_CAP = 3
|
|
||||||
# Process-local "already paged" set for polled incidents. The 5-minute
|
|
||||||
# cooldown still applies; this stops a later poll (or a restart that
|
|
||||||
# re-reads the DB check) from treating a durable hit as new. Not used
|
|
||||||
# for moving adsb/ais/firms targets.
|
|
||||||
_notified_once: set[tuple[str, str, str]] = set()
|
|
||||||
|
|
||||||
|
|
||||||
def _rings_from_geojson(geojson: dict) -> list[list[list[float]]]:
|
def _rings_from_geojson(geojson: dict) -> list[list[list[float]]]:
|
||||||
if not isinstance(geojson, dict):
|
if not isinstance(geojson, dict):
|
||||||
|
|
@ -113,160 +99,6 @@ _recent_hits: dict[tuple[str, str], datetime] = {}
|
||||||
_HIT_COOLDOWN = timedelta(minutes=5)
|
_HIT_COOLDOWN = timedelta(minutes=5)
|
||||||
|
|
||||||
|
|
||||||
def iso_z(ts: datetime) -> str:
|
|
||||||
"""UTC ISO-8601 with a Z suffix so it is safe in a query string."""
|
|
||||||
if ts.tzinfo is None:
|
|
||||||
ts = ts.replace(tzinfo=timezone.utc)
|
|
||||||
return ts.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
||||||
|
|
||||||
|
|
||||||
def snapshot_path(gid: str, ts: datetime) -> str:
|
|
||||||
return f"/api/geofences/{gid}/at?ts={iso_z(ts)}"
|
|
||||||
|
|
||||||
|
|
||||||
def camera_evidence(row: dict) -> dict:
|
|
||||||
"""Proxy path only. Never copy ``cameras.snapshot_url`` (agency / rtsp)."""
|
|
||||||
cid = str(row.get("id") or "")
|
|
||||||
name = row.get("name")
|
|
||||||
if name is None:
|
|
||||||
name = row.get("location_name") or ""
|
|
||||||
return {
|
|
||||||
"id": cid,
|
|
||||||
"name": str(name or ""),
|
|
||||||
"snapshot_url": f"/api/cameras/{cid}/snapshot",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def news_evidence(row: dict) -> dict:
|
|
||||||
return {
|
|
||||||
"headline": str(row.get("headline") or ""),
|
|
||||||
"url": str(row.get("url") or ""),
|
|
||||||
"importance": str(row.get("importance") or ""),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def evidence_pack(
|
|
||||||
gid: str, ts: datetime, cameras: list[dict], news: list[dict],
|
|
||||||
) -> dict:
|
|
||||||
return {
|
|
||||||
"cameras": [camera_evidence(r) for r in cameras[:_CAMERA_CAP]],
|
|
||||||
"news": [news_evidence(r) for r in news[:_NEWS_CAP]],
|
|
||||||
"snapshot": snapshot_path(gid, ts),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def polygon_bbox(geojson: dict) -> str | None:
|
|
||||||
"""``minlon,minlat,maxlon,maxlat`` of the outer ring, or None."""
|
|
||||||
try:
|
|
||||||
rings = _rings_from_geojson(geojson)
|
|
||||||
except (ValueError, TypeError, KeyError):
|
|
||||||
return None
|
|
||||||
pts = rings[0]
|
|
||||||
lons = [p[0] for p in pts]
|
|
||||||
lats = [p[1] for p in pts]
|
|
||||||
return f"{min(lons)},{min(lats)},{max(lons)},{max(lats)}"
|
|
||||||
|
|
||||||
|
|
||||||
def earthquake_entity_id(row: dict) -> str:
|
|
||||||
"""Stable id shared by the insert hook and the catch-up scan."""
|
|
||||||
raw = row.get("raw")
|
|
||||||
if isinstance(raw, str):
|
|
||||||
try:
|
|
||||||
raw = json.loads(raw)
|
|
||||||
except ValueError:
|
|
||||||
raw = None
|
|
||||||
if isinstance(raw, dict) and raw.get("usgs_id"):
|
|
||||||
return str(raw["usgs_id"])
|
|
||||||
url = row.get("url")
|
|
||||||
if url and str(url).strip():
|
|
||||||
return str(url).strip()
|
|
||||||
return str(row.get("id") or row.get("event_id") or "")
|
|
||||||
|
|
||||||
|
|
||||||
def fire_incident_entity_id(marker: dict) -> str:
|
|
||||||
"""IrwinID when the feed has one, else a stable name|state|discovered key."""
|
|
||||||
extra = marker.get("extra") or {}
|
|
||||||
for key in ("irwin_id", "unique_fire_id"):
|
|
||||||
val = extra.get(key)
|
|
||||||
if val:
|
|
||||||
return str(val)
|
|
||||||
name = marker.get("id") or marker.get("label") or "incident"
|
|
||||||
state = extra.get("state") or ""
|
|
||||||
discovered = extra.get("discovered") or ""
|
|
||||||
return f"{name}|{state}|{discovered}"
|
|
||||||
|
|
||||||
|
|
||||||
# Do not SELECT cameras.snapshot_url — that column is the agency/rtsp URL.
|
|
||||||
_CAMERAS_INSIDE_SQL = """
|
|
||||||
SELECT id::text AS id,
|
|
||||||
COALESCE(location_name, '') AS name
|
|
||||||
FROM cameras
|
|
||||||
WHERE location_lat IS NOT NULL
|
|
||||||
AND location_lon IS NOT NULL
|
|
||||||
AND ST_Intersects(
|
|
||||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
|
||||||
ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326)
|
|
||||||
)
|
|
||||||
ORDER BY ST_Distance(
|
|
||||||
ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326),
|
|
||||||
ST_SetSRID(ST_MakePoint(:lon, :lat), 4326)
|
|
||||||
)
|
|
||||||
LIMIT :limit
|
|
||||||
"""
|
|
||||||
|
|
||||||
_NEWS_INSIDE_SQL = """
|
|
||||||
SELECT headline,
|
|
||||||
COALESCE(url, '') AS url,
|
|
||||||
COALESCE(importance, '') AS importance
|
|
||||||
FROM news_items
|
|
||||||
WHERE lat IS NOT NULL
|
|
||||||
AND lon IS NOT NULL
|
|
||||||
AND ST_Intersects(
|
|
||||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
|
||||||
ST_SetSRID(ST_MakePoint(lon, lat), 4326)
|
|
||||||
)
|
|
||||||
ORDER BY created_at DESC
|
|
||||||
LIMIT :limit
|
|
||||||
"""
|
|
||||||
|
|
||||||
_ALREADY_SQL = """
|
|
||||||
SELECT 1
|
|
||||||
FROM geofence_alerts
|
|
||||||
WHERE geofence_id = CAST(:gid AS uuid)
|
|
||||||
AND source_kind = :source_kind
|
|
||||||
AND entity_id = :entity_id
|
|
||||||
LIMIT 1
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
async def _rows(sql: str, params: dict) -> list[dict]:
|
|
||||||
async with async_session() as session:
|
|
||||||
result = await session.execute(text(sql), params)
|
|
||||||
return [dict(r) for r in result.mappings().all()]
|
|
||||||
|
|
||||||
|
|
||||||
async def build_evidence(
|
|
||||||
gid: str, *, lat: float, lon: float, now: datetime,
|
|
||||||
) -> dict:
|
|
||||||
"""Cameras nearest the hit (≤5) and news most-recent (≤3) inside the fence.
|
|
||||||
|
|
||||||
Empty arrays if none or the query fails. Snapshot is a path, not a body.
|
|
||||||
"""
|
|
||||||
cameras: list[dict] = []
|
|
||||||
news: list[dict] = []
|
|
||||||
try:
|
|
||||||
cameras = await _rows(_CAMERAS_INSIDE_SQL, {
|
|
||||||
"gid": gid, "lat": lat, "lon": lon, "limit": _CAMERA_CAP,
|
|
||||||
})
|
|
||||||
except Exception:
|
|
||||||
logger.exception("evidence cameras query failed gid=%s", gid)
|
|
||||||
try:
|
|
||||||
news = await _rows(_NEWS_INSIDE_SQL, {"gid": gid, "limit": _NEWS_CAP})
|
|
||||||
except Exception:
|
|
||||||
logger.exception("evidence news query failed gid=%s", gid)
|
|
||||||
return evidence_pack(gid, now, cameras, news)
|
|
||||||
|
|
||||||
|
|
||||||
async def refresh_cache() -> list[dict]:
|
async def refresh_cache() -> list[dict]:
|
||||||
global _cache
|
global _cache
|
||||||
async with async_session() as session:
|
async with async_session() as session:
|
||||||
|
|
@ -417,24 +249,12 @@ async def record_and_notify(
|
||||||
lat: float,
|
lat: float,
|
||||||
lon: float,
|
lon: float,
|
||||||
payload: dict[str, Any] | None = None,
|
payload: dict[str, Any] | None = None,
|
||||||
skip_existing: bool = False,
|
|
||||||
) -> int:
|
) -> int:
|
||||||
"""Insert a geofence_alerts row per hit and WS-push to viewport clients.
|
"""Insert a geofence_alerts row per hit and WS-push to viewport clients.
|
||||||
|
|
||||||
PostGIS ST_Intersects is the source of truth. The in-process GeoJSON
|
PostGIS ST_Intersects is the source of truth. The in-process GeoJSON
|
||||||
cache is not a reject filter — the FIRMS ingester never fills it.
|
cache is not a reject filter — the FIRMS ingester never fills it.
|
||||||
|
|
||||||
``source_kind=camera`` is refused (no row, no WS). Earthquake, fire
|
|
||||||
incident, and news hits get an ``evidence`` object; adsb/ais/firms
|
|
||||||
keep the caller payload unchanged.
|
|
||||||
|
|
||||||
``skip_existing`` is for polled incidents (same id every cycle). It
|
|
||||||
does not change the 5-minute cooldown. A failed existence check
|
|
||||||
skips the hit so a broken read cannot page every fence.
|
|
||||||
"""
|
"""
|
||||||
if source_kind == "camera":
|
|
||||||
logger.warning("refusing geofence notify for source_kind=camera")
|
|
||||||
return 0
|
|
||||||
hits = await st_intersects(lon, lat)
|
hits = await st_intersects(lon, lat)
|
||||||
if not hits:
|
if not hits:
|
||||||
return 0
|
return 0
|
||||||
|
|
@ -455,33 +275,6 @@ async def record_and_notify(
|
||||||
hits = fresh
|
hits = fresh
|
||||||
async with async_session() as session:
|
async with async_session() as session:
|
||||||
for fence in hits:
|
for fence in hits:
|
||||||
once_key = (str(fence["id"]), source_kind, str(entity_id))
|
|
||||||
if skip_existing:
|
|
||||||
if once_key in _notified_once:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
existing = await session.execute(
|
|
||||||
text(_ALREADY_SQL),
|
|
||||||
{
|
|
||||||
"gid": fence["id"],
|
|
||||||
"source_kind": source_kind,
|
|
||||||
"entity_id": str(entity_id),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
if existing.first() is not None:
|
|
||||||
_notified_once.add(once_key)
|
|
||||||
continue
|
|
||||||
except Exception:
|
|
||||||
logger.exception(
|
|
||||||
"geofence existing-hit check failed kind=%s entity=%s",
|
|
||||||
source_kind, entity_id,
|
|
||||||
)
|
|
||||||
continue
|
|
||||||
body_payload = dict(payload or {})
|
|
||||||
if source_kind in EVIDENCE_KINDS:
|
|
||||||
body_payload["evidence"] = await build_evidence(
|
|
||||||
str(fence["id"]), lat=lat, lon=lon, now=now,
|
|
||||||
)
|
|
||||||
aid = str(uuid4())
|
aid = str(uuid4())
|
||||||
body = {
|
body = {
|
||||||
"id": aid,
|
"id": aid,
|
||||||
|
|
@ -491,7 +284,7 @@ async def record_and_notify(
|
||||||
"entity_id": str(entity_id),
|
"entity_id": str(entity_id),
|
||||||
"lat": lat,
|
"lat": lat,
|
||||||
"lon": lon,
|
"lon": lon,
|
||||||
"payload": body_payload,
|
"payload": payload or {},
|
||||||
"created_at": now.isoformat(),
|
"created_at": now.isoformat(),
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
|
|
@ -513,7 +306,7 @@ async def record_and_notify(
|
||||||
"entity_id": str(entity_id),
|
"entity_id": str(entity_id),
|
||||||
"lat": lat,
|
"lat": lat,
|
||||||
"lon": lon,
|
"lon": lon,
|
||||||
"payload": json.dumps(body_payload),
|
"payload": json.dumps(payload or {}),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|
@ -521,324 +314,8 @@ async def record_and_notify(
|
||||||
sent += await manager.publish_point(
|
sent += await manager.publish_point(
|
||||||
"geofence_alert", body, lat=lat, lon=lon,
|
"geofence_alert", body, lat=lat, lon=lon,
|
||||||
)
|
)
|
||||||
if skip_existing:
|
|
||||||
_notified_once.add(once_key)
|
|
||||||
try:
|
try:
|
||||||
await session.commit()
|
await session.commit()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return sent
|
return sent
|
||||||
|
|
||||||
|
|
||||||
async def list_alerts(
|
|
||||||
*,
|
|
||||||
geofence_id: str | None = None,
|
|
||||||
since: datetime | None = None,
|
|
||||||
until: datetime | None = None,
|
|
||||||
source_kind: str | None = None,
|
|
||||||
limit: int = 100,
|
|
||||||
) -> list[dict]:
|
|
||||||
"""Filterable hit log. Empty list if the DB is down — never raises."""
|
|
||||||
where = ["TRUE"]
|
|
||||||
params: dict[str, Any] = {"limit": int(limit)}
|
|
||||||
if geofence_id:
|
|
||||||
where.append("geofence_id = CAST(:geofence_id AS uuid)")
|
|
||||||
params["geofence_id"] = geofence_id
|
|
||||||
if since is not None:
|
|
||||||
where.append("created_at >= :since")
|
|
||||||
params["since"] = since
|
|
||||||
if until is not None:
|
|
||||||
where.append("created_at <= :until")
|
|
||||||
params["until"] = until
|
|
||||||
if source_kind:
|
|
||||||
where.append("source_kind = :source_kind")
|
|
||||||
params["source_kind"] = source_kind
|
|
||||||
sql = f"""
|
|
||||||
SELECT id::text, geofence_id::text, source_kind, entity_id,
|
|
||||||
lat, lon, payload, created_at
|
|
||||||
FROM geofence_alerts
|
|
||||||
WHERE {' AND '.join(where)}
|
|
||||||
ORDER BY created_at DESC
|
|
||||||
LIMIT :limit
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
async with async_session() as session:
|
|
||||||
rows = (await session.execute(text(sql), params)).mappings().all()
|
|
||||||
out = []
|
|
||||||
for r in rows:
|
|
||||||
item = dict(r)
|
|
||||||
if item.get("created_at") is not None:
|
|
||||||
item["created_at"] = item["created_at"].isoformat()
|
|
||||||
out.append(item)
|
|
||||||
return out
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
async def get_geofence(gid: str) -> dict | None:
|
|
||||||
current = next((f for f in _cache if f["id"] == gid), None)
|
|
||||||
if current is not None:
|
|
||||||
return current
|
|
||||||
try:
|
|
||||||
await refresh_cache()
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
return next((f for f in _cache if f["id"] == gid), None)
|
|
||||||
|
|
||||||
|
|
||||||
def _marker_from_track(row) -> dict:
|
|
||||||
from live_layers import to_marker
|
|
||||||
|
|
||||||
extra = {"bucket": row["bucket"].isoformat() if row.get("bucket") else None, "dvr": True}
|
|
||||||
return to_marker(
|
|
||||||
row["id"], row["lat"], row["lon"],
|
|
||||||
heading=row.get("heading"), speed=row.get("speed"),
|
|
||||||
label=row.get("label") or row["id"],
|
|
||||||
extra=extra,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def _cagg_inside(gid: str, kind: str, bucket: datetime, limit: int = 2000) -> list[dict]:
|
|
||||||
table = "aircraft_tracks_1min" if kind == "aircraft" else "vessel_tracks_1min"
|
|
||||||
id_col = "hex" if kind == "aircraft" else "mmsi"
|
|
||||||
sql = f"""
|
|
||||||
SELECT {id_col} AS id, lat, lon, heading, speed, label, bucket
|
|
||||||
FROM {table}
|
|
||||||
WHERE bucket = :bucket
|
|
||||||
AND ST_Intersects(
|
|
||||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
|
||||||
ST_SetSRID(ST_MakePoint(lon, lat), 4326)
|
|
||||||
)
|
|
||||||
LIMIT :limit
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
async with async_session() as session:
|
|
||||||
rows = (await session.execute(
|
|
||||||
text(sql), {"bucket": bucket, "gid": gid, "limit": limit},
|
|
||||||
)).mappings().all()
|
|
||||||
return [
|
|
||||||
_marker_from_track(r)
|
|
||||||
for r in rows
|
|
||||||
if r["lat"] is not None and r["lon"] is not None
|
|
||||||
]
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
async def _fires_inside(gid: str, ts: datetime, limit: int = 2000) -> list[dict]:
|
|
||||||
from tracks import minute_bucket
|
|
||||||
|
|
||||||
bucket = minute_bucket(ts)
|
|
||||||
t1 = bucket + timedelta(minutes=1)
|
|
||||||
sql = """
|
|
||||||
SELECT latitude, longitude, brightness, confidence, acq_time, satellite,
|
|
||||||
instrument, bright_ti5, frp, daynight
|
|
||||||
FROM fires
|
|
||||||
WHERE acq_time >= :t0 AND acq_time < :t1
|
|
||||||
AND ST_Intersects(
|
|
||||||
(SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)),
|
|
||||||
ST_SetSRID(ST_MakePoint(longitude, latitude), 4326)
|
|
||||||
)
|
|
||||||
LIMIT :limit
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
async with async_session() as session:
|
|
||||||
rows = (await session.execute(
|
|
||||||
text(sql),
|
|
||||||
{"t0": bucket, "t1": t1, "gid": gid, "limit": limit},
|
|
||||||
)).mappings().all()
|
|
||||||
out = []
|
|
||||||
for r in rows:
|
|
||||||
item = dict(r)
|
|
||||||
if item.get("acq_time") is not None:
|
|
||||||
item["acq_time"] = item["acq_time"].isoformat()
|
|
||||||
out.append(item)
|
|
||||||
return out
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
|
|
||||||
async def snapshot_at(gid: str, ts: datetime) -> dict | None:
|
|
||||||
"""Positions inside the fence at time T. None if the fence is missing.
|
|
||||||
|
|
||||||
Does not persist or notify. Empty lists if track/fire queries fail.
|
|
||||||
"""
|
|
||||||
fence = await get_geofence(gid)
|
|
||||||
if fence is None:
|
|
||||||
return None
|
|
||||||
from tracks import minute_bucket
|
|
||||||
|
|
||||||
bucket = minute_bucket(ts)
|
|
||||||
aircraft = await _cagg_inside(gid, "aircraft", bucket)
|
|
||||||
vessels = await _cagg_inside(gid, "vessel", bucket)
|
|
||||||
fires = await _fires_inside(gid, ts)
|
|
||||||
return {
|
|
||||||
"geofence_id": gid,
|
|
||||||
"timestamp": ts.isoformat(),
|
|
||||||
"aircraft": aircraft,
|
|
||||||
"vessels": vessels,
|
|
||||||
"fires": fires,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
_QUAKE_SCAN_SQL = """
|
|
||||||
SELECT id::text AS id, url, title, location_lat, location_lon, raw
|
|
||||||
FROM events
|
|
||||||
WHERE source_type = 'earthquake'
|
|
||||||
AND location_lat IS NOT NULL
|
|
||||||
AND location_lon IS NOT NULL
|
|
||||||
AND source_timestamp >= now() - interval '7 days'
|
|
||||||
ORDER BY source_timestamp DESC
|
|
||||||
LIMIT :limit
|
|
||||||
"""
|
|
||||||
|
|
||||||
# Same pin set as GET /api/news/map: kind=map, flagged, coords, last 24h.
|
|
||||||
_NEWS_SCAN_SQL = """
|
|
||||||
SELECT id::text AS id, headline, url, importance, lat, lon
|
|
||||||
FROM news_items
|
|
||||||
WHERE kind = 'map'
|
|
||||||
AND lat IS NOT NULL
|
|
||||||
AND lon IS NOT NULL
|
|
||||||
AND importance IN ('critical', 'high')
|
|
||||||
AND created_at >= now() - interval '24 hours'
|
|
||||||
ORDER BY created_at DESC
|
|
||||||
LIMIT :limit
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
async def scan_earthquakes(limit: int = 200) -> int:
|
|
||||||
"""Catch-up: quakes already in ``events`` when a fence is drawn later."""
|
|
||||||
try:
|
|
||||||
rows = await _rows(_QUAKE_SCAN_SQL, {"limit": int(limit)})
|
|
||||||
except Exception:
|
|
||||||
logger.exception("earthquake geofence scan failed")
|
|
||||||
return 0
|
|
||||||
n = 0
|
|
||||||
for row in rows:
|
|
||||||
lat, lon = row.get("location_lat"), row.get("location_lon")
|
|
||||||
if lat is None or lon is None:
|
|
||||||
continue
|
|
||||||
eid = earthquake_entity_id(row)
|
|
||||||
if not eid:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
n += await record_and_notify(
|
|
||||||
source_kind="earthquake",
|
|
||||||
entity_id=eid,
|
|
||||||
lat=float(lat),
|
|
||||||
lon=float(lon),
|
|
||||||
payload={"title": row.get("title"), "url": row.get("url") or ""},
|
|
||||||
skip_existing=True,
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
logger.exception("earthquake geofence notify failed entity=%s", eid)
|
|
||||||
return n
|
|
||||||
|
|
||||||
|
|
||||||
async def scan_news_pins(limit: int = 200) -> int:
|
|
||||||
"""Read ``news_items`` map pins. Does not import the summarizer."""
|
|
||||||
try:
|
|
||||||
rows = await _rows(_NEWS_SCAN_SQL, {"limit": int(limit)})
|
|
||||||
except Exception:
|
|
||||||
logger.exception("news geofence scan failed")
|
|
||||||
return 0
|
|
||||||
n = 0
|
|
||||||
for row in rows:
|
|
||||||
lat, lon = row.get("lat"), row.get("lon")
|
|
||||||
if lat is None or lon is None:
|
|
||||||
continue
|
|
||||||
eid = str(row.get("id") or "")
|
|
||||||
if not eid:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
n += await record_and_notify(
|
|
||||||
source_kind="news",
|
|
||||||
entity_id=eid,
|
|
||||||
lat=float(lat),
|
|
||||||
lon=float(lon),
|
|
||||||
payload={
|
|
||||||
"headline": row.get("headline") or "",
|
|
||||||
"url": row.get("url") or "",
|
|
||||||
"importance": row.get("importance") or "",
|
|
||||||
},
|
|
||||||
skip_existing=True,
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
logger.exception("news geofence notify failed entity=%s", eid)
|
|
||||||
return n
|
|
||||||
|
|
||||||
|
|
||||||
async def poll_fire_incidents(fences: list[dict] | None = None) -> int:
|
|
||||||
"""WFIGS incidents are not stored. Fetch each active fence's bbox.
|
|
||||||
|
|
||||||
``load_fire_incidents`` does not mutate the map cache or correlate
|
|
||||||
aircraft. A point in the bbox but outside the polygon is dropped
|
|
||||||
before ``record_and_notify``; ST_Intersects is still the write guard.
|
|
||||||
"""
|
|
||||||
if fences is None:
|
|
||||||
fences = [f for f in cached_fences() if f.get("active", True)]
|
|
||||||
from live_layers import load_fire_incidents
|
|
||||||
|
|
||||||
n = 0
|
|
||||||
seen: set[str] = set()
|
|
||||||
for fence in fences:
|
|
||||||
if not fence.get("active", True):
|
|
||||||
continue
|
|
||||||
bbox = polygon_bbox(fence.get("geojson") or {})
|
|
||||||
if not bbox:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
incidents = await load_fire_incidents(bbox)
|
|
||||||
except Exception:
|
|
||||||
logger.exception("wfigs fence poll failed bbox=%s", bbox)
|
|
||||||
continue
|
|
||||||
if not isinstance(incidents, list):
|
|
||||||
continue
|
|
||||||
for inc in incidents:
|
|
||||||
if not isinstance(inc, dict):
|
|
||||||
continue
|
|
||||||
lat, lon = inc.get("lat"), inc.get("lon")
|
|
||||||
if lat is None or lon is None:
|
|
||||||
continue
|
|
||||||
if not point_in_geojson(float(lon), float(lat), fence.get("geojson") or {}):
|
|
||||||
continue
|
|
||||||
eid = fire_incident_entity_id(inc)
|
|
||||||
if not eid or eid in seen:
|
|
||||||
continue
|
|
||||||
seen.add(eid)
|
|
||||||
try:
|
|
||||||
n += await record_and_notify(
|
|
||||||
source_kind="fire_incident",
|
|
||||||
entity_id=eid,
|
|
||||||
lat=float(lat),
|
|
||||||
lon=float(lon),
|
|
||||||
payload={
|
|
||||||
"label": inc.get("label"),
|
|
||||||
"extra": inc.get("extra") or {},
|
|
||||||
},
|
|
||||||
skip_existing=True,
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
logger.exception("fire_incident geofence notify failed entity=%s", eid)
|
|
||||||
return n
|
|
||||||
|
|
||||||
|
|
||||||
async def scan_geofence_feeds() -> int:
|
|
||||||
"""Ingester-loop catch-up. No-op when no active fence is cached.
|
|
||||||
|
|
||||||
Earthquakes also notify on insert (``ingestor.ingest_event``). This
|
|
||||||
scan covers rows already stored, WFIGS (not persisted), and news
|
|
||||||
pins written by the summarizer process.
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
await refresh_cache()
|
|
||||||
except Exception:
|
|
||||||
logger.exception("geofence cache refresh failed")
|
|
||||||
fences = [f for f in cached_fences() if f.get("active", True)]
|
|
||||||
if not fences:
|
|
||||||
return 0
|
|
||||||
n = 0
|
|
||||||
n += await scan_earthquakes()
|
|
||||||
n += await scan_news_pins()
|
|
||||||
n += await poll_fire_incidents(fences)
|
|
||||||
return n
|
|
||||||
|
|
|
||||||
|
|
@ -219,32 +219,9 @@ async def ingest_event(msg: dict):
|
||||||
await session.commit()
|
await session.commit()
|
||||||
event_id = result.inserted_primary_key[0] # type: ignore[union-attr]
|
event_id = result.inserted_primary_key[0] # type: ignore[union-attr]
|
||||||
logger.info("Ingested event %s from source %s", event_id, msg.get("source_type"))
|
logger.info("Ingested event %s from source %s", event_id, msg.get("source_type"))
|
||||||
# Cameras are persisted as events only. Never a geofence hit.
|
|
||||||
if event_row["source_type"] == "earthquake":
|
|
||||||
await _notify_earthquake(event_row, event_id)
|
|
||||||
return event_id
|
return event_id
|
||||||
|
|
||||||
|
|
||||||
async def _notify_earthquake(event_row: dict, event_id) -> None:
|
|
||||||
"""One hit per new quake. Dedup already dropped replays; skip if no point."""
|
|
||||||
lat, lon = event_row.get("location_lat"), event_row.get("location_lon")
|
|
||||||
if lat is None or lon is None:
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
from geofence import earthquake_entity_id, record_and_notify
|
|
||||||
row = {**event_row, "id": str(event_id)}
|
|
||||||
await record_and_notify(
|
|
||||||
source_kind="earthquake",
|
|
||||||
entity_id=earthquake_entity_id(row),
|
|
||||||
lat=float(lat),
|
|
||||||
lon=float(lon),
|
|
||||||
payload={"title": event_row.get("title"), "url": event_row.get("url") or ""},
|
|
||||||
skip_existing=True,
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
logger.exception("earthquake geofence notify failed")
|
|
||||||
|
|
||||||
|
|
||||||
async def start_nats_consumer():
|
async def start_nats_consumer():
|
||||||
"""Start NATS JetStream consumer for OSINT events."""
|
"""Start NATS JetStream consumer for OSINT events."""
|
||||||
nc = await nats.connect(NATS_URLS)
|
nc = await nats.connect(NATS_URLS)
|
||||||
|
|
|
||||||
|
|
@ -155,12 +155,6 @@ def overlay_catalog() -> dict:
|
||||||
"endpoint": "/api/map/gpsjam",
|
"endpoint": "/api/map/gpsjam",
|
||||||
"attribution": "GPSJAM / John Wiseman / ADS-B Exchange",
|
"attribution": "GPSJAM / John Wiseman / ADS-B Exchange",
|
||||||
},
|
},
|
||||||
"satellites": {
|
|
||||||
"id": "satellites",
|
|
||||||
"kind": "points",
|
|
||||||
"endpoint": "/api/satellites",
|
|
||||||
"attribution": "CelesTrak (GP JSON / SGP4)",
|
|
||||||
},
|
|
||||||
"infra_nuclear": {
|
"infra_nuclear": {
|
||||||
"id": "infra_nuclear",
|
"id": "infra_nuclear",
|
||||||
"kind": "points",
|
"kind": "points",
|
||||||
|
|
@ -743,25 +737,18 @@ def transform_wfigs_incidents(fc: dict | None) -> list[dict]:
|
||||||
continue
|
continue
|
||||||
props = feat.get("properties") or {}
|
props = feat.get("properties") or {}
|
||||||
name = str(props.get("IncidentName") or "Incident").strip()
|
name = str(props.get("IncidentName") or "Incident").strip()
|
||||||
extra = {
|
|
||||||
"acres": props.get("IncidentSize"),
|
|
||||||
"contained": props.get("PercentContained"),
|
|
||||||
"state": props.get("POOState"),
|
|
||||||
"category": props.get("IncidentTypeCategory"),
|
|
||||||
"cause": props.get("FireCause"),
|
|
||||||
"discovered": props.get("FireDiscoveryDateTime"),
|
|
||||||
"src": "wfigs",
|
|
||||||
}
|
|
||||||
irwin = props.get("IrwinID")
|
|
||||||
if irwin:
|
|
||||||
extra["irwin_id"] = str(irwin)
|
|
||||||
ufi = props.get("UniqueFireIdentifier")
|
|
||||||
if ufi:
|
|
||||||
extra["unique_fire_id"] = str(ufi)
|
|
||||||
out.append(to_marker(
|
out.append(to_marker(
|
||||||
name, lat, lon,
|
name, lat, lon,
|
||||||
label=name,
|
label=name,
|
||||||
extra=extra,
|
extra={
|
||||||
|
"acres": props.get("IncidentSize"),
|
||||||
|
"contained": props.get("PercentContained"),
|
||||||
|
"state": props.get("POOState"),
|
||||||
|
"category": props.get("IncidentTypeCategory"),
|
||||||
|
"cause": props.get("FireCause"),
|
||||||
|
"discovered": props.get("FireDiscoveryDateTime"),
|
||||||
|
"src": "wfigs",
|
||||||
|
},
|
||||||
))
|
))
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
@ -1091,27 +1078,17 @@ def _wfigs_params(bbox: str | None, *, offset_m: float = 250.0) -> dict:
|
||||||
return params
|
return params
|
||||||
|
|
||||||
|
|
||||||
_WFIGS_INCIDENT_FIELDS = (
|
async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]:
|
||||||
"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."""
|
|
||||||
params = _wfigs_params(bbox)
|
params = _wfigs_params(bbox)
|
||||||
params["outFields"] = _WFIGS_INCIDENT_FIELDS
|
params["outFields"] = (
|
||||||
|
"IncidentName,IncidentSize,FireDiscoveryDateTime,POOState,"
|
||||||
|
"PercentContained,IncidentTypeCategory,FireCause"
|
||||||
|
)
|
||||||
|
|
||||||
async def _load():
|
async def _load():
|
||||||
return transform_wfigs_incidents(await _get_json(WFIGS_INCIDENTS, params))
|
return transform_wfigs_incidents(await _get_json(WFIGS_INCIDENTS, params))
|
||||||
|
|
||||||
rows = await _ttl_get(f"wfigs:inc:{bbox_cell_key(bbox)}", 600.0, _load)
|
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)
|
fire_last_known[:] = list(rows)
|
||||||
if rows and aircraft_last_known:
|
if rows and aircraft_last_known:
|
||||||
from fire_aircraft import correlate_and_notify
|
from fire_aircraft import correlate_and_notify
|
||||||
|
|
|
||||||
384
app/main.py
384
app/main.py
|
|
@ -21,12 +21,11 @@ from datetime import datetime, timedelta, timezone
|
||||||
from decimal import Decimal
|
from decimal import Decimal
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import NoReturn
|
from typing import NoReturn
|
||||||
from urllib.parse import urlparse
|
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import structlog
|
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.middleware.gzip import GZipMiddleware
|
||||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
|
@ -34,18 +33,17 @@ from sqlalchemy import and_, func, or_, select, text
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from database import async_session, init_extensions
|
from database import async_session, init_extensions
|
||||||
from auth import AdminAuthMiddleware, router as auth_router
|
|
||||||
from models import (
|
from models import (
|
||||||
alerts, documents, entities, entity_events, events, feed_sources, fires,
|
alerts, documents, entities, entity_events, events, feed_sources, fires,
|
||||||
articles, article_scores, article_summaries, news_items,
|
articles, article_summaries, news_items,
|
||||||
)
|
)
|
||||||
from schemas import (
|
from schemas import (
|
||||||
AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate,
|
AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate,
|
||||||
ConflictZoneOut, ConflictsOut,
|
ConflictZoneOut, ConflictsOut,
|
||||||
DashboardSummary, EntityCreate, EntityKind, EntityOut,
|
DashboardSummary, EntityCreate, EntityKind, EntityOut,
|
||||||
EventCreate, EventOut, FireOut, NewsArticleOut, NewsBlipOut, NewsMapItemOut,
|
EventCreate, EventOut, FireOut, NewsArticleOut, NewsMapItemOut,
|
||||||
NewsSummaryOut, NewsTickerItemOut,
|
NewsSummaryOut, NewsTickerItemOut,
|
||||||
FeedSourceCreate, FeedSourceOut, FeedSourceUpdate,
|
FeedSourceCreate, FeedSourceOut,
|
||||||
KeyOut, KeyValueIn,
|
KeyOut, KeyValueIn,
|
||||||
NewsModelsOut, SettingsIn, SettingsOut,
|
NewsModelsOut, SettingsIn, SettingsOut,
|
||||||
SearchResult, SentimentSummary, SourceType,
|
SearchResult, SentimentSummary, SourceType,
|
||||||
|
|
@ -53,11 +51,9 @@ from schemas import (
|
||||||
GeofenceCreate, GeofenceUpdate,
|
GeofenceCreate, GeofenceUpdate,
|
||||||
)
|
)
|
||||||
from ingestor import ingest_event, fetch_and_process
|
from ingestor import ingest_event, fetch_and_process
|
||||||
from camera_scraper import is_public_url
|
from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals
|
||||||
from sources import GDELT_API, ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals
|
|
||||||
from fire_sources import ingest_fires
|
from fire_sources import ingest_fires
|
||||||
from keystore import KeyFormatError, delete_key, list_keys, set_key
|
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 settings_store import SettingsError, get_app_settings, list_models, set_summary_model
|
||||||
from live_layers import (
|
from live_layers import (
|
||||||
fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters,
|
fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters,
|
||||||
|
|
@ -65,7 +61,6 @@ from live_layers import (
|
||||||
fetch_storms, fetch_trains, fetch_vessels, fetch_weather_alerts,
|
fetch_storms, fetch_trains, fetch_vessels, fetch_weather_alerts,
|
||||||
fetch_infrastructure, overlay_catalog, parse_bbox, UpstreamRateLimited,
|
fetch_infrastructure, overlay_catalog, parse_bbox, UpstreamRateLimited,
|
||||||
)
|
)
|
||||||
from satellites import fetch_satellites, parse_groups, DEFAULT_GROUPS
|
|
||||||
from place import reverse_geocode
|
from place import reverse_geocode
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
|
@ -118,57 +113,17 @@ app = FastAPI(
|
||||||
)
|
)
|
||||||
app.add_middleware(GZipMiddleware, minimum_size=1024)
|
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"
|
STATIC_DIR = Path(__file__).parent / "static"
|
||||||
|
|
||||||
|
|
||||||
def _adsb_watch_boxes() -> list[tuple[float, float, float, float]]:
|
|
||||||
"""Chokepoint presets as viewport boxes (minlon, minlat, maxlon, maxlat).
|
|
||||||
|
|
||||||
Used only while no browser viewport is registered: without it the refresh
|
|
||||||
loop persists nothing and ``aircraft_positions`` silently stalls whenever
|
|
||||||
nobody has the map open.
|
|
||||||
"""
|
|
||||||
from chokepoints import chokepoints
|
|
||||||
|
|
||||||
out: list[tuple[float, float, float, float]] = []
|
|
||||||
for preset in chokepoints():
|
|
||||||
try:
|
|
||||||
# Preset bboxes are minlat,minlon,maxlat,maxlon (VesselAPI order).
|
|
||||||
minlat, minlon, maxlat, maxlon = (float(v) for v in str(preset["bbox"]).split(","))
|
|
||||||
except (KeyError, TypeError, ValueError):
|
|
||||||
continue
|
|
||||||
out.append((minlon, minlat, maxlon, maxlat))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
async def _adsb_refresh_loop() -> None:
|
async def _adsb_refresh_loop() -> None:
|
||||||
"""Poll ADSB.lol for connected viewports — never from GET /api/aircraft.
|
"""Poll ADSB.lol for connected viewports — never from GET /api/aircraft."""
|
||||||
|
|
||||||
When no client viewport is registered the loop sweeps the watch boxes
|
|
||||||
(chokepoint presets) at ``ADSB_WATCH_INTERVAL`` so aircraft ingest keeps
|
|
||||||
advancing with no map open.
|
|
||||||
"""
|
|
||||||
from ws_manager import manager
|
from ws_manager import manager
|
||||||
from live_layers import fetch_aircraft
|
from live_layers import fetch_aircraft
|
||||||
from config import ADSB_REFRESH_INTERVAL, ADSB_WATCH_ENABLED, ADSB_WATCH_INTERVAL
|
|
||||||
|
|
||||||
watch_boxes: list[tuple[float, float, float, float]] | None = None
|
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
interval = ADSB_REFRESH_INTERVAL
|
|
||||||
try:
|
try:
|
||||||
boxes = manager.viewports()
|
boxes = manager.viewports()
|
||||||
if not boxes and ADSB_WATCH_ENABLED:
|
|
||||||
if watch_boxes is None:
|
|
||||||
watch_boxes = _adsb_watch_boxes()
|
|
||||||
boxes = watch_boxes
|
|
||||||
interval = ADSB_WATCH_INTERVAL
|
|
||||||
logger.debug("adsb_idle_watch", boxes=len(boxes))
|
|
||||||
for box in boxes:
|
for box in boxes:
|
||||||
bbox = f"{box[0]},{box[1]},{box[2]},{box[3]}"
|
bbox = f"{box[0]},{box[1]},{box[2]},{box[3]}"
|
||||||
try:
|
try:
|
||||||
|
|
@ -177,7 +132,7 @@ async def _adsb_refresh_loop() -> None:
|
||||||
logger.warning("adsb_refresh_failed", error=str(exc))
|
logger.warning("adsb_refresh_failed", error=str(exc))
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
logger.warning("adsb_refresh_loop", error=str(exc))
|
logger.warning("adsb_refresh_loop", error=str(exc))
|
||||||
await asyncio.sleep(interval)
|
await asyncio.sleep(8)
|
||||||
|
|
||||||
|
|
||||||
class CachedStaticFiles(StaticFiles):
|
class CachedStaticFiles(StaticFiles):
|
||||||
|
|
@ -308,14 +263,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 events", "events", 20 * 60)
|
||||||
await _age("SELECT max(ingested_at) FROM fires", "fires", 30 * 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
|
await _age("SELECT max(timestamp) FROM articles", "articles", 2 * 3600)
|
||||||
# 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(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600)
|
await _age("SELECT max(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600)
|
||||||
return checks
|
return checks
|
||||||
|
|
||||||
|
|
@ -341,7 +289,7 @@ async def _stats_counts() -> dict:
|
||||||
aircraft_last_known, vessel_last_known, train_count, nws_alert_count,
|
aircraft_last_known, vessel_last_known, train_count, nws_alert_count,
|
||||||
)
|
)
|
||||||
|
|
||||||
counts: dict = {
|
counts: dict[str, int | str] = {
|
||||||
"aircraft": len(aircraft_last_known),
|
"aircraft": len(aircraft_last_known),
|
||||||
"vessels": len(vessel_last_known),
|
"vessels": len(vessel_last_known),
|
||||||
"trains": train_count,
|
"trains": train_count,
|
||||||
|
|
@ -373,41 +321,9 @@ async def _stats_counts() -> dict:
|
||||||
logger.warning("stats_db_failed", error=str(exc))
|
logger.warning("stats_db_failed", error=str(exc))
|
||||||
|
|
||||||
counts["timestamp"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
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
|
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")
|
@app.get("/api/stats")
|
||||||
async def api_stats():
|
async def api_stats():
|
||||||
"""Cheap HUD counters (counts only — no GeoJSON). Cached ~20 s."""
|
"""Cheap HUD counters (counts only — no GeoJSON). Cached ~20 s."""
|
||||||
|
|
@ -449,22 +365,20 @@ async def create_source(payload: FeedSourceCreate):
|
||||||
|
|
||||||
|
|
||||||
@app.patch("/api/sources/{source_id}")
|
@app.patch("/api/sources/{source_id}")
|
||||||
async def update_source(source_id: UUID, payload: FeedSourceUpdate):
|
async def update_source(source_id: UUID, payload: dict):
|
||||||
"""Update a feed source (name/url/config/enabled only)."""
|
"""Update a feed source (e.g., toggle enabled)."""
|
||||||
values = payload.model_dump(exclude_unset=True)
|
|
||||||
async with async_session() as session:
|
async with async_session() as session:
|
||||||
row = (await session.execute(
|
row = (await session.execute(
|
||||||
select(feed_sources).where(feed_sources.c.id == source_id)
|
select(feed_sources).where(feed_sources.c.id == source_id)
|
||||||
)).mappings().one_or_none()
|
)).mappings().one_or_none()
|
||||||
if not row:
|
if not row:
|
||||||
raise HTTPException(404, "Source not found")
|
raise HTTPException(404, "Source not found")
|
||||||
if values:
|
await session.execute(
|
||||||
await session.execute(
|
feed_sources.update()
|
||||||
feed_sources.update()
|
.where(feed_sources.c.id == source_id)
|
||||||
.where(feed_sources.c.id == source_id)
|
.values(**payload)
|
||||||
.values(**values)
|
)
|
||||||
)
|
await session.commit()
|
||||||
await session.commit()
|
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -907,15 +821,9 @@ async def put_settings(payload: SettingsIn):
|
||||||
|
|
||||||
# ── Ingestion Triggers ───────────────────────────────────────────────────
|
# ── 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")
|
@app.post("/api/ingest/rss")
|
||||||
async def trigger_rss_ingest(feed_url: str, source_id: str | None = None):
|
async def trigger_rss_ingest(feed_url: str, source_id: str | None = None):
|
||||||
"""Trigger RSS feed ingestion."""
|
"""Trigger RSS feed ingestion."""
|
||||||
_require_public_url(feed_url, "feed_url")
|
|
||||||
count = await ingest_rss_feed(feed_url, source_id)
|
count = await ingest_rss_feed(feed_url, source_id)
|
||||||
return {"status": "ok", "items_ingested": count}
|
return {"status": "ok", "items_ingested": count}
|
||||||
|
|
||||||
|
|
@ -923,10 +831,6 @@ async def trigger_rss_ingest(feed_url: str, source_id: str | None = None):
|
||||||
@app.post("/api/ingest/gdelt")
|
@app.post("/api/ingest/gdelt")
|
||||||
async def trigger_gdelt_ingest(query: str = "", max_articles: int = 50):
|
async def trigger_gdelt_ingest(query: str = "", max_articles: int = 50):
|
||||||
"""Trigger GDELT data ingestion."""
|
"""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)
|
count = await ingest_gdelt(query, max_articles)
|
||||||
return {"status": "ok", "articles_ingested": count}
|
return {"status": "ok", "articles_ingested": count}
|
||||||
|
|
||||||
|
|
@ -952,16 +856,24 @@ async def trigger_social_ingest(query: str = "", max_items: int = 50):
|
||||||
return {"status": "ok", "signals_ingested": count}
|
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")
|
@app.websocket("/ws/live")
|
||||||
async def live_ws(ws: WebSocket):
|
async def live_ws(ws: WebSocket):
|
||||||
"""Viewport-filtered AIS/ADS-B fan-out.
|
"""Viewport-filtered AIS/ADS-B fan-out. Client sends {type:viewport,bbox}."""
|
||||||
|
|
||||||
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.
|
|
||||||
"""
|
|
||||||
from ws_manager import manager
|
from ws_manager import manager
|
||||||
|
|
||||||
client_id = str(id(ws))
|
client_id = str(id(ws))
|
||||||
|
|
@ -987,10 +899,6 @@ async def live_ws(ws: WebSocket):
|
||||||
manager.set_viewport(client_id, parse_bbox(str(data["bbox"])))
|
manager.set_viewport(client_id, parse_bbox(str(data["bbox"])))
|
||||||
except ValueError:
|
except ValueError:
|
||||||
continue
|
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:
|
except WebSocketDisconnect:
|
||||||
pass
|
pass
|
||||||
finally:
|
finally:
|
||||||
|
|
@ -1142,7 +1050,7 @@ async def list_cameras(
|
||||||
True,
|
True,
|
||||||
description="Only cameras with a verified HTTP/MJPEG snapshot_url "
|
description="Only cameras with a verified HTTP/MJPEG snapshot_url "
|
||||||
"(the ones that actually preview). Set false to include "
|
"(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),
|
limit: int = Query(500, ge=1, le=5000),
|
||||||
):
|
):
|
||||||
|
|
@ -1219,7 +1127,7 @@ async def get_camera(camera_id: UUID):
|
||||||
async def camera_snapshot(camera_id: UUID):
|
async def camera_snapshot(camera_id: UUID):
|
||||||
"""Still image for one camera.
|
"""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
|
snapshot_url — we probe common still-image paths and, failing that, grab
|
||||||
one JPEG frame from RTSP via ffmpeg. No credentials are tried.
|
one JPEG frame from RTSP via ffmpeg. No credentials are tried.
|
||||||
"""
|
"""
|
||||||
|
|
@ -1368,12 +1276,7 @@ async def list_news(
|
||||||
):
|
):
|
||||||
"""Most recent scraped news articles (newest first)."""
|
"""Most recent scraped news articles (newest first)."""
|
||||||
async with async_session() as session:
|
async with async_session() as session:
|
||||||
stmt = select(articles).where(
|
stmt = select(articles).order_by(
|
||||||
or_(
|
|
||||||
articles.c.timestamp.is_(None),
|
|
||||||
articles.c.timestamp <= func.now(),
|
|
||||||
)
|
|
||||||
).order_by(
|
|
||||||
articles.c.timestamp.desc().nullslast()
|
articles.c.timestamp.desc().nullslast()
|
||||||
)
|
)
|
||||||
if domain:
|
if domain:
|
||||||
|
|
@ -1384,7 +1287,7 @@ async def list_news(
|
||||||
rows = (await session.execute(stmt)).mappings().all()
|
rows = (await session.execute(stmt)).mappings().all()
|
||||||
return [
|
return [
|
||||||
NewsArticleOut(
|
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"],
|
content=r["content"] if include_content else None, domain=r["domain"],
|
||||||
timestamp=r["timestamp"],
|
timestamp=r["timestamp"],
|
||||||
)
|
)
|
||||||
|
|
@ -1537,94 +1440,6 @@ async def list_news_map(
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/news/blips", response_model=list[NewsBlipOut])
|
|
||||||
async def list_news_blips(
|
|
||||||
bbox: str | None = Query(
|
|
||||||
None,
|
|
||||||
description="Comma-separated 'minlon,minlat,maxlon,maxlat' to bound the "
|
|
||||||
"result set by article coordinates. Omit for all blips.",
|
|
||||||
),
|
|
||||||
since: datetime | None = Query(
|
|
||||||
None,
|
|
||||||
description="Only gradings created at/after this UTC instant. "
|
|
||||||
"Defaults to the last 24 hours.",
|
|
||||||
),
|
|
||||||
limit: int = Query(1000, ge=1, le=5000),
|
|
||||||
):
|
|
||||||
"""Per-article proximate geo blips: EVERY graded article with a derivable
|
|
||||||
location (not just the critical/high map pins). Deduped by article id —
|
|
||||||
the latest grading's geo wins. Only finite lat/lon rows, newest first.
|
|
||||||
"""
|
|
||||||
if since is None:
|
|
||||||
since = datetime.now(timezone.utc) - timedelta(hours=24)
|
|
||||||
async with async_session() as session:
|
|
||||||
# DISTINCT ON (article_id) + ORDER BY article_id, created_at DESC
|
|
||||||
# keeps the latest grading per article; the outer query re-sorts
|
|
||||||
# newest-first and applies the limit. NaN is excluded explicitly:
|
|
||||||
# Postgres sorts NaN above every finite value, so range checks
|
|
||||||
# alone would let it through. prefix_with keeps this renderable on
|
|
||||||
# both SQLAlchemy 2.0 and 2.1 (requirements pin >=2.0).
|
|
||||||
stmt = (
|
|
||||||
select(
|
|
||||||
article_scores.c.article_id.label("id"),
|
|
||||||
articles.c.title.label("headline"),
|
|
||||||
articles.c.url,
|
|
||||||
articles.c.domain,
|
|
||||||
article_scores.c.location_name,
|
|
||||||
article_scores.c.lat,
|
|
||||||
article_scores.c.lon,
|
|
||||||
article_scores.c.location_confidence,
|
|
||||||
article_scores.c.category,
|
|
||||||
article_scores.c.score,
|
|
||||||
article_scores.c.created_at,
|
|
||||||
)
|
|
||||||
.select_from(
|
|
||||||
article_scores.join(articles, articles.c.id == article_scores.c.article_id)
|
|
||||||
)
|
|
||||||
.where(
|
|
||||||
article_scores.c.lat.isnot(None),
|
|
||||||
article_scores.c.lon.isnot(None),
|
|
||||||
article_scores.c.lat.between(-90, 90),
|
|
||||||
article_scores.c.lon.between(-180, 180),
|
|
||||||
text("article_scores.lat <> 'NaN'::double precision"),
|
|
||||||
text("article_scores.lon <> 'NaN'::double precision"),
|
|
||||||
article_scores.c.created_at >= since,
|
|
||||||
)
|
|
||||||
.prefix_with("DISTINCT ON (article_scores.article_id)")
|
|
||||||
.order_by(article_scores.c.article_id, article_scores.c.created_at.desc())
|
|
||||||
)
|
|
||||||
if bbox:
|
|
||||||
parts = [p.strip() for p in bbox.split(",")]
|
|
||||||
if len(parts) != 4:
|
|
||||||
raise HTTPException(
|
|
||||||
422, "bbox must be 'minlon,minlat,maxlon,maxlat' (4 comma-separated values)"
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
minlon, minlat, maxlon, maxlat = (float(p) for p in parts)
|
|
||||||
except ValueError:
|
|
||||||
raise HTTPException(
|
|
||||||
422, "bbox values must be floats: 'minlon,minlat,maxlon,maxlat'"
|
|
||||||
)
|
|
||||||
stmt = stmt.where(
|
|
||||||
and_(
|
|
||||||
article_scores.c.lon >= minlon, article_scores.c.lon <= maxlon,
|
|
||||||
article_scores.c.lat >= minlat, article_scores.c.lat <= maxlat,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
latest = stmt.subquery()
|
|
||||||
ordered = select(latest).order_by(latest.c.created_at.desc()).limit(limit)
|
|
||||||
rows = (await session.execute(ordered)).mappings().all()
|
|
||||||
return [
|
|
||||||
NewsBlipOut(
|
|
||||||
id=r["id"], headline=r["headline"] or "", url=r["url"], domain=r["domain"],
|
|
||||||
location_name=r["location_name"], lat=r["lat"], lon=r["lon"],
|
|
||||||
location_confidence=r["location_confidence"], category=r["category"],
|
|
||||||
score=r["score"], created_at=r["created_at"],
|
|
||||||
)
|
|
||||||
for r in rows
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/news/models", response_model=NewsModelsOut)
|
@app.get("/api/news/models", response_model=NewsModelsOut)
|
||||||
async def list_news_models():
|
async def list_news_models():
|
||||||
"""Nous model catalog for the summarizer selector. Never 502s."""
|
"""Nous model catalog for the summarizer selector. Never 502s."""
|
||||||
|
|
@ -1942,83 +1757,33 @@ async def api_update_geofence(gid: str, payload: GeofenceUpdate):
|
||||||
@app.delete("/api/geofences/{gid}", status_code=204)
|
@app.delete("/api/geofences/{gid}", status_code=204)
|
||||||
async def api_delete_geofence(gid: str):
|
async def api_delete_geofence(gid: str):
|
||||||
from geofence import delete_geofence
|
from geofence import delete_geofence
|
||||||
ok = await delete_geofence(gid)
|
await delete_geofence(gid)
|
||||||
if not ok:
|
|
||||||
raise HTTPException(404, "geofence not found")
|
|
||||||
return None
|
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")
|
@app.get("/api/geofence-alerts")
|
||||||
async def api_geofence_alerts(
|
async def api_geofence_alerts(limit: int = Query(100, ge=1, le=500)):
|
||||||
geofence_id: UUID | None = Query(None),
|
from sqlalchemy import text as sql_text
|
||||||
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",
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
since_ts = parse_timestamp(since) if since else None
|
async with async_session() as session:
|
||||||
until_ts = parse_timestamp(until) if until else None
|
rows = (await session.execute(sql_text(
|
||||||
except ValueError as exc:
|
"""
|
||||||
raise HTTPException(422, str(exc)) from exc
|
SELECT id::text, geofence_id::text, source_kind, entity_id,
|
||||||
return await list_alerts(
|
lat, lon, payload, created_at
|
||||||
geofence_id=str(geofence_id) if geofence_id else None,
|
FROM geofence_alerts
|
||||||
since=since_ts,
|
ORDER BY created_at DESC
|
||||||
until=until_ts,
|
LIMIT :limit
|
||||||
source_kind=source_kind,
|
"""
|
||||||
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")
|
@app.get("/api/fire-aircraft")
|
||||||
|
|
@ -2134,35 +1899,6 @@ async def map_gpsjam(
|
||||||
return overlay_json(fc, 3600)
|
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"})
|
_INFRA_TYPES = frozenset({"nuclear"})
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -2226,4 +1962,4 @@ app.mount("/static", CachedStaticFiles(directory=str(STATIC_DIR)), name="static"
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import uvicorn
|
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 uuid import uuid4
|
||||||
|
|
||||||
from sqlalchemy import (
|
from sqlalchemy import (
|
||||||
Boolean, Column, Enum, Float, Index, Integer, String, Text,
|
Column, Enum, Float, Index, Integer, String, Text,
|
||||||
DateTime, JSON, func, Table, PrimaryKeyConstraint,
|
DateTime, JSON, func, Table, PrimaryKeyConstraint,
|
||||||
)
|
)
|
||||||
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
|
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
|
||||||
|
|
@ -242,34 +242,3 @@ news_items = Table(
|
||||||
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
|
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
|
||||||
)
|
)
|
||||||
Index("ix_news_items_kind_created", news_items.c.kind, news_items.c.created_at)
|
Index("ix_news_items_kind_created", news_items.c.kind, news_items.c.created_at)
|
||||||
|
|
||||||
|
|
||||||
# Per-article map-phase grades (alembic 012/013/014). One row per graded
|
|
||||||
# article per run; PK (article_id, created_at) lets re-grades accumulate.
|
|
||||||
# Geo columns are nullable: only articles with a derivable location carry
|
|
||||||
# coordinates, served by GET /api/news/blips.
|
|
||||||
article_scores = Table(
|
|
||||||
"article_scores",
|
|
||||||
metadata,
|
|
||||||
Column("article_id", Integer, nullable=False),
|
|
||||||
Column("summary_id", Integer),
|
|
||||||
Column("score", Integer, nullable=False),
|
|
||||||
Column("category", Text),
|
|
||||||
Column("selected", Boolean, nullable=False),
|
|
||||||
Column("model", Text),
|
|
||||||
Column("duplicate_of", Integer),
|
|
||||||
Column("location_name", Text),
|
|
||||||
Column("lat", Float),
|
|
||||||
Column("lon", Float),
|
|
||||||
Column("location_confidence", Text),
|
|
||||||
Column("created_at", DateTime(timezone=True),
|
|
||||||
server_default=func.now(), nullable=False),
|
|
||||||
PrimaryKeyConstraint("article_id", "created_at"),
|
|
||||||
)
|
|
||||||
Index("ix_article_scores_summary", article_scores.c.summary_id)
|
|
||||||
Index(
|
|
||||||
"ix_article_scores_geo_bbox",
|
|
||||||
article_scores.c.lon, article_scores.c.lat,
|
|
||||||
postgresql_where=article_scores.c.lat.isnot(None)
|
|
||||||
& article_scores.c.lon.isnot(None),
|
|
||||||
)
|
|
||||||
|
|
|
||||||
|
|
@ -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()
|
|
||||||
|
|
@ -13,4 +13,3 @@ structlog>=24.4
|
||||||
websockets>=14
|
websockets>=14
|
||||||
cachetools>=5.5
|
cachetools>=5.5
|
||||||
h3>=4.0
|
h3>=4.0
|
||||||
sgp4>=2.23
|
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,9 @@
|
||||||
"""Long-running camera discovery service.
|
"""Long-running camera discovery service.
|
||||||
|
|
||||||
Discovers cameras on an interval and upserts them into the `cameras` table
|
Follows the existing ingest pattern: discovers cameras on an interval and
|
||||||
(dedupe by url_hash) for the /api/cameras bbox query. Discovery is not an
|
publishes each one as a NATS message (`events.camera`) so the shared NATS ->
|
||||||
event: this process does not publish `events.camera` messages. Those were
|
ingester pipeline persists them; also upserts directly into the `cameras`
|
||||||
inserted as events rows and flooded the HUD feed. The cameras table is the
|
table (dedupe by url_hash) for the /api/cameras bbox query.
|
||||||
index.
|
|
||||||
|
|
||||||
Env:
|
Env:
|
||||||
CAMERA_SOURCE_URLS comma-separated public directory/list URLs
|
CAMERA_SOURCE_URLS comma-separated public directory/list URLs
|
||||||
|
|
@ -15,6 +14,7 @@ Env:
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
@ -22,12 +22,16 @@ from pathlib import Path
|
||||||
sys_path = str(Path(__file__).parent)
|
sys_path = str(Path(__file__).parent)
|
||||||
sys.path.insert(0, sys_path)
|
sys.path.insert(0, sys_path)
|
||||||
|
|
||||||
|
import nats # noqa: E402
|
||||||
|
|
||||||
from camera_config import ( # noqa: E402
|
from camera_config import ( # noqa: E402
|
||||||
CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL,
|
CAMERA_SOURCE_URLS, CAMERA_SCRAPE_INTERVAL, CAMERA_NATS_SUBJECT,
|
||||||
SNAPSHOT_CACHE_DIR,
|
SNAPSHOT_CACHE_DIR,
|
||||||
)
|
)
|
||||||
from camera_scraper import run_cycle # noqa: E402
|
from camera_models import cameras # noqa: E402
|
||||||
from database import init_extensions # noqa: E402
|
from camera_scraper import run_cycle, url_hash # noqa: E402
|
||||||
|
from database import async_session, init_extensions # noqa: E402
|
||||||
|
from config import NATS_URL # noqa: E402
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO,
|
logging.basicConfig(level=logging.INFO,
|
||||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||||
|
|
@ -36,16 +40,48 @@ logger = logging.getLogger("osint.camera_service")
|
||||||
ENABLED = sys.argv[1:] != ["--once"]
|
ENABLED = sys.argv[1:] != ["--once"]
|
||||||
|
|
||||||
|
|
||||||
async def publish_new_cameras(rows: list | None = None) -> int:
|
async def publish_new_cameras() -> int:
|
||||||
"""Do not publish camera discoveries as events.
|
"""Publish cameras seen in the latest cycle to NATS for the ingester."""
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
``run_cycle`` already upserts the cameras table, which backs
|
cutoff = datetime.now(timezone.utc) - timedelta(seconds=CAMERA_SCRAPE_INTERVAL * 2)
|
||||||
``GET /api/cameras``. ``rows`` is newly seen cameras from a cycle or a
|
published = 0
|
||||||
test; none are JetStream-published, so the ingester inserts 0 events
|
try:
|
||||||
with source_type=camera.
|
nc = await nats.connect(NATS_URL)
|
||||||
"""
|
except Exception: # noqa: BLE001
|
||||||
del rows
|
logger.warning("NATS unavailable — skipping publish pass")
|
||||||
return 0
|
return 0
|
||||||
|
try:
|
||||||
|
js = nc.jetstream()
|
||||||
|
async with async_session() as session:
|
||||||
|
rows = (await session.execute(
|
||||||
|
cameras.select().where(cameras.c.last_seen >= cutoff)
|
||||||
|
)).mappings().all()
|
||||||
|
for r in rows:
|
||||||
|
msg = {
|
||||||
|
"source_type": "camera",
|
||||||
|
"title": f"Open camera ({r['vendor'] or 'unknown vendor'})",
|
||||||
|
"url": r["source_url"],
|
||||||
|
"location_lat": r["location_lat"],
|
||||||
|
"location_lon": r["location_lon"],
|
||||||
|
"location_name": r["location_name"],
|
||||||
|
"tags": ["osint", "camera", r["discovery_source"]],
|
||||||
|
"raw": {
|
||||||
|
"url_hash": r["url_hash"],
|
||||||
|
"snapshot_url": r["snapshot_url"],
|
||||||
|
"vendor": r["vendor"],
|
||||||
|
"device_type": r["device_type"],
|
||||||
|
"first_seen": r["first_seen"].isoformat(),
|
||||||
|
"last_seen": r["last_seen"].isoformat(),
|
||||||
|
},
|
||||||
|
"source_timestamp": datetime.now(timezone.utc).isoformat(),
|
||||||
|
}
|
||||||
|
await js.publish(CAMERA_NATS_SUBJECT, json.dumps(msg).encode())
|
||||||
|
published += 1
|
||||||
|
if published >= 500: # per-cycle cap
|
||||||
|
break
|
||||||
|
finally:
|
||||||
|
await nc.close()
|
||||||
|
return published
|
||||||
|
|
||||||
|
|
||||||
async def main() -> None:
|
async def main() -> None:
|
||||||
|
|
@ -57,7 +93,8 @@ async def main() -> None:
|
||||||
try:
|
try:
|
||||||
n = await run_cycle()
|
n = await run_cycle()
|
||||||
p = await publish_new_cameras()
|
p = await publish_new_cameras()
|
||||||
logger.info("cycle: %d stored, %d camera events published", n, p)
|
logger.info("cycle: %d stored, %d published to %s",
|
||||||
|
n, p, CAMERA_NATS_SUBJECT)
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
logger.exception("camera cycle error")
|
logger.exception("camera cycle error")
|
||||||
if not ENABLED: # --once mode
|
if not ENABLED: # --once mode
|
||||||
|
|
|
||||||
|
|
@ -56,11 +56,8 @@ async def producer_loop() -> None:
|
||||||
try:
|
try:
|
||||||
g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50)
|
g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50)
|
||||||
logger.info("GDELT -> %d articles", g)
|
logger.info("GDELT -> %d articles", g)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
# Quota/backoff cases are handled inside ingest_gdelt (one clean
|
logger.exception("GDELT fetch failed")
|
||||||
# line); anything reaching here is a real failure and a stack
|
|
||||||
# trace every 5 minutes is not actionable, so keep it to one line.
|
|
||||||
logger.warning("GDELT fetch failed: %s", exc)
|
|
||||||
if ENABLE_QUAKES:
|
if ENABLE_QUAKES:
|
||||||
try:
|
try:
|
||||||
q = await ingest_earthquakes()
|
q = await ingest_earthquakes()
|
||||||
|
|
@ -119,24 +116,6 @@ async def fire_loop() -> None:
|
||||||
await asyncio.sleep(FIRMS_INTERVAL)
|
await asyncio.sleep(FIRMS_INTERVAL)
|
||||||
|
|
||||||
|
|
||||||
async def geofence_feed_loop() -> None:
|
|
||||||
"""Hear quakes already stored, WFIGS incidents, and news map pins.
|
|
||||||
|
|
||||||
WFIGS is not persisted — fetched per active-fence bbox here (no FIRMS
|
|
||||||
or AIS key). News pins are read from ``news_items``; the summarizer
|
|
||||||
is not imported. New earthquakes also notify from ``ingest_event``.
|
|
||||||
"""
|
|
||||||
logger.info("geofence feed loop starting (interval=%ss)", INTERVAL)
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
from geofence import scan_geofence_feeds
|
|
||||||
n = await scan_geofence_feeds()
|
|
||||||
logger.info("geofence feeds -> %d notifies", n)
|
|
||||||
except Exception: # noqa: BLE001
|
|
||||||
logger.exception("geofence feed scan failed")
|
|
||||||
await asyncio.sleep(INTERVAL)
|
|
||||||
|
|
||||||
|
|
||||||
async def main() -> None:
|
async def main() -> None:
|
||||||
logger.info(
|
logger.info(
|
||||||
"ingester starting (rss=%d feeds, gdelt_q=%r, quakes=%s, fires=%s, interval=%ss)",
|
"ingester starting (rss=%d feeds, gdelt_q=%r, quakes=%s, fires=%s, interval=%ss)",
|
||||||
|
|
@ -147,9 +126,7 @@ async def main() -> None:
|
||||||
await refresh_cache()
|
await refresh_cache()
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception("geofence cache refresh failed (ST_Intersects still runs on ingest)")
|
logger.exception("geofence cache refresh failed (ST_Intersects still runs on ingest)")
|
||||||
tasks: list[asyncio.Task] = [
|
tasks: list[asyncio.Task] = []
|
||||||
asyncio.create_task(geofence_feed_loop()),
|
|
||||||
]
|
|
||||||
if ENABLE_FIRES:
|
if ENABLE_FIRES:
|
||||||
# Fire ingest only starts once FIRMS_MAP_KEY is set (ingest_fires logs
|
# Fire ingest only starts once FIRMS_MAP_KEY is set (ingest_fires logs
|
||||||
# and idles otherwise).
|
# and idles otherwise).
|
||||||
|
|
|
||||||
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(),
|
|
||||||
}
|
|
||||||
|
|
@ -7,7 +7,7 @@ from enum import Enum
|
||||||
from typing import Literal, Optional
|
from typing import Literal, Optional
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
from pydantic import BaseModel, Field, field_validator
|
||||||
|
|
||||||
|
|
||||||
# ─── Enums ───────────────────────────────────────────────────────────────
|
# ─── Enums ───────────────────────────────────────────────────────────────
|
||||||
|
|
@ -63,17 +63,6 @@ class FeedSourceCreate(BaseModel):
|
||||||
config: Optional[dict] = None
|
config: Optional[dict] = None
|
||||||
|
|
||||||
|
|
||||||
class FeedSourceUpdate(BaseModel):
|
|
||||||
"""PATCH /api/sources/{id} — only these keys may be set."""
|
|
||||||
|
|
||||||
model_config = ConfigDict(extra="forbid")
|
|
||||||
|
|
||||||
name: Optional[str] = None
|
|
||||||
url: Optional[str] = None
|
|
||||||
config: Optional[dict] = None
|
|
||||||
enabled: Optional[bool] = None
|
|
||||||
|
|
||||||
|
|
||||||
class FeedSourceOut(BaseModel):
|
class FeedSourceOut(BaseModel):
|
||||||
id: UUID
|
id: UUID
|
||||||
name: str
|
name: str
|
||||||
|
|
@ -314,26 +303,6 @@ class NewsMapItemOut(BaseModel):
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
|
|
||||||
|
|
||||||
class NewsBlipOut(BaseModel):
|
|
||||||
"""One per-article proximate geo blip as exposed by GET /api/news/blips.
|
|
||||||
|
|
||||||
Frozen wire contract (card t_bc15eb53): every graded article with a
|
|
||||||
derivable location, deduped by article id (latest grading wins).
|
|
||||||
Unlike /api/news/map this is NOT limited to critical/high items.
|
|
||||||
"""
|
|
||||||
id: int
|
|
||||||
headline: str
|
|
||||||
url: Optional[str] = None
|
|
||||||
domain: Optional[str] = None
|
|
||||||
location_name: Optional[str] = None
|
|
||||||
lat: float
|
|
||||||
lon: float
|
|
||||||
location_confidence: Optional[str] = None
|
|
||||||
category: Optional[str] = None
|
|
||||||
score: Optional[int] = None
|
|
||||||
created_at: datetime
|
|
||||||
|
|
||||||
|
|
||||||
class NewsModelId(BaseModel):
|
class NewsModelId(BaseModel):
|
||||||
"""One model id as exposed by GET /api/news/models."""
|
"""One model id as exposed by GET /api/news/models."""
|
||||||
|
|
||||||
|
|
|
||||||
351
app/sources.py
351
app/sources.py
|
|
@ -2,15 +2,9 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import html
|
|
||||||
import io
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
from datetime import datetime, timezone
|
||||||
import re
|
|
||||||
import time
|
|
||||||
import zipfile
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
from email.utils import parsedate_to_datetime
|
from email.utils import parsedate_to_datetime
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
@ -149,61 +143,6 @@ def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]:
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# GDELT 429 backoff state. GDELT sends no Retry-After, and its block window
|
|
||||||
# grows with request volume, so the only useful reaction to a 429 is to stop
|
|
||||||
# asking: skip whole producer cycles, doubling the wait from BASE to MAX.
|
|
||||||
GDELT_BACKOFF_BASE = int(os.getenv("GDELT_BACKOFF_BASE", "300"))
|
|
||||||
GDELT_BACKOFF_MAX = int(os.getenv("GDELT_BACKOFF_MAX", "1800"))
|
|
||||||
_gdelt_backoff_secs = 0
|
|
||||||
_gdelt_backoff_until = 0.0 # time.monotonic()
|
|
||||||
|
|
||||||
|
|
||||||
def gdelt_backoff_remaining() -> float:
|
|
||||||
"""Seconds left in the GDELT cooldown window (0 = ready to call)."""
|
|
||||||
return max(0.0, _gdelt_backoff_until - time.monotonic())
|
|
||||||
|
|
||||||
|
|
||||||
def _gdelt_backoff_until_iso() -> str:
|
|
||||||
return (
|
|
||||||
datetime.now(timezone.utc).replace(microsecond=0)
|
|
||||||
+ timedelta(seconds=gdelt_backoff_remaining())
|
|
||||||
).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
||||||
|
|
||||||
|
|
||||||
def _gdelt_start_backoff(retry_after: float | None = None) -> None:
|
|
||||||
global _gdelt_backoff_secs, _gdelt_backoff_until
|
|
||||||
wait = retry_after or min(
|
|
||||||
GDELT_BACKOFF_MAX, max(GDELT_BACKOFF_BASE, _gdelt_backoff_secs * 2)
|
|
||||||
)
|
|
||||||
_gdelt_backoff_secs = int(wait)
|
|
||||||
_gdelt_backoff_until = time.monotonic() + wait
|
|
||||||
|
|
||||||
|
|
||||||
def _gdelt_clear_backoff() -> None:
|
|
||||||
global _gdelt_backoff_secs, _gdelt_backoff_until
|
|
||||||
_gdelt_backoff_secs = 0
|
|
||||||
_gdelt_backoff_until = 0.0
|
|
||||||
|
|
||||||
|
|
||||||
def _gdelt_retry_after(resp: httpx.Response) -> float | None:
|
|
||||||
"""Retry-After as seconds (delta-seconds or HTTP-date); GDELT sends neither."""
|
|
||||||
raw = resp.headers.get("retry-after")
|
|
||||||
if not raw:
|
|
||||||
return None
|
|
||||||
raw = raw.strip()
|
|
||||||
try:
|
|
||||||
return max(1.0, float(raw))
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
return max(
|
|
||||||
1.0,
|
|
||||||
(parsedate_to_datetime(raw) - datetime.now(timezone.utc)).total_seconds(),
|
|
||||||
)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_gdelt_seendate(value: object) -> str:
|
def _parse_gdelt_seendate(value: object) -> str:
|
||||||
if isinstance(value, str) and len(value) >= 15:
|
if isinstance(value, str) and len(value) >= 15:
|
||||||
try:
|
try:
|
||||||
|
|
@ -236,59 +175,25 @@ def parse_gdelt_articles(data: dict) -> list[dict]:
|
||||||
return events
|
return events
|
||||||
|
|
||||||
|
|
||||||
async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50):
|
async def ingest_gdelt(query: str = "", max_articles: int = 50):
|
||||||
"""Fetch articles from the GDELT DOC 2.0 API.
|
"""Fetch articles from the GDELT DOC 2.0 API."""
|
||||||
|
|
||||||
GDELT enforces a per-IP quota that answers ``429`` with a plain-text body
|
|
||||||
("Please limit requests to one every 5 seconds"), sends **no** Retry-After,
|
|
||||||
and widens the block window as request volume accumulates. So a 429 is not
|
|
||||||
retried: the ingester stops calling until a backoff window expires, and the
|
|
||||||
cycle is skipped with a single log line. See ``gdelt_backoff_remaining``.
|
|
||||||
"""
|
|
||||||
remaining = gdelt_backoff_remaining()
|
|
||||||
if remaining > 0:
|
|
||||||
logger.info(
|
|
||||||
"GDELT: cooling down (%ds left after 429); skipping this cycle", int(remaining)
|
|
||||||
)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
params = gdelt_params(query=query, max_articles=max_articles)
|
params = gdelt_params(query=query, max_articles=max_articles)
|
||||||
|
data: dict = {"articles": []}
|
||||||
async with httpx.AsyncClient(
|
async with httpx.AsyncClient(
|
||||||
timeout=60, headers=_ua_headers(), follow_redirects=True,
|
timeout=60, headers=_ua_headers(), follow_redirects=True,
|
||||||
) as client:
|
) as client:
|
||||||
try:
|
try:
|
||||||
resp = await client.get(GDELT_API, params=params)
|
resp = await client.get(GDELT_API, params=params)
|
||||||
except httpx.TransportError as exc:
|
|
||||||
# gdeltproject.org certs have expired in the wild; HTTP fallback.
|
|
||||||
# Only transport failures (TLS/connect) get the fallback — an HTTP
|
|
||||||
# error status is a quota answer and retrying it just burns the
|
|
||||||
# same per-IP budget a second time.
|
|
||||||
logger.warning("GDELT HTTPS transport error (%s); retrying HTTP", exc)
|
|
||||||
http_url = GDELT_API.replace("https://", "http://", 1)
|
|
||||||
resp = await client.get(http_url, params=params)
|
|
||||||
|
|
||||||
if resp.status_code == 429:
|
|
||||||
_gdelt_start_backoff(_gdelt_retry_after(resp))
|
|
||||||
logger.warning(
|
|
||||||
"GDELT 429 (rate limited) -> backing off until %s",
|
|
||||||
_gdelt_backoff_until_iso(),
|
|
||||||
)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
try:
|
|
||||||
resp.raise_for_status()
|
resp.raise_for_status()
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
except (httpx.HTTPStatusError, ValueError) as exc:
|
except (httpx.TransportError, httpx.HTTPStatusError) as exc:
|
||||||
# GDELT also signals errors/throttling as HTTP 200 + prose, so a
|
# gdeltproject.org certs have expired in the wild; HTTP fallback.
|
||||||
# JSON decode failure is "busy", not "no results".
|
logger.warning("GDELT HTTPS failed (%s); retrying HTTP", exc)
|
||||||
_gdelt_start_backoff(_gdelt_retry_after(resp))
|
http_url = GDELT_API.replace("https://", "http://", 1)
|
||||||
logger.warning(
|
resp = await client.get(http_url, params=params)
|
||||||
"GDELT unusable response (HTTP %s: %s) -> backing off until %s",
|
resp.raise_for_status()
|
||||||
resp.status_code, str(exc).splitlines()[0][:120], _gdelt_backoff_until_iso(),
|
data = resp.json()
|
||||||
)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
_gdelt_clear_backoff()
|
|
||||||
events = parse_gdelt_articles(data if isinstance(data, dict) else {})
|
events = parse_gdelt_articles(data if isinstance(data, dict) else {})
|
||||||
for event in events:
|
for event in events:
|
||||||
await publish_event("events.gdelt", event)
|
await publish_event("events.gdelt", event)
|
||||||
|
|
@ -296,240 +201,6 @@ async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50):
|
||||||
return len(events)
|
return len(events)
|
||||||
|
|
||||||
|
|
||||||
# ─── GDELT 2.0 15-minute bulk files (throttle-free) ─────────────────────
|
|
||||||
#
|
|
||||||
# The DOC 2.0 API is per-IP quota'd (429, no Retry-After). The same coverage is
|
|
||||||
# published every 15 minutes as static files under /gdeltv2/ with no key and no
|
|
||||||
# quota, indexed by ``lastupdate.txt``:
|
|
||||||
# *.export.CSV.zip events (CAMEO codes)
|
|
||||||
# *.mentions.CSV.zip event->article mentions (URL + confidence, no title)
|
|
||||||
# *.gkg.csv.zip Global Knowledge Graph, one row per article: URL, source
|
|
||||||
# domain, themes, locations with lat/lon, tone, and the
|
|
||||||
# page title in the V2ExtrasXML column
|
|
||||||
# GKG is the one that carries title + geo, so map a filtered row into the same
|
|
||||||
# event shape ``parse_gdelt_articles`` produces and let the existing
|
|
||||||
# ``events.gdelt`` NATS consumer + ``event_dedup`` (URL) keep working.
|
|
||||||
|
|
||||||
GDELT_BULK_ENABLED = os.getenv("GDELT_BULK_ENABLED", "1").lower() in ("1", "true", "yes")
|
|
||||||
GDELT_BULK_LASTUPDATE = os.getenv(
|
|
||||||
"GDELT_BULK_LASTUPDATE", "https://data.gdeltproject.org/gdeltv2/lastupdate.txt"
|
|
||||||
)
|
|
||||||
GDELT_BULK_MAX_EVENTS = int(os.getenv("GDELT_BULK_MAX_EVENTS", "100"))
|
|
||||||
|
|
||||||
# Newest bulk file already parsed; lastupdate.txt is re-read every cycle but the
|
|
||||||
# 15-minute file behind it only changes 4x/hour.
|
|
||||||
_gdelt_bulk_last_file: str | None = None
|
|
||||||
|
|
||||||
_PAGE_TITLE_RE = re.compile(r"<PAGE_TITLE>(.*?)</PAGE_TITLE>", re.DOTALL)
|
|
||||||
_PAGE_PUB_TS_RE = re.compile(r"<PAGE_PRECISEPUBTIMESTAMP>(\d{14})<")
|
|
||||||
|
|
||||||
|
|
||||||
def gdelt_query_terms(query: str = "") -> list[str]:
|
|
||||||
"""CONFIG GDELT query (``(unrest OR protest OR ...)``) -> plain terms.
|
|
||||||
|
|
||||||
Used to filter bulk rows against their GKG theme tokens instead of
|
|
||||||
publishing every article in the 15-minute window.
|
|
||||||
"""
|
|
||||||
q = (query or "").strip() or GDELT_DEFAULT_QUERY
|
|
||||||
terms: list[str] = []
|
|
||||||
for part in re.split(r"\s+OR\s+", q.strip().strip("()"), flags=re.IGNORECASE):
|
|
||||||
term = part.strip().strip('"').strip("'").strip().lower()
|
|
||||||
if term and term not in terms:
|
|
||||||
terms.append(term)
|
|
||||||
return terms
|
|
||||||
|
|
||||||
|
|
||||||
def _term_hits_themes(term: str, themes: str) -> bool:
|
|
||||||
"""Term matches when every word of it appears in the theme token list."""
|
|
||||||
words = [w for w in re.split(r"[\s_\-]+", term) if w]
|
|
||||||
return bool(words) and all(w in themes for w in words)
|
|
||||||
|
|
||||||
|
|
||||||
def select_gdelt_bulk_url(lastupdate_text: str) -> tuple[str, str] | None:
|
|
||||||
"""``(filename, https_url)`` of the newest GKG file in lastupdate.txt.
|
|
||||||
|
|
||||||
lastupdate.txt lists plain ``http://`` URLs, which 301 to https; normalise
|
|
||||||
so the fetch never follows a redirect into a stale mirror.
|
|
||||||
"""
|
|
||||||
for line in (lastupdate_text or "").splitlines():
|
|
||||||
parts = line.split()
|
|
||||||
if len(parts) < 3 or not parts[2].endswith(".gkg.csv.zip"):
|
|
||||||
continue
|
|
||||||
url = parts[2]
|
|
||||||
if url.startswith("http://"):
|
|
||||||
url = "https://" + url[len("http://"):]
|
|
||||||
return url.rsplit("/", 1)[-1], url
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _gkg_location(field: str) -> tuple[float | None, float | None, str | None]:
|
|
||||||
"""First location in a V2Locations field -> (lat, lon, name).
|
|
||||||
|
|
||||||
V2Locations is ``type#fullname#cc#adm1[#adm2]#lat#lon#featureid``; the
|
|
||||||
adm2 slot is sometimes dropped, so read the triple from the end.
|
|
||||||
"""
|
|
||||||
segment = (field or "").split(";", 1)[0]
|
|
||||||
parts = segment.split("#")
|
|
||||||
if len(parts) < 5:
|
|
||||||
return None, None, None
|
|
||||||
name = parts[1].strip() or None
|
|
||||||
try:
|
|
||||||
lat = float(parts[-3])
|
|
||||||
lon = float(parts[-2])
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return None, None, name
|
|
||||||
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
|
||||||
return None, None, name
|
|
||||||
return lat, lon, name
|
|
||||||
|
|
||||||
|
|
||||||
def _gkg_tone(field: str) -> float | None:
|
|
||||||
try:
|
|
||||||
return _parse_gdelt_tone(field.split(",", 1)[0])
|
|
||||||
except (AttributeError, IndexError):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _gkg_timestamp(row: list[str], extras: str) -> str:
|
|
||||||
"""Article publish time: PAGE_PRECISEPUBTIMESTAMP, else the GKG window stamp."""
|
|
||||||
stamps = []
|
|
||||||
pub = _PAGE_PUB_TS_RE.search(extras)
|
|
||||||
if pub is not None:
|
|
||||||
stamps.append(pub.group(1))
|
|
||||||
if len(row) > 1 and isinstance(row[1], str):
|
|
||||||
stamps.append(row[1][:14])
|
|
||||||
for stamp in stamps:
|
|
||||||
try:
|
|
||||||
return datetime.strptime(stamp, "%Y%m%d%H%M%S").replace(
|
|
||||||
tzinfo=timezone.utc
|
|
||||||
).isoformat()
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
return datetime.now(timezone.utc).isoformat()
|
|
||||||
|
|
||||||
|
|
||||||
def parse_gkg_row(row: list[str], terms: list[str], bulk_file: str = "") -> dict | None:
|
|
||||||
"""Map one GKG CSV row into the ``events.gdelt`` event shape.
|
|
||||||
|
|
||||||
Returns None when the row has no usable URL or matches none of ``terms``.
|
|
||||||
"""
|
|
||||||
if len(row) < 8:
|
|
||||||
return None
|
|
||||||
url = (row[4] or "").strip()
|
|
||||||
if not url.startswith(("http://", "https://")):
|
|
||||||
return None
|
|
||||||
|
|
||||||
raw_themes = row[7] or ""
|
|
||||||
themes = raw_themes.lower()
|
|
||||||
matched = [t for t in terms if _term_hits_themes(t, themes)]
|
|
||||||
if not matched:
|
|
||||||
return None
|
|
||||||
|
|
||||||
extras = row[-1] if isinstance(row[-1], str) else ""
|
|
||||||
title_match = _PAGE_TITLE_RE.search(extras)
|
|
||||||
title = html.unescape(title_match.group(1)).strip() if title_match else None
|
|
||||||
|
|
||||||
lat = lon = loc_name = None
|
|
||||||
for idx in (9, 10):
|
|
||||||
if idx < len(row):
|
|
||||||
lat, lon, loc_name = _gkg_location(row[idx])
|
|
||||||
if lat is not None:
|
|
||||||
break
|
|
||||||
|
|
||||||
theme_tokens = [t for t in raw_themes.split(";") if t]
|
|
||||||
tags = matched + [
|
|
||||||
t for t in theme_tokens
|
|
||||||
if any(w in t.lower() for w in matched)
|
|
||||||
]
|
|
||||||
tags = list(dict.fromkeys(tags))[:10]
|
|
||||||
|
|
||||||
return {
|
|
||||||
"source_type": "gdel-t2",
|
|
||||||
"title": title,
|
|
||||||
"body": (row[3] or "").strip() or None,
|
|
||||||
"url": url,
|
|
||||||
"location_lat": lat,
|
|
||||||
"location_lon": lon,
|
|
||||||
"location_name": loc_name,
|
|
||||||
"source_timestamp": _gkg_timestamp(row, extras),
|
|
||||||
"tags": tags,
|
|
||||||
"raw": {
|
|
||||||
"gkg_record_id": row[0],
|
|
||||||
"source_common_name": row[3],
|
|
||||||
"source_collection": row[2],
|
|
||||||
"themes": theme_tokens[:12],
|
|
||||||
"tone": _gkg_tone(row[15]) if len(row) > 15 else None,
|
|
||||||
"bulk_file": bulk_file,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def ingest_gdelt_bulk(query: str = "", max_events: int | None = None) -> int:
|
|
||||||
"""Publish new articles from the newest 15-minute GKG bulk file.
|
|
||||||
|
|
||||||
No API key, no per-IP quota, and the existing URL dedupe means re-reading
|
|
||||||
the same file after a restart publishes nothing new.
|
|
||||||
"""
|
|
||||||
global _gdelt_bulk_last_file
|
|
||||||
cap = GDELT_BULK_MAX_EVENTS if max_events is None else max_events
|
|
||||||
|
|
||||||
async with httpx.AsyncClient(
|
|
||||||
timeout=120, headers=_ua_headers(), follow_redirects=True,
|
|
||||||
) as client:
|
|
||||||
index = await client.get(GDELT_BULK_LASTUPDATE)
|
|
||||||
index.raise_for_status()
|
|
||||||
picked = select_gdelt_bulk_url(index.text)
|
|
||||||
if picked is None:
|
|
||||||
logger.warning("GDELT bulk: no .gkg file listed in lastupdate.txt")
|
|
||||||
return 0
|
|
||||||
filename, url = picked
|
|
||||||
if filename == _gdelt_bulk_last_file:
|
|
||||||
logger.debug("GDELT bulk: %s already ingested; nothing new", filename)
|
|
||||||
return 0
|
|
||||||
archive = await client.get(url)
|
|
||||||
archive.raise_for_status()
|
|
||||||
|
|
||||||
terms = gdelt_query_terms(query)
|
|
||||||
events: list[dict] = []
|
|
||||||
scanned = 0
|
|
||||||
with zipfile.ZipFile(io.BytesIO(archive.content)) as zf:
|
|
||||||
member = zf.namelist()[0]
|
|
||||||
with zf.open(member) as fh:
|
|
||||||
for line in io.TextIOWrapper(fh, encoding="utf-8", errors="replace"):
|
|
||||||
if not line.strip():
|
|
||||||
continue
|
|
||||||
scanned += 1
|
|
||||||
event = parse_gkg_row(line.rstrip("\r\n").split("\t"), terms, filename)
|
|
||||||
if event is not None and len(events) < cap:
|
|
||||||
events.append(event)
|
|
||||||
|
|
||||||
published = await _publish_unknown("events.gdelt", events)
|
|
||||||
_gdelt_bulk_last_file = filename
|
|
||||||
logger.info(
|
|
||||||
"GDELT bulk %s: %d/%d rows matched %s, %d new articles published",
|
|
||||||
filename, len(events), scanned, "/".join(terms), published,
|
|
||||||
)
|
|
||||||
return published
|
|
||||||
|
|
||||||
|
|
||||||
async def ingest_gdelt(query: str = "", max_articles: int = 50):
|
|
||||||
"""GDELT articles: throttle-free 15-minute bulk file first, DOC API fallback.
|
|
||||||
|
|
||||||
The bulk path carries the coverage; the DOC 2.0 call (with its 429 backoff)
|
|
||||||
only runs when the bulk fetch itself fails, so the per-IP quota is no longer
|
|
||||||
on the hot path.
|
|
||||||
"""
|
|
||||||
if GDELT_BULK_ENABLED:
|
|
||||||
try:
|
|
||||||
return await ingest_gdelt_bulk(query=query)
|
|
||||||
except Exception as exc: # noqa: BLE001 — any bulk failure falls back
|
|
||||||
logger.warning(
|
|
||||||
"GDELT bulk fetch failed (%s: %s); falling back to DOC API",
|
|
||||||
type(exc).__name__, str(exc)[:160],
|
|
||||||
)
|
|
||||||
return await _ingest_gdelt_doc(query=query, max_articles=max_articles)
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_gdelt_tone(tone: str) -> float | None:
|
def _parse_gdelt_tone(tone: str) -> float | None:
|
||||||
"""Parse GDELT tone string to a -1..1 sentiment score."""
|
"""Parse GDELT tone string to a -1..1 sentiment score."""
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -8,18 +8,10 @@ from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import UUID
|
|
||||||
|
|
||||||
BBox = tuple[float, float, float, float] # minlon, minlat, maxlon, maxlat
|
BBox = tuple[float, float, float, float] # minlon, minlat, maxlon, maxlat
|
||||||
|
|
||||||
|
|
||||||
def _uuid_str(value: object) -> str | None:
|
|
||||||
try:
|
|
||||||
return str(UUID(str(value)))
|
|
||||||
except (ValueError, TypeError, AttributeError):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def point_in_bbox(lon: float, lat: float, bbox: BBox | None) -> bool:
|
def point_in_bbox(lon: float, lat: float, bbox: BBox | None) -> bool:
|
||||||
"""True if (lon, lat) sits inside an axis-aligned viewport."""
|
"""True if (lon, lat) sits inside an axis-aligned viewport."""
|
||||||
if bbox is None:
|
if bbox is None:
|
||||||
|
|
@ -34,7 +26,6 @@ class ConnectionManager:
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self._queues: dict[str, asyncio.Queue] = {}
|
self._queues: dict[str, asyncio.Queue] = {}
|
||||||
self._viewports: dict[str, BBox] = {}
|
self._viewports: dict[str, BBox] = {}
|
||||||
self._watched: dict[str, set[str]] = {}
|
|
||||||
|
|
||||||
def register(self, client_id: str, maxsize: int = 256) -> asyncio.Queue:
|
def register(self, client_id: str, maxsize: int = 256) -> asyncio.Queue:
|
||||||
q: asyncio.Queue = asyncio.Queue(maxsize=maxsize)
|
q: asyncio.Queue = asyncio.Queue(maxsize=maxsize)
|
||||||
|
|
@ -44,21 +35,6 @@ class ConnectionManager:
|
||||||
def unregister(self, client_id: str) -> None:
|
def unregister(self, client_id: str) -> None:
|
||||||
self._queues.pop(client_id, None)
|
self._queues.pop(client_id, None)
|
||||||
self._viewports.pop(client_id, None)
|
self._viewports.pop(client_id, None)
|
||||||
self._watched.pop(client_id, None)
|
|
||||||
|
|
||||||
def set_watched_geofences(self, client_id: str, ids: list[str]) -> None:
|
|
||||||
"""Watch these fence UUIDs so geofence_alert delivers off-viewport.
|
|
||||||
|
|
||||||
Invalid UUIDs are ignored. Empty list = watch none (viewport-only).
|
|
||||||
"""
|
|
||||||
if client_id not in self._queues:
|
|
||||||
return
|
|
||||||
watched: set[str] = set()
|
|
||||||
for raw in ids:
|
|
||||||
uid = _uuid_str(raw)
|
|
||||||
if uid is not None:
|
|
||||||
watched.add(uid)
|
|
||||||
self._watched[client_id] = watched
|
|
||||||
|
|
||||||
def set_viewport(self, client_id: str, bbox: BBox) -> None:
|
def set_viewport(self, client_id: str, bbox: BBox) -> None:
|
||||||
if client_id in self._queues:
|
if client_id in self._queues:
|
||||||
|
|
@ -83,21 +59,13 @@ class ConnectionManager:
|
||||||
) -> int:
|
) -> int:
|
||||||
"""Enqueue `{type, payload}` for clients whose viewport contains the point.
|
"""Enqueue `{type, payload}` for clients whose viewport contains the point.
|
||||||
|
|
||||||
kind=geofence_alert also delivers when payload.geofence_id is in the
|
Drops the oldest queued message if a client's buffer is full so a slow
|
||||||
client's watch set (even if the point is off-viewport). Other kinds
|
tab cannot stall ingest. Returns the number of clients that got a copy.
|
||||||
stay viewport-only. Drops the oldest queued message if a client's
|
|
||||||
buffer is full. Returns the number of clients that got a copy.
|
|
||||||
"""
|
"""
|
||||||
msg = {"type": kind, "payload": payload}
|
msg = {"type": kind, "payload": payload}
|
||||||
sent = 0
|
sent = 0
|
||||||
gid = _uuid_str(payload.get("geofence_id")) if kind == "geofence_alert" else None
|
|
||||||
for client_id, queue in list(self._queues.items()):
|
for client_id, queue in list(self._queues.items()):
|
||||||
in_view = point_in_bbox(lon, lat, self._viewports.get(client_id))
|
if not point_in_bbox(lon, lat, self._viewports.get(client_id)):
|
||||||
if kind == "geofence_alert":
|
|
||||||
watching = gid is not None and gid in self._watched.get(client_id, set())
|
|
||||||
if not in_view and not watching:
|
|
||||||
continue
|
|
||||||
elif not in_view:
|
|
||||||
continue
|
continue
|
||||||
if queue.full():
|
if queue.full():
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
31
deploy/README.md
Normal file
31
deploy/README.md
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
# systemd unit template — copy to /etc/systemd/system/osint-masscan.service
|
||||||
|
#
|
||||||
|
# The masscan service is a CONTINUOUS rolling sweep (a full IPv4 pass at a
|
||||||
|
# conservative rate takes ~5 days), so it runs as a long-lived service, NOT a
|
||||||
|
# daily timer. The [Install] WantedBy means it starts at boot and Restart=always
|
||||||
|
# keeps it up. Install steps (run once on the Pi, as root):
|
||||||
|
#
|
||||||
|
# apt install -y masscan # or: apt-get install masscan
|
||||||
|
# mkdir -p /etc/osint-dashboard /opt/siriusdevops
|
||||||
|
# cp deploy/masscan-excludes.txt /etc/osint-dashboard/masscan-excludes.txt
|
||||||
|
#
|
||||||
|
# # Optional tuning (override env in this file; the DB_* values in the unit
|
||||||
|
# # already point at the host-published Postgres on 127.0.0.1:5432):
|
||||||
|
# cat > /etc/osint-dashboard/masscan.env <<'EOF'
|
||||||
|
# MASSCAN_RANGE=0.0.0.0/0
|
||||||
|
# MASSCAN_PORTS=554
|
||||||
|
# MASSCAN_RATE=1000
|
||||||
|
# EOF
|
||||||
|
#
|
||||||
|
# # Venv for the scanner (host-level, not the compose image):
|
||||||
|
# cd /opt/siriusdevops/osint-dashboard
|
||||||
|
# python3 -m venv .venv-masscan
|
||||||
|
# .venv-masscan/bin/pip install -r app/requirements.txt
|
||||||
|
#
|
||||||
|
# install -m 644 deploy/osint-masscan.service /etc/systemd/system/
|
||||||
|
# systemctl daemon-reload
|
||||||
|
# systemctl enable --now osint-masscan
|
||||||
|
#
|
||||||
|
# Watch: journalctl -u osint-masscan -f
|
||||||
|
# DB: writes into the same Postgres the compose stack uses (127.0.0.1:5432)
|
||||||
|
# so findings appear on the dashboard camera map automatically.
|
||||||
33
deploy/masscan-excludes.txt
Normal file
33
deploy/masscan-excludes.txt
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
# masscan excludefile — never probe these ranges.
|
||||||
|
# RFC1918 private + loopback + link-local + multicast + documentation/bogons.
|
||||||
|
# The service refuses to start if this file is missing (fail closed).
|
||||||
|
|
||||||
|
# Loopback
|
||||||
|
127.0.0.0/8
|
||||||
|
|
||||||
|
# RFC1918 private
|
||||||
|
10.0.0.0/8
|
||||||
|
172.16.0.0/12
|
||||||
|
192.168.0.0/16
|
||||||
|
|
||||||
|
# Link-local
|
||||||
|
169.254.0.0/16
|
||||||
|
|
||||||
|
# CGNAT (RFC 6598)
|
||||||
|
100.64.0.0/10
|
||||||
|
|
||||||
|
# Multicast + reserved
|
||||||
|
224.0.0.0/4
|
||||||
|
240.0.0.0/4
|
||||||
|
|
||||||
|
# Documentation / benchmark / example ranges (never real hosts)
|
||||||
|
0.0.0.0/8
|
||||||
|
192.0.2.0/24
|
||||||
|
198.51.100.0/24
|
||||||
|
203.0.113.0/24
|
||||||
|
192.0.0.0/24
|
||||||
|
198.18.0.0/15
|
||||||
|
255.255.255.255/32
|
||||||
|
|
||||||
|
# Carrier NAT / TEST-NET leftovers
|
||||||
|
233.252.0.0/24
|
||||||
29
deploy/osint-masscan.service
Normal file
29
deploy/osint-masscan.service
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
[Unit]
|
||||||
|
Description=OSINT dashboard — masscan rolling sweep (open RTSP port 554)
|
||||||
|
Documentation=https://forgejo.siriusdevops.com/sirius/osint-dashboard
|
||||||
|
After=network-online.target
|
||||||
|
Wants=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
# masscan needs raw sockets (CAP_NET_RAW) — run as root on the Pi host.
|
||||||
|
User=root
|
||||||
|
WorkingDirectory=/opt/siriusdevops/osint-dashboard
|
||||||
|
EnvironmentFile=-/etc/osint-dashboard/masscan.env
|
||||||
|
# Point at the compose-published Postgres on the HOST (127.0.0.1:5432), not the
|
||||||
|
# docker service name 'postgres' which doesn't resolve outside the compose net.
|
||||||
|
Environment=DB_HOST=127.0.0.1
|
||||||
|
Environment=DB_PORT=5432
|
||||||
|
Environment=DB_USER=osint
|
||||||
|
Environment=DB_PASSWORD=osint
|
||||||
|
Environment=DB_NAME=osint_data
|
||||||
|
Environment=MASSCAN_EXCLUDEFILE=/etc/osint-dashboard/masscan-excludes.txt
|
||||||
|
ExecStart=/opt/siriusdevops/osint-dashboard/.venv-masscan/bin/python app/run_masscan_service.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=10
|
||||||
|
# Log the sweep to journald (read with: journalctl -u osint-masscan -f)
|
||||||
|
StandardOutput=journal
|
||||||
|
StandardError=journal
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
|
@ -170,7 +170,7 @@ services:
|
||||||
# Listens on 8000 INSIDE the container (the app already owns host 8000);
|
# Listens on 8000 INSIDE the container (the app already owns host 8000);
|
||||||
# published on host loopback 127.0.0.1:8001 only.
|
# published on host loopback 127.0.0.1:8001 only.
|
||||||
titiler:
|
titiler:
|
||||||
image: ghcr.io/developmentseed/titiler:latest@sha256:1809958d063543e3ec858259536002b2de78e9f8f09a22a8d9591bdc2b550b14
|
image: ghcr.io/developmentseed/titiler:latest
|
||||||
pull_policy: missing
|
pull_policy: missing
|
||||||
container_name: osint-titiler
|
container_name: osint-titiler
|
||||||
platform: linux/arm64
|
platform: linux/arm64
|
||||||
|
|
|
||||||
86
docs/auth.md
86
docs/auth.md
|
|
@ -1,86 +0,0 @@
|
||||||
# Admin authentication
|
|
||||||
|
|
||||||
The dashboard is **public read-only**: anyone can open the map and the news
|
|
||||||
brief. One admin (the operator) additionally gets API-key management, settings
|
|
||||||
and every state-changing route. There is no user table, no RBAC and no OAuth —
|
|
||||||
one admin, one signed cookie (`app/auth.py`).
|
|
||||||
|
|
||||||
## Surface
|
|
||||||
|
|
||||||
| Route | Anonymous | Admin |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| `GET /`, `GET /login`, `GET /static/*`, `WS /ws/live` | ✅ | ✅ |
|
|
||||||
| Read allowlist (`GET /api/news`, `/api/map/*`, feeds, analytics, cameras, `POST /api/search`, …) | ✅ | ✅ |
|
|
||||||
| `GET/POST/DELETE /api/keys*` | 401 | ✅ |
|
|
||||||
| `GET/PUT /api/settings`, `GET /api/news/models` | 401 | ✅ |
|
|
||||||
| Every other `POST/PUT/PATCH/DELETE` (`/api/ingest/*`, `/api/sources`, events, entities, alerts, geofences, `/api/vessels/subscribe`) | 401 | ✅ |
|
|
||||||
| `GET /api/auth/me` | 200 `{"authenticated": false, "admin": false}` | 200, both `true` |
|
|
||||||
| `POST /api/auth/login` | — | 200 + `Set-Cookie` |
|
|
||||||
| `POST /api/auth/logout` | 200 (clears cookie) | 200 |
|
|
||||||
|
|
||||||
Enforcement is **deny-by-default on `/api/*`** in `AdminAuthMiddleware`
|
|
||||||
(`app/auth.py`); the public list is an explicit allowlist (`PUBLIC_GET_EXACT`,
|
|
||||||
`PUBLIC_GET_PATTERNS`, `PUBLIC_POST_EXACT`). Naming a path there is the only way
|
|
||||||
to make it public — never a per-route decorator in `app/main.py`.
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
Three environment variables (cluster: Secret `osint-admin`):
|
|
||||||
|
|
||||||
| Variable | Meaning |
|
|
||||||
| --- | --- |
|
|
||||||
| `ADMIN_USER` | Admin username. |
|
|
||||||
| `ADMIN_PASSWORD_HASH` | `pbkdf2_sha256$<iterations>$<salt_b64>$<hash_b64>`. |
|
|
||||||
| `ADMIN_SESSION_SECRET` | HMAC-SHA256 key for the session token. |
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python app/auth.py hash 'your password' # password hash
|
|
||||||
python -c 'import secrets; print(secrets.token_urlsafe(48))' # session secret
|
|
||||||
```
|
|
||||||
|
|
||||||
Put the values into a Secret and reference them from the deployment; never
|
|
||||||
commit them.
|
|
||||||
|
|
||||||
### Fail closed
|
|
||||||
|
|
||||||
If `ADMIN_PASSWORD_HASH` **or** `ADMIN_SESSION_SECRET` is unset/empty:
|
|
||||||
|
|
||||||
* every admin endpoint answers `403 {"detail": "admin auth not configured"}`,
|
|
||||||
* `/login` renders that message instead of the form,
|
|
||||||
* `/api/auth/login` also answers 403,
|
|
||||||
* public pages and the read allowlist still work.
|
|
||||||
|
|
||||||
There is no default password and no bypass.
|
|
||||||
|
|
||||||
## Session cookie
|
|
||||||
|
|
||||||
`osint_session`, HMAC-SHA256 signed base64url JSON payload `{v,sub,iat,exp}`,
|
|
||||||
`HttpOnly`, `SameSite=Lax`, `Path=/`, 7-day lifetime, `Secure` when the request
|
|
||||||
arrived over https (`X-Forwarded-Proto`, i.e. behind Cloudflare). Signature and
|
|
||||||
expiry are checked with `hmac.compare_digest`; a token for another username, or
|
|
||||||
one signed with a different secret, is rejected.
|
|
||||||
|
|
||||||
Set `ADMIN_COOKIE_SECURE=1` (`true`/`yes` also work) whenever the deployment is
|
|
||||||
TLS-only but the app itself is reached over plain HTTP. In the cluster the
|
|
||||||
Cloudflare tunnel originates at the Cilium Gateway on plain HTTP and Envoy
|
|
||||||
normalizes `X-Forwarded-Proto` to `http`, so the header inference never fires
|
|
||||||
there — the flag is what makes the cookie `Secure` in the cluster. Leave it
|
|
||||||
unset for local development, where the cookie has to work over `http://localhost`.
|
|
||||||
|
|
||||||
## Abuse controls
|
|
||||||
|
|
||||||
* **Login rate limit:** 5 failed attempts per client IP (first hop of
|
|
||||||
`X-Forwarded-For`, else the socket peer) per 15 minutes, then `429`.
|
|
||||||
In-memory — fine for the single replica.
|
|
||||||
* **CSRF:** state-changing admin requests that carry `Origin`/`Referer` must
|
|
||||||
match the request host, else `403`. Header-less clients (curl,
|
|
||||||
service-to-service) rely on the signed SameSite=Lax cookie.
|
|
||||||
|
|
||||||
## HUD
|
|
||||||
|
|
||||||
`app/static/index.html` hides admin chrome with `body:not(.is-admin)
|
|
||||||
[data-admin]` and adds the class only when `GET /api/auth/me` reports
|
|
||||||
`admin: true`. The menu's Ingest / API Keys / Settings entries, the summarizer
|
|
||||||
panel and the geofence draw/rename/delete controls are admin-only; anonymous
|
|
||||||
visitors see a discreet `SIGN IN` link to `/login`. This is UX only — the API
|
|
||||||
gate is what actually protects the data.
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
Builder brief for backend + frontend. Researched 2026-08-27. Every endpoint below was either live-probed from this machine or taken from the provider’s current docs. Prefer **free, no-key, CORS-open** sources first. Keys are called out explicitly.
|
Builder brief for backend + frontend. Researched 2026-08-27. Every endpoint below was either live-probed from this machine or taken from the provider’s current docs. Prefer **free, no-key, CORS-open** sources first. Keys are called out explicitly.
|
||||||
|
|
||||||
This is **not** a camera-discovery change. Existing camera rules still apply: never emit `rtsp://` hrefs; camera pins go through `/api/cameras/{id}/snapshot`; HTTP directory cams use `/stream` MJPEG.
|
This is **not** a camera-discovery / masscan change. Existing camera rules still apply: never emit `rtsp://` hrefs; masscan pins go through `/api/cameras/{id}/snapshot`; HTTP directory cams use `/stream` MJPEG.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
@ -13,7 +13,7 @@ This is **not** a camera-discovery change. Existing camera rules still apply: ne
|
||||||
| NASA FIRMS VIIRS hotspots | Ingested (`app/fire_sources.py` → NATS `events.fire` → `fires` hypertable → `GET /api/fires`) | Needs free `FIRMS_MAP_KEY`. See `docs/firms.md`. |
|
| NASA FIRMS VIIRS hotspots | Ingested (`app/fire_sources.py` → NATS `events.fire` → `fires` hypertable → `GET /api/fires`) | Needs free `FIRMS_MAP_KEY`. See `docs/firms.md`. |
|
||||||
| NASA GIBS basemaps | Frontend tiles via `app/gibs_map.py` | No key. CORS `*`. |
|
| NASA GIBS basemaps | Frontend tiles via `app/gibs_map.py` | No key. CORS `*`. |
|
||||||
| GIBS VIIRS thermal tiles | Documented, not wired as overlay | Same GIBS stack; no key. |
|
| GIBS VIIRS thermal tiles | Documented, not wired as overlay | Same GIBS stack; no key. |
|
||||||
| Cameras | Scraper → `cameras` table | Defaults already include ALERTWest JPEGs + Live-Environment-Streams HLS/YouTube GeoJSON. |
|
| Cameras | Scraper + masscan → `cameras` table | Defaults already include ALERTWest JPEGs + Live-Environment-Streams HLS/YouTube GeoJSON. |
|
||||||
| News / RSS / GDELT / USGS quakes | Ingest | Out of scope for this brief. |
|
| News / RSS / GDELT / USGS quakes | Ingest | Out of scope for this brief. |
|
||||||
|
|
||||||
**Action for existing fire ingest:** NASA will stop Suomi NPP product delivery on **2026-11-01**. Switch `FIRMS_DATASET` from `VIIRS_SNPP_NRT` to `VIIRS_NOAA20_NRT` and/or `VIIRS_NOAA21_NRT` before then.[20]
|
**Action for existing fire ingest:** NASA will stop Suomi NPP product delivery on **2026-11-01**. Switch `FIRMS_DATASET` from `VIIRS_SNPP_NRT` to `VIIRS_NOAA20_NRT` and/or `VIIRS_NOAA21_NRT` before then.[20]
|
||||||
|
|
@ -261,7 +261,7 @@ Use later if you want commuter rail / subway vehicle positions (LA Metro, MTA, e
|
||||||
|
|
||||||
## 6. Open video / camera feeds (official public only)
|
## 6. Open video / camera feeds (official public only)
|
||||||
|
|
||||||
Do **not** add Insecam-style random IP cams as a new source. The scraper already has a public list; this section is **agency-published** JPEG/HLS.
|
Do **not** add Insecam-style random IP cams as a new source. The scraper already has a public list + masscan; this section is **agency-published** JPEG/HLS.
|
||||||
|
|
||||||
### 6.1 Already wired
|
### 6.1 Already wired
|
||||||
|
|
||||||
|
|
@ -304,7 +304,7 @@ Do not call the YouTube Data API unless you want search. Embedding existing stre
|
||||||
|
|
||||||
### 6.5 Skip
|
### 6.5 Skip
|
||||||
|
|
||||||
- Insecam / random “public IP cam” aggregators — ToS / privacy.
|
- Insecam / random “public IP cam” aggregators — ToS / privacy / already covered by masscan ethics.
|
||||||
- TrafficLand, EarthCam commercial APIs.
|
- TrafficLand, EarthCam commercial APIs.
|
||||||
- SkylineWebcams — scraping, not an API.
|
- SkylineWebcams — scraping, not an API.
|
||||||
|
|
||||||
|
|
@ -523,7 +523,7 @@ Attribution bar (required): OpenSky / ADSB.lol ODbL / Amtraker / RainViewer / IE
|
||||||
|
|
||||||
## 12. Legal / ethics (non-negotiable)
|
## 12. Legal / ethics (non-negotiable)
|
||||||
|
|
||||||
- RTSP policy unchanged (never emit `rtsp://` hrefs).
|
- Masscan / RTSP policy unchanged.
|
||||||
- AISStream: server-side only; do not put the key in JS.[5]
|
- AISStream: server-side only; do not put the key in JS.[5]
|
||||||
- OpenSky: non-commercial unless licensed; cite if you publish.[2]
|
- OpenSky: non-commercial unless licensed; cite if you publish.[2]
|
||||||
- ADSB.lol: ODbL share-alike on derived databases.[4]
|
- ADSB.lol: ODbL share-alike on derived databases.[4]
|
||||||
|
|
|
||||||
55
docs/news.md
55
docs/news.md
|
|
@ -43,10 +43,7 @@ feeds (`GET /api/news` exact key set is unchanged on purpose).
|
||||||
URLs from `urls.txt` (homepages autodiscover RSS; feed URLs are parsed
|
URLs from `urls.txt` (homepages autodiscover RSS; feed URLs are parsed
|
||||||
directly), follows each `<item>` link, extracts the main article body, and
|
directly), follows each `<item>` link, extracts the main article body, and
|
||||||
the `PostgresPipeline` writes to `articles` with URL-based dedup
|
the `PostgresPipeline` writes to `articles` with URL-based dedup
|
||||||
(`ON CONFLICT (url) DO NOTHING`). Items whose parsed publish date is more
|
(`ON CONFLICT (url) DO NOTHING`).
|
||||||
than 2 hours in the future are dropped at ingest (`future_dated_dropped`)
|
|
||||||
and never surface via `/api/news`, which additionally hides any
|
|
||||||
`articles.timestamp > now()` row until its date arrives.
|
|
||||||
2. **Summarizer** — `news/summerizer/run_news_summarizer.py` runs
|
2. **Summarizer** — `news/summerizer/run_news_summarizer.py` runs
|
||||||
`summarizer.py` every `NEWS_SUMMARIZE_INTERVAL_S` (default 900) over the
|
`summarizer.py` every `NEWS_SUMMARIZE_INTERVAL_S` (default 900) over the
|
||||||
last `SUMMARY_WINDOW_MINUTES` (default 15), and again at 23:00
|
last `SUMMARY_WINDOW_MINUTES` (default 15), and again at 23:00
|
||||||
|
|
@ -63,46 +60,8 @@ if `article_summaries` already has a row in the last interval, the summarizer
|
||||||
|
|
||||||
The `articles` and `article_summaries` tables are created by the idempotent
|
The `articles` and `article_summaries` tables are created by the idempotent
|
||||||
alembic migration `003_news` (also created by the scraper's own
|
alembic migration `003_news` (also created by the scraper's own
|
||||||
`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items` and
|
`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items`.
|
||||||
`article_scores` is `012_article_scores` (also created by the summarizer's own
|
Container startup order doesn't matter.
|
||||||
`ensure_tables()`). Container startup order doesn't matter.
|
|
||||||
|
|
||||||
## Grading and selection
|
|
||||||
|
|
||||||
The map phase grades every article 0-100 against the rubric in the map prompt
|
|
||||||
(90-100 breaking geopolitical/military/security or major disaster, 70-89
|
|
||||||
significant national/international news, 40-69 notable regional/economic/tech/
|
|
||||||
health, 10-39 routine crime and local interest, 0-9 noise: sport, celebrity,
|
|
||||||
entertainment, market tape, promotional and event-calendar listings). The
|
|
||||||
summarizer parses the first `Score:` line in each `Article <n>:` block, clamps
|
|
||||||
it to 0-100, and falls back to the `Importance:` label (critical 95, high 78,
|
|
||||||
medium 50, low 22, none 5) when the line is missing or unparsable — a block is
|
|
||||||
never dropped and the fallback count is logged per batch. Only blocks scoring
|
|
||||||
`>= SUMMARY_MIN_SCORE` (default 60) reach the reduce prompt, best first, capped
|
|
||||||
at `SUMMARY_TOP_N` (default 12). If nothing clears the bar, up to
|
|
||||||
`SUMMARY_FALLBACK_TOP` blocks (default 3) scoring at least
|
|
||||||
`SUMMARY_FALLBACK_MIN_SCORE` (default 40) are used; when none does, or when
|
|
||||||
`SUMMARY_FALLBACK_TOP=0`, the reduce phase receives an empty DATA section and
|
|
||||||
writes the empty-brief response instead of promoting noise. The reduce prompt
|
|
||||||
no longer asks for filler: it leads with the highest-scoring stories and never
|
|
||||||
promotes an item above its score. Every graded article is persisted to
|
|
||||||
`article_scores` (score, category, selected, model, summary_id) so the operator
|
|
||||||
can tune the thresholds against real data.
|
|
||||||
|
|
||||||
Syndicated wire copy is collapsed **before** the threshold and cap, so
|
|
||||||
`SUMMARY_TOP_N` counts distinct stories instead of stations: the same headline
|
|
||||||
carried by seven Hearst domains is one story, not seven. Titles are normalised
|
|
||||||
first (lowercase, punctuation flattened, a trailing ` - KCCI` / ` | CNN` /
|
|
||||||
` — AP` source suffix dropped when it is short and digit-free), then two blocks
|
|
||||||
are the same story when the normalised titles are equal or at least
|
|
||||||
`SUMMARY_DEDUPE_SIMILARITY` similar (default 0.85; word-set Jaccard or
|
|
||||||
word-sequence `difflib` ratio). The highest-scoring copy represents the story
|
|
||||||
(ties → earliest); differing `category` values and titles that disagree on any
|
|
||||||
number are never merged. Duplicates are still written to `article_scores` with
|
|
||||||
`selected=false` and `duplicate_of` = the surviving `article_id`, so nothing is
|
|
||||||
lost for tuning. `SUMMARY_DEDUPE=0` disables dedupe entirely; raising
|
|
||||||
`SUMMARY_DEDUPE_SIMILARITY` toward 0.95 makes it stricter. Dedupe is pure string
|
|
||||||
work — no extra LLM call.
|
|
||||||
|
|
||||||
## Keys and Settings
|
## Keys and Settings
|
||||||
|
|
||||||
|
|
@ -281,13 +240,7 @@ map. `summary_en` lands in `article_summaries.summary_text`.
|
||||||
| `NOUS_BASE_URL` | `https://inference-api.nousresearch.com/v1` | Read-only in Settings. |
|
| `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`. |
|
| `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`). |
|
| `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_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles. |
|
||||||
| `SUMMARY_TOP_N` | `12` | Max blocks passed to the reduce phase (best score first). |
|
|
||||||
| `SUMMARY_FALLBACK_TOP` | `3` | Blocks used when nothing clears `SUMMARY_MIN_SCORE`; `0` = empty DATA. |
|
|
||||||
| `SUMMARY_FALLBACK_MIN_SCORE` | `40` | Score floor for the fallback set; below it the reduce phase gets empty DATA. |
|
|
||||||
| `SUMMARY_DEDUPE` | `1` | Collapse syndicated wire copies before selection; `0` skips dedupe entirely. |
|
|
||||||
| `SUMMARY_DEDUPE_SIMILARITY` | `0.85` | Normalised-title similarity at which two blocks count as the same story (1.0 = verbatim only). |
|
|
||||||
| `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles (window is `(now - N, now]`; future-dated rows are ignored). |
|
|
||||||
| `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). |
|
| `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). |
|
||||||
| `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). |
|
| `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). |
|
||||||
| `TZ` | `America/New_York` | Timezone for the 23:00 daily recap. |
|
| `TZ` | `America/New_York` | Timezone for the 23:00 daily recap. |
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import datetime
|
import datetime
|
||||||
import re
|
|
||||||
from email.utils import parsedate_to_datetime
|
from email.utils import parsedate_to_datetime
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
|
@ -31,26 +30,3 @@ def article_timestamp(pub_date: str | None) -> datetime.datetime:
|
||||||
except ValueError:
|
except ValueError:
|
||||||
pass
|
pass
|
||||||
return datetime.datetime.now(datetime.timezone.utc)
|
return datetime.datetime.now(datetime.timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
# Whole-title CDATA wrapper only. Keep in sync with app/news_title.py —
|
|
||||||
# the scraper image and the API image do not share a package.
|
|
||||||
_CDATA_WRAPPER = re.compile(
|
|
||||||
r"\A\s*<!\[CDATA\[(.*?)\]\]>\s*\Z",
|
|
||||||
re.DOTALL,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def unwrap_cdata_title(title):
|
|
||||||
"""Strip a surrounding CDATA wrapper. Anything else is unchanged.
|
|
||||||
|
|
||||||
``<![CDATA[Hello]]>`` and ``\\n <![CDATA[Hello]]>`` become
|
|
||||||
``Hello``. Real HTML (``<b>Hello</b>``) and a title that merely contains
|
|
||||||
the markers are returned as-is. Non-strings pass through.
|
|
||||||
"""
|
|
||||||
if not isinstance(title, str):
|
|
||||||
return title
|
|
||||||
match = _CDATA_WRAPPER.match(title)
|
|
||||||
if match is None:
|
|
||||||
return title
|
|
||||||
return match.group(1).strip()
|
|
||||||
|
|
|
||||||
|
|
@ -3,51 +3,10 @@
|
||||||
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
|
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
|
||||||
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
|
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
|
||||||
|
|
||||||
import datetime
|
|
||||||
import logging
|
import logging
|
||||||
import psycopg2
|
import psycopg2
|
||||||
import os
|
import os
|
||||||
from scrapy.exceptions import DropItem
|
from scrapy.exceptions import DropItem
|
||||||
|
|
||||||
from newsScraper.feed_util import unwrap_cdata_title
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# Feed items dated further ahead than this are event listings (or clock skew
|
|
||||||
# from the source), not news. Dropping them keeps `ORDER BY timestamp DESC`
|
|
||||||
# from pinning the top of /api/news for days. See docs/news.md.
|
|
||||||
FUTURE_TOLERANCE = datetime.timedelta(hours=2)
|
|
||||||
|
|
||||||
|
|
||||||
def _parsed_timestamp(value):
|
|
||||||
"""Return an aware UTC datetime for an item timestamp, or None.
|
|
||||||
|
|
||||||
None means "could not parse" — callers must keep such items, exactly as
|
|
||||||
before this guard existed (undated items currently get now() upstream).
|
|
||||||
"""
|
|
||||||
if isinstance(value, datetime.datetime):
|
|
||||||
ts = value
|
|
||||||
elif isinstance(value, str) and value.strip():
|
|
||||||
try:
|
|
||||||
ts = datetime.datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
|
|
||||||
except ValueError:
|
|
||||||
return None
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
if ts.tzinfo is None:
|
|
||||||
ts = ts.replace(tzinfo=datetime.timezone.utc)
|
|
||||||
return ts.astimezone(datetime.timezone.utc)
|
|
||||||
|
|
||||||
|
|
||||||
def is_future_dated(value, now=None, tolerance=FUTURE_TOLERANCE):
|
|
||||||
"""True when a parsed publish timestamp is more than `tolerance` ahead."""
|
|
||||||
ts = _parsed_timestamp(value)
|
|
||||||
if ts is None:
|
|
||||||
return False
|
|
||||||
now = now or datetime.datetime.now(datetime.timezone.utc)
|
|
||||||
return ts > now + tolerance
|
|
||||||
|
|
||||||
|
|
||||||
class PostgresPipeline:
|
class PostgresPipeline:
|
||||||
|
|
||||||
def __init__(self, db_config):
|
def __init__(self, db_config):
|
||||||
|
|
@ -55,8 +14,6 @@ class PostgresPipeline:
|
||||||
self.db_config = db_config
|
self.db_config = db_config
|
||||||
# 2. Initialize the set here so it exists when process_item is called
|
# 2. Initialize the set here so it exists when process_item is called
|
||||||
self.seen_urls = set()
|
self.seen_urls = set()
|
||||||
# 3. Future-dated drops, reported once per run in close_spider()
|
|
||||||
self.future_dated_dropped = 0
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_crawler(cls, crawler):
|
def from_crawler(cls, crawler):
|
||||||
|
|
@ -97,16 +54,9 @@ class PostgresPipeline:
|
||||||
|
|
||||||
def process_item(self, item, spider):
|
def process_item(self, item, spider):
|
||||||
url = item['url']
|
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:
|
if url in self.seen_urls:
|
||||||
raise DropItem(f"Duplicate URL (in-memory): {url}")
|
raise DropItem(f"Duplicate URL (in-memory): {url}")
|
||||||
self.seen_urls.add(url)
|
self.seen_urls.add(url)
|
||||||
item['title'] = unwrap_cdata_title(item['title'])
|
|
||||||
try:
|
try:
|
||||||
self.cur.execute("""
|
self.cur.execute("""
|
||||||
INSERT INTO articles (title, url, content, domain, timestamp)
|
INSERT INTO articles (title, url, content, domain, timestamp)
|
||||||
|
|
@ -132,11 +82,6 @@ class PostgresPipeline:
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def close_spider(self, spider):
|
def close_spider(self, spider):
|
||||||
if self.future_dated_dropped:
|
|
||||||
spider.logger.info(
|
|
||||||
"Dropped %d future-dated item(s) (>%s ahead)",
|
|
||||||
self.future_dated_dropped, FUTURE_TOLERANCE,
|
|
||||||
)
|
|
||||||
self.cur.close()
|
self.cur.close()
|
||||||
self.connection.close()
|
self.connection.close()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -13,8 +13,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
COPY summarizer.py run_news_summarizer.py intel.py nous_client.py gazetteer.py ./
|
COPY summarizer.py run_news_summarizer.py intel.py nous_client.py ./
|
||||||
COPY data/ ./data/
|
|
||||||
|
|
||||||
# Security: run as a non-privileged user.
|
# Security: run as a non-privileged user.
|
||||||
RUN useradd -m summarizer_user
|
RUN useradd -m summarizer_user
|
||||||
|
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
# GeoNames reference data (offline gazetteer)
|
|
||||||
|
|
||||||
Vendored from GeoNames (https://www.geonames.org/), licensed CC-BY 4.0
|
|
||||||
(https://creativecommons.org/licenses/by/4.0/). Attribution: "GeoNames"
|
|
||||||
(https://www.geonames.org/) — the summarizer resolves place names to
|
|
||||||
proximate coordinates fully offline from these files; no geocoding API
|
|
||||||
is called at runtime.
|
|
||||||
|
|
||||||
## Files
|
|
||||||
|
|
||||||
- `cities15000.tsv` — trimmed `cities15000.txt` dump (all cities with
|
|
||||||
population > 15000, ~34k rows). Columns (tab-separated, no header):
|
|
||||||
`name asciiname latitude longitude population country_code admin1_code`
|
|
||||||
Source: https://download.geonames.org/export/dump/cities15000.zip
|
|
||||||
- `admin1.tsv` — trimmed `admin1CodesASCII.txt` (~3.9k first-level
|
|
||||||
divisions: states/regions). Columns: `code name asciiname`
|
|
||||||
(code is `CC.A1`, e.g. `US.TX`). Used to disambiguate "Paris, Texas"
|
|
||||||
from "Paris, France".
|
|
||||||
Source: https://download.geonames.org/export/dump/admin1CodesASCII.txt
|
|
||||||
- `countries.tsv` — trimmed `countryInfo.txt` (252 rows). Columns:
|
|
||||||
`iso_code country_name capital`
|
|
||||||
Source: https://download.geonames.org/export/dump/countryInfo.txt
|
|
||||||
Country-level lookups resolve to the capital's coordinates (the
|
|
||||||
countryInfo dump carries no centroid), confidence "approx".
|
|
||||||
|
|
||||||
Refresh: re-download the dumps, keep the same column layout. The loader
|
|
||||||
(`../gazetteer.py`) tolerates extra/missing trailing columns and skips
|
|
||||||
malformed rows.
|
|
||||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,252 +0,0 @@
|
||||||
AD Andorra Andorra la Vella
|
|
||||||
AE United Arab Emirates Abu Dhabi
|
|
||||||
AF Afghanistan Kabul
|
|
||||||
AG Antigua and Barbuda St. John's
|
|
||||||
AI Anguilla The Valley
|
|
||||||
AL Albania Tirana
|
|
||||||
AM Armenia Yerevan
|
|
||||||
AO Angola Luanda
|
|
||||||
AQ Antarctica
|
|
||||||
AR Argentina Buenos Aires
|
|
||||||
AS American Samoa Pago Pago
|
|
||||||
AT Austria Vienna
|
|
||||||
AU Australia Canberra
|
|
||||||
AW Aruba Oranjestad
|
|
||||||
AX Aland Islands Mariehamn
|
|
||||||
AZ Azerbaijan Baku
|
|
||||||
BA Bosnia and Herzegovina Sarajevo
|
|
||||||
BB Barbados Bridgetown
|
|
||||||
BD Bangladesh Dhaka
|
|
||||||
BE Belgium Brussels
|
|
||||||
BF Burkina Faso Ouagadougou
|
|
||||||
BG Bulgaria Sofia
|
|
||||||
BH Bahrain Manama
|
|
||||||
BI Burundi Gitega
|
|
||||||
BJ Benin Porto-Novo
|
|
||||||
BL Saint Barthelemy Gustavia
|
|
||||||
BM Bermuda Hamilton
|
|
||||||
BN Brunei Bandar Seri Begawan
|
|
||||||
BO Bolivia Sucre
|
|
||||||
BQ Bonaire, Saint Eustatius and Saba
|
|
||||||
BR Brazil Brasilia
|
|
||||||
BS Bahamas Nassau
|
|
||||||
BT Bhutan Thimphu
|
|
||||||
BV Bouvet Island
|
|
||||||
BW Botswana Gaborone
|
|
||||||
BY Belarus Minsk
|
|
||||||
BZ Belize Belmopan
|
|
||||||
CA Canada Ottawa
|
|
||||||
CC Cocos Islands West Island
|
|
||||||
CD Democratic Republic of the Congo Kinshasa
|
|
||||||
CF Central African Republic Bangui
|
|
||||||
CG Republic of the Congo Brazzaville
|
|
||||||
CH Switzerland Bern
|
|
||||||
CI Ivory Coast Yamoussoukro
|
|
||||||
CK Cook Islands Avarua
|
|
||||||
CL Chile Santiago
|
|
||||||
CM Cameroon Yaounde
|
|
||||||
CN China Beijing
|
|
||||||
CO Colombia Bogota
|
|
||||||
CR Costa Rica San Jose
|
|
||||||
CU Cuba Havana
|
|
||||||
CV Cabo Verde Praia
|
|
||||||
CW Curacao Willemstad
|
|
||||||
CX Christmas Island Flying Fish Cove
|
|
||||||
CY Cyprus Nicosia
|
|
||||||
CZ Czechia Prague
|
|
||||||
DE Germany Berlin
|
|
||||||
DJ Djibouti Djibouti
|
|
||||||
DK Denmark Copenhagen
|
|
||||||
DM Dominica Roseau
|
|
||||||
DO Dominican Republic Santo Domingo
|
|
||||||
DZ Algeria Algiers
|
|
||||||
EC Ecuador Quito
|
|
||||||
EE Estonia Tallinn
|
|
||||||
EG Egypt Cairo
|
|
||||||
EH Western Sahara El-Aaiun
|
|
||||||
ER Eritrea Asmara
|
|
||||||
ES Spain Madrid
|
|
||||||
ET Ethiopia Addis Ababa
|
|
||||||
FI Finland Helsinki
|
|
||||||
FJ Fiji Suva
|
|
||||||
FK Falkland Islands Stanley
|
|
||||||
FM Micronesia Palikir
|
|
||||||
FO Faroe Islands Torshavn
|
|
||||||
FR France Paris
|
|
||||||
GA Gabon Libreville
|
|
||||||
GB United Kingdom London
|
|
||||||
GD Grenada St. George's
|
|
||||||
GE Georgia Tbilisi
|
|
||||||
GF French Guiana Cayenne
|
|
||||||
GG Guernsey St Peter Port
|
|
||||||
GH Ghana Accra
|
|
||||||
GI Gibraltar Gibraltar
|
|
||||||
GL Greenland Nuuk
|
|
||||||
GM Gambia Banjul
|
|
||||||
GN Guinea Conakry
|
|
||||||
GP Guadeloupe Basse-Terre
|
|
||||||
GQ Equatorial Guinea Ciudad de la Paz
|
|
||||||
GR Greece Athens
|
|
||||||
GS South Georgia and the South Sandwich Islands Grytviken
|
|
||||||
GT Guatemala Guatemala City
|
|
||||||
GU Guam Hagatna
|
|
||||||
GW Guinea-Bissau Bissau
|
|
||||||
GY Guyana Georgetown
|
|
||||||
HK Hong Kong Hong Kong
|
|
||||||
HM Heard Island and McDonald Islands
|
|
||||||
HN Honduras Tegucigalpa
|
|
||||||
HR Croatia Zagreb
|
|
||||||
HT Haiti Port-au-Prince
|
|
||||||
HU Hungary Budapest
|
|
||||||
ID Indonesia Jakarta
|
|
||||||
IE Ireland Dublin
|
|
||||||
IL Israel Jerusalem
|
|
||||||
IM Isle of Man Douglas
|
|
||||||
IN India New Delhi
|
|
||||||
IO British Indian Ocean Territory Diego Garcia
|
|
||||||
IQ Iraq Baghdad
|
|
||||||
IR Iran Tehran
|
|
||||||
IS Iceland Reykjavik
|
|
||||||
IT Italy Rome
|
|
||||||
JE Jersey Saint Helier
|
|
||||||
JM Jamaica Kingston
|
|
||||||
JO Jordan Amman
|
|
||||||
JP Japan Tokyo
|
|
||||||
KE Kenya Nairobi
|
|
||||||
KG Kyrgyzstan Bishkek
|
|
||||||
KH Cambodia Phnom Penh
|
|
||||||
KI Kiribati Tarawa
|
|
||||||
KM Comoros Moroni
|
|
||||||
KN Saint Kitts and Nevis Basseterre
|
|
||||||
KP North Korea Pyongyang
|
|
||||||
KR South Korea Seoul
|
|
||||||
XK Kosovo Pristina
|
|
||||||
KW Kuwait Kuwait City
|
|
||||||
KY Cayman Islands George Town
|
|
||||||
KZ Kazakhstan Nur-Sultan
|
|
||||||
LA Laos Vientiane
|
|
||||||
LB Lebanon Beirut
|
|
||||||
LC Saint Lucia Castries
|
|
||||||
LI Liechtenstein Vaduz
|
|
||||||
LK Sri Lanka Colombo
|
|
||||||
LR Liberia Monrovia
|
|
||||||
LS Lesotho Maseru
|
|
||||||
LT Lithuania Vilnius
|
|
||||||
LU Luxembourg Luxembourg
|
|
||||||
LV Latvia Riga
|
|
||||||
LY Libya Tripoli
|
|
||||||
MA Morocco Rabat
|
|
||||||
MC Monaco Monaco
|
|
||||||
MD Moldova Chisinau
|
|
||||||
ME Montenegro Podgorica
|
|
||||||
MF Saint Martin Marigot
|
|
||||||
MG Madagascar Antananarivo
|
|
||||||
MH Marshall Islands Majuro
|
|
||||||
MK North Macedonia Skopje
|
|
||||||
ML Mali Bamako
|
|
||||||
MM Myanmar Nay Pyi Taw
|
|
||||||
MN Mongolia Ulaanbaatar
|
|
||||||
MO Macao Macao
|
|
||||||
MP Northern Mariana Islands Saipan
|
|
||||||
MQ Martinique Fort-de-France
|
|
||||||
MR Mauritania Nouakchott
|
|
||||||
MS Montserrat Plymouth
|
|
||||||
MT Malta Valletta
|
|
||||||
MU Mauritius Port Louis
|
|
||||||
MV Maldives Male
|
|
||||||
MW Malawi Lilongwe
|
|
||||||
MX Mexico Mexico City
|
|
||||||
MY Malaysia Kuala Lumpur
|
|
||||||
MZ Mozambique Maputo
|
|
||||||
NA Namibia Windhoek
|
|
||||||
NC New Caledonia Noumea
|
|
||||||
NE Niger Niamey
|
|
||||||
NF Norfolk Island Kingston
|
|
||||||
NG Nigeria Abuja
|
|
||||||
NI Nicaragua Managua
|
|
||||||
NL The Netherlands Amsterdam
|
|
||||||
NO Norway Oslo
|
|
||||||
NP Nepal Kathmandu
|
|
||||||
NR Nauru Yaren
|
|
||||||
NU Niue Alofi
|
|
||||||
NZ New Zealand Wellington
|
|
||||||
OM Oman Muscat
|
|
||||||
PA Panama Panama City
|
|
||||||
PE Peru Lima
|
|
||||||
PF French Polynesia Papeete
|
|
||||||
PG Papua New Guinea Port Moresby
|
|
||||||
PH Philippines Manila
|
|
||||||
PK Pakistan Islamabad
|
|
||||||
PL Poland Warsaw
|
|
||||||
PM Saint Pierre and Miquelon Saint-Pierre
|
|
||||||
PN Pitcairn Adamstown
|
|
||||||
PR Puerto Rico San Juan
|
|
||||||
PS Palestinian Territory East Jerusalem
|
|
||||||
PT Portugal Lisbon
|
|
||||||
PW Palau Melekeok
|
|
||||||
PY Paraguay Asuncion
|
|
||||||
QA Qatar Doha
|
|
||||||
RE Reunion Saint-Denis
|
|
||||||
RO Romania Bucharest
|
|
||||||
RS Serbia Belgrade
|
|
||||||
RU Russia Moscow
|
|
||||||
RW Rwanda Kigali
|
|
||||||
SA Saudi Arabia Riyadh
|
|
||||||
SB Solomon Islands Honiara
|
|
||||||
SC Seychelles Victoria
|
|
||||||
SD Sudan Khartoum
|
|
||||||
SS South Sudan Juba
|
|
||||||
SE Sweden Stockholm
|
|
||||||
SG Singapore Singapore
|
|
||||||
SH Saint Helena Jamestown
|
|
||||||
SI Slovenia Ljubljana
|
|
||||||
SJ Svalbard and Jan Mayen Longyearbyen
|
|
||||||
SK Slovakia Bratislava
|
|
||||||
SL Sierra Leone Freetown
|
|
||||||
SM San Marino San Marino
|
|
||||||
SN Senegal Dakar
|
|
||||||
SO Somalia Mogadishu
|
|
||||||
SR Suriname Paramaribo
|
|
||||||
ST Sao Tome and Principe Sao Tome
|
|
||||||
SV El Salvador San Salvador
|
|
||||||
SX Sint Maarten Philipsburg
|
|
||||||
SY Syria Damascus
|
|
||||||
SZ Eswatini Mbabane
|
|
||||||
TC Turks and Caicos Islands Cockburn Town
|
|
||||||
TD Chad N'Djamena
|
|
||||||
TF French Southern Territories Port-aux-Francais
|
|
||||||
TG Togo Lome
|
|
||||||
TH Thailand Bangkok
|
|
||||||
TJ Tajikistan Dushanbe
|
|
||||||
TK Tokelau
|
|
||||||
TL Timor Leste Dili
|
|
||||||
TM Turkmenistan Ashgabat
|
|
||||||
TN Tunisia Tunis
|
|
||||||
TO Tonga Nuku'alofa
|
|
||||||
TR Turkey Ankara
|
|
||||||
TT Trinidad and Tobago Port of Spain
|
|
||||||
TV Tuvalu Funafuti
|
|
||||||
TW Taiwan Taipei
|
|
||||||
TZ Tanzania Dodoma
|
|
||||||
UA Ukraine Kyiv
|
|
||||||
UG Uganda Kampala
|
|
||||||
UM United States Minor Outlying Islands
|
|
||||||
US United States Washington
|
|
||||||
UY Uruguay Montevideo
|
|
||||||
UZ Uzbekistan Tashkent
|
|
||||||
VA Vatican Vatican City
|
|
||||||
VC Saint Vincent and the Grenadines Kingstown
|
|
||||||
VE Venezuela Caracas
|
|
||||||
VG British Virgin Islands Road Town
|
|
||||||
VI U.S. Virgin Islands Charlotte Amalie
|
|
||||||
VN Vietnam Hanoi
|
|
||||||
VU Vanuatu Port Vila
|
|
||||||
WF Wallis and Futuna Mata Utu
|
|
||||||
WS Samoa Apia
|
|
||||||
YE Yemen Sanaa
|
|
||||||
YT Mayotte Mamoudzou
|
|
||||||
ZA South Africa Pretoria
|
|
||||||
ZM Zambia Lusaka
|
|
||||||
ZW Zimbabwe Harare
|
|
||||||
CS Serbia and Montenegro Belgrade
|
|
||||||
AN Netherlands Antilles Willemstad
|
|
||||||
|
|
|
@ -1,193 +0,0 @@
|
||||||
"""Offline GeoNames gazetteer — proximate geolocation for graded articles.
|
|
||||||
|
|
||||||
When a map-phase block names a place but gives no coordinates, resolve the
|
|
||||||
name against vendored GeoNames data (``data/``): cities15000 first, then
|
|
||||||
country -> capital. Fully offline: no paid API, no rate-limited Nominatim,
|
|
||||||
no network at runtime. Every resolution is labelled confidence "approx"
|
|
||||||
by the caller — a gazetteer point is a proximate guess, never an exact fix.
|
|
||||||
|
|
||||||
Matching is best-effort and conservative: normalised (case/diacritic-folded)
|
|
||||||
exact-name lookups with country/admin1 context disambiguation ("Paris,
|
|
||||||
Texas" vs "Paris, France"), highest population wins ties. A miss returns
|
|
||||||
None — the article simply gets no blip. Never invents a place.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import unicodedata
|
|
||||||
from functools import lru_cache
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
_DATA_DIR = Path(__file__).resolve().parent / "data"
|
|
||||||
|
|
||||||
# Common short forms the model writes that GeoNames spells out.
|
|
||||||
_COUNTRY_ALIASES = {
|
|
||||||
"usa": "US",
|
|
||||||
"u.s.a.": "US",
|
|
||||||
"u.s.": "US",
|
|
||||||
"us": "US",
|
|
||||||
"uk": "GB",
|
|
||||||
"u.k.": "GB",
|
|
||||||
"united states of america": "US",
|
|
||||||
"england": "GB",
|
|
||||||
"south korea": "KR",
|
|
||||||
"north korea": "KP",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _norm(text: str) -> str:
|
|
||||||
"""Casefold + strip diacritics + collapse whitespace for matching."""
|
|
||||||
text = unicodedata.normalize("NFKD", text)
|
|
||||||
text = "".join(ch for ch in text if not unicodedata.combining(ch))
|
|
||||||
return " ".join(text.casefold().split())
|
|
||||||
|
|
||||||
|
|
||||||
def _read_tsv(filename: str) -> list[list[str]]:
|
|
||||||
path = _DATA_DIR / filename
|
|
||||||
rows: list[list[str]] = []
|
|
||||||
try:
|
|
||||||
with open(path, encoding="utf-8") as fh:
|
|
||||||
for line in fh:
|
|
||||||
parts = line.rstrip("\n").split("\t")
|
|
||||||
if parts and parts[0]:
|
|
||||||
rows.append(parts)
|
|
||||||
except OSError:
|
|
||||||
return []
|
|
||||||
return rows
|
|
||||||
|
|
||||||
|
|
||||||
@lru_cache(maxsize=1)
|
|
||||||
def _city_index() -> dict[str, list[tuple[float, float, int, str, str]]]:
|
|
||||||
"""norm name -> [(lat, lon, population, country_code, admin1_code)]."""
|
|
||||||
index: dict[str, list[tuple[float, float, int, str, str]]] = {}
|
|
||||||
for parts in _read_tsv("cities15000.tsv"):
|
|
||||||
if len(parts) < 7:
|
|
||||||
continue
|
|
||||||
name, asciiname, lat, lon, pop, cc, admin1 = parts[:7]
|
|
||||||
try:
|
|
||||||
lat_f, lon_f, pop_i = float(lat), float(lon), int(pop)
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
if not (-90 <= lat_f <= 90 and -180 <= lon_f <= 180):
|
|
||||||
continue
|
|
||||||
entry = (lat_f, lon_f, pop_i, cc, admin1)
|
|
||||||
for key in {name, asciiname}:
|
|
||||||
key = _norm(key)
|
|
||||||
if key:
|
|
||||||
index.setdefault(key, []).append(entry)
|
|
||||||
return index
|
|
||||||
|
|
||||||
|
|
||||||
@lru_cache(maxsize=1)
|
|
||||||
def _country_index() -> dict[str, tuple[str, str]]:
|
|
||||||
"""norm country name/iso -> (iso_code, capital)."""
|
|
||||||
index: dict[str, tuple[str, str]] = {}
|
|
||||||
for parts in _read_tsv("countries.tsv"):
|
|
||||||
if len(parts) < 3:
|
|
||||||
continue
|
|
||||||
iso, name, capital = parts[:3]
|
|
||||||
value = (iso, capital)
|
|
||||||
index[_norm(name)] = value
|
|
||||||
index[iso.casefold()] = value
|
|
||||||
for alias, iso in _COUNTRY_ALIASES.items():
|
|
||||||
hit = index.get(iso.casefold())
|
|
||||||
if hit:
|
|
||||||
index[_norm(alias)] = hit
|
|
||||||
return index
|
|
||||||
|
|
||||||
|
|
||||||
@lru_cache(maxsize=1)
|
|
||||||
def _admin1_index() -> dict[str, list[tuple[str, str]]]:
|
|
||||||
"""norm division name -> [(country_code, admin1_code)]."""
|
|
||||||
index: dict[str, list[tuple[str, str]]] = {}
|
|
||||||
for parts in _read_tsv("admin1.tsv"):
|
|
||||||
if len(parts) < 3 or "." not in parts[0]:
|
|
||||||
continue
|
|
||||||
code, name, asciiname = parts[:3]
|
|
||||||
cc, _, a1 = code.partition(".")
|
|
||||||
for key in {name, asciiname}:
|
|
||||||
key = _norm(key)
|
|
||||||
if key:
|
|
||||||
index.setdefault(key, []).append((cc, a1))
|
|
||||||
return index
|
|
||||||
|
|
||||||
|
|
||||||
def _pick(entries: list[tuple[float, float, int, str, str]]) -> tuple[float, float]:
|
|
||||||
best = max(entries, key=lambda e: e[2])
|
|
||||||
return (best[0], best[1])
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_place(location_name) -> tuple[float, float] | None:
|
|
||||||
"""Proximate (lat, lon) for a model-written place name, else None.
|
|
||||||
|
|
||||||
Tries the full string, then the comma-leading part, with trailing
|
|
||||||
parts as country/admin1 context. Falls back to country -> capital.
|
|
||||||
"""
|
|
||||||
if not isinstance(location_name, str):
|
|
||||||
return None
|
|
||||||
text = location_name.strip()
|
|
||||||
if not text:
|
|
||||||
return None
|
|
||||||
parts = [p.strip() for p in text.split(",") if p.strip()]
|
|
||||||
if not parts:
|
|
||||||
return None
|
|
||||||
|
|
||||||
countries = _country_index()
|
|
||||||
admin1s = _admin1_index()
|
|
||||||
context_country: str | None = None
|
|
||||||
context_admin1: list[tuple[str, str]] = []
|
|
||||||
for part in parts[1:]:
|
|
||||||
key = _norm(part)
|
|
||||||
hit = countries.get(key)
|
|
||||||
if hit:
|
|
||||||
context_country = hit[0]
|
|
||||||
continue
|
|
||||||
context_admin1.extend(admin1s.get(key, []))
|
|
||||||
|
|
||||||
cities = _city_index()
|
|
||||||
for candidate in (text, parts[0]):
|
|
||||||
entries = cities.get(_norm(candidate))
|
|
||||||
if not entries:
|
|
||||||
continue
|
|
||||||
if context_admin1:
|
|
||||||
scoped = [
|
|
||||||
e for e in entries
|
|
||||||
if any(e[3] == cc and e[4] == a1 for cc, a1 in context_admin1)
|
|
||||||
]
|
|
||||||
if scoped:
|
|
||||||
return _pick(scoped)
|
|
||||||
if context_country:
|
|
||||||
scoped = [e for e in entries if e[3] == context_country]
|
|
||||||
if scoped:
|
|
||||||
return _pick(scoped)
|
|
||||||
return _pick(entries)
|
|
||||||
|
|
||||||
# Country-only location ("Ukraine"): resolve to the capital.
|
|
||||||
hit = countries.get(_norm(parts[0]))
|
|
||||||
if hit:
|
|
||||||
entries = cities.get(_norm(hit[1]))
|
|
||||||
if entries:
|
|
||||||
return _pick(entries)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def fill_block_geo(block: dict) -> dict:
|
|
||||||
"""Fill missing coords on a parsed map block from the gazetteer.
|
|
||||||
|
|
||||||
Blocks that already carry model coordinates are untouched. A resolved
|
|
||||||
place is labelled confidence "approx"; a miss leaves the block as-is
|
|
||||||
(name preserved, no coords) — never invents a place.
|
|
||||||
"""
|
|
||||||
if not isinstance(block, dict):
|
|
||||||
return block
|
|
||||||
if block.get("lat") is not None and block.get("lon") is not None:
|
|
||||||
return block
|
|
||||||
name = block.get("location_name")
|
|
||||||
if not name:
|
|
||||||
return block
|
|
||||||
coords = resolve_place(name)
|
|
||||||
if coords is None:
|
|
||||||
return block
|
|
||||||
block["lat"], block["lon"] = coords
|
|
||||||
block["location_confidence"] = "approx"
|
|
||||||
return block
|
|
||||||
|
|
@ -1,8 +1,7 @@
|
||||||
"""Pure parser for the news-summarizer map grading / reduce JSON / geo contract."""
|
"""Pure parser for the news-summarizer reduce JSON / geo / importance contract."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import difflib
|
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
|
@ -17,94 +16,6 @@ MAP_HEADLINE_MAX = 160
|
||||||
TICKER_CAP = 12
|
TICKER_CAP = 12
|
||||||
MAP_CAP = 20
|
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:
|
def parse_reduce_json(raw: str) -> dict:
|
||||||
try:
|
try:
|
||||||
|
|
@ -191,401 +102,3 @@ def select_map(items: list) -> list:
|
||||||
if len(out) >= MAP_CAP:
|
if len(out) >= MAP_CAP:
|
||||||
break
|
break
|
||||||
return out
|
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
|
|
||||||
|
|
|
||||||
|
|
@ -14,12 +14,6 @@ of each summarize_news() — env wins, else api_keys / app_settings:
|
||||||
NOUS_API_KEY Nous Portal key (else api_keys.name='NOUS_API_KEY')
|
NOUS_API_KEY Nous Portal key (else api_keys.name='NOUS_API_KEY')
|
||||||
NOUS_BASE_URL default https://inference-api.nousresearch.com/v1
|
NOUS_BASE_URL default https://inference-api.nousresearch.com/v1
|
||||||
SUMMARY_MODEL default Hermes-4.3-36B (else app_settings)
|
SUMMARY_MODEL default Hermes-4.3-36B (else app_settings)
|
||||||
SUMMARY_MIN_SCORE map-score a block needs to reach the reduce brief (60)
|
|
||||||
SUMMARY_TOP_N max distinct blocks passed to reduce (12)
|
|
||||||
SUMMARY_FALLBACK_TOP blocks used when nothing clears MIN_SCORE (3)
|
|
||||||
SUMMARY_FALLBACK_MIN_SCORE score floor for that fallback set (40)
|
|
||||||
SUMMARY_DEDUPE "0" disables syndication dedupe (default on)
|
|
||||||
SUMMARY_DEDUPE_SIMILARITY normalised-title similarity for one story (0.85)
|
|
||||||
BATCH_SIZE articles per map-phase batch (default 50)
|
BATCH_SIZE articles per map-phase batch (default 50)
|
||||||
SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set)
|
SUMMARY_WINDOW_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_RECAP "1" for the 23:00 daily recap (24h window, recap prompt)
|
||||||
|
|
@ -37,20 +31,7 @@ from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
import psycopg2
|
import psycopg2
|
||||||
|
|
||||||
from gazetteer import fill_block_geo
|
from intel import parse_reduce_json, select_map, select_ticker
|
||||||
from intel import (
|
|
||||||
GEO_CONFIDENCES,
|
|
||||||
article_url_for_row,
|
|
||||||
clamp_coords,
|
|
||||||
clean_location_name,
|
|
||||||
dedupe_blocks,
|
|
||||||
join_blocks,
|
|
||||||
parse_map_scores,
|
|
||||||
parse_reduce_json,
|
|
||||||
select_graded,
|
|
||||||
select_map,
|
|
||||||
select_ticker,
|
|
||||||
)
|
|
||||||
from nous_client import chat
|
from nous_client import chat
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||||
|
|
@ -69,58 +50,6 @@ DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1"
|
||||||
DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B"
|
DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B"
|
||||||
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50"))
|
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:
|
def _summary_window_minutes() -> int:
|
||||||
hours = (os.getenv("SUMMARY_WINDOW_HOURS") or "").strip()
|
hours = (os.getenv("SUMMARY_WINDOW_HOURS") or "").strip()
|
||||||
|
|
@ -165,41 +94,30 @@ FUTURES_TICKERS = {
|
||||||
MAP_PROMPT_DEFAULT = """\
|
MAP_PROMPT_DEFAULT = """\
|
||||||
You are a precise, factual OSINT news processor. Your ONLY source of information is the articles provided below. Do NOT add external knowledge, assumptions, training data, or invented facts.
|
You are a precise, factual OSINT news processor. Your ONLY source of information is the articles provided below. Do NOT add external knowledge, assumptions, training data, or invented facts.
|
||||||
|
|
||||||
Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. Extract every article; the Score below decides what reaches the operator brief.
|
Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. If the batch has no critical/high stories, still extract minor incidents and crime reports.
|
||||||
|
|
||||||
Write every field in English. Translate if the article is not English.
|
Write every field in English. Translate if the article is not English.
|
||||||
|
|
||||||
Grade every article with this rubric before writing anything else in its block:
|
|
||||||
|
|
||||||
- 90–100 — breaking geopolitical/military/security event or major disaster, immediate consequence
|
|
||||||
- 70–89 — significant national/international politics, conflict, security, infrastructure or disaster news
|
|
||||||
- 40–69 — notable regional/economic/tech/health story with real consequences
|
|
||||||
- 10–39 — routine, minor or single-incident crime; local interest
|
|
||||||
- 0–9 — noise: sport, celebrity, entertainment, market/commodity tape, promotional or event-calendar/schedule listings
|
|
||||||
|
|
||||||
For EACH article in the batch:
|
For EACH article in the batch:
|
||||||
1. Score: the integer 0-100 from the rubric above, first line of the block.
|
1. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
||||||
2. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
2. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit.
|
||||||
3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit. Confidence: how precise that location is — exact (a specific site/address), city, region, or country. Never invent a place.
|
3. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
||||||
4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
4. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
||||||
5. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
5. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
|
||||||
6. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
|
6. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none.
|
||||||
7. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none. Keep it consistent with the Score.
|
|
||||||
|
|
||||||
If several articles cover the same story, add one short batch-level note at the end: "Batch theme: [one sentence]".
|
If several articles cover the same story, add one short batch-level note at the end: "Batch theme: [one sentence]".
|
||||||
|
|
||||||
Output format — strictly one block per article, Score and Importance first:
|
Output format — strictly one block per article:
|
||||||
|
|
||||||
Article 1:
|
Article 1:
|
||||||
- Score: <0-100>
|
|
||||||
- Importance: critical|high|medium|low|none
|
|
||||||
- Fact bullet 1
|
- Fact bullet 1
|
||||||
- Fact bullet 2
|
- Fact bullet 2
|
||||||
- Location: ...
|
- Location: ...
|
||||||
- Confidence: exact|city|region|country
|
|
||||||
- Entities: ...
|
- Entities: ...
|
||||||
- Category: ...
|
- Category: ...
|
||||||
- OSINT signal: ...
|
- OSINT signal: ...
|
||||||
|
- Importance: ...
|
||||||
- Lat: ...
|
- Lat: ...
|
||||||
- Lon: ...
|
- Lon: ...
|
||||||
|
|
||||||
|
|
@ -215,11 +133,9 @@ You are writing an English operator HUD brief from the article facts in DATA bel
|
||||||
|
|
||||||
Always write a real summary_en that recaps the most important stories present in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
|
Always write a real summary_en that recaps the most important stories present in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
|
||||||
|
|
||||||
DATA is pre-filtered by score and ordered best-first. Lead with the highest-scoring breaking stories and rank them honestly by importance — never promote an item above its score. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short.
|
Lead with critical and high breaking events. If DATA has no critical/high stories, fill the brief with minor incidents and crime reports rather than writing an empty or unfinished brief. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short.
|
||||||
|
|
||||||
If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}.
|
ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank.
|
||||||
|
|
||||||
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.
|
map_items may be empty if no located critical/high event is explicit in the data.
|
||||||
|
|
||||||
|
|
@ -244,11 +160,9 @@ You are writing a daily recap of the last 24 hours of news for an OSINT operator
|
||||||
|
|
||||||
Always write a real summary_en daily recap of the most important stories in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
|
Always write a real summary_en daily recap of the most important stories in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news.
|
||||||
|
|
||||||
DATA is pre-filtered by score and ordered best-first. Lead with the highest-scoring breaking stories of the day and rank them honestly by importance — never promote an item above its score. Never truncate mid-sentence; finish every sentence.
|
Lead with critical and high breaking events. If DATA has no critical/high stories, fill the recap with minor incidents and crime reports rather than writing an empty or unfinished recap. Never truncate mid-sentence; finish every sentence.
|
||||||
|
|
||||||
If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}.
|
ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank.
|
||||||
|
|
||||||
ticker: only stories present in DATA, highest score first.
|
|
||||||
|
|
||||||
Demand a single JSON object (no markdown fences) with this exact shape:
|
Demand a single JSON object (no markdown fences) with this exact shape:
|
||||||
|
|
||||||
|
|
@ -412,27 +326,6 @@ def ensure_tables() -> None:
|
||||||
CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox
|
CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox
|
||||||
ON news_items (lon, lat)
|
ON news_items (lon, lat)
|
||||||
WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL;
|
WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL;
|
||||||
CREATE TABLE IF NOT EXISTS article_scores (
|
|
||||||
article_id INTEGER NOT NULL,
|
|
||||||
summary_id INTEGER,
|
|
||||||
score INTEGER NOT NULL,
|
|
||||||
category TEXT,
|
|
||||||
selected BOOLEAN NOT NULL,
|
|
||||||
model TEXT,
|
|
||||||
duplicate_of INTEGER,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
||||||
PRIMARY KEY (article_id, created_at)
|
|
||||||
);
|
|
||||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER;
|
|
||||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_name TEXT;
|
|
||||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lat DOUBLE PRECISION;
|
|
||||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lon DOUBLE PRECISION;
|
|
||||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_confidence TEXT;
|
|
||||||
CREATE INDEX IF NOT EXISTS ix_article_scores_summary
|
|
||||||
ON article_scores (summary_id);
|
|
||||||
CREATE INDEX IF NOT EXISTS ix_article_scores_geo_bbox
|
|
||||||
ON article_scores (lon, lat)
|
|
||||||
WHERE lat IS NOT NULL AND lon IS NOT NULL;
|
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
conn = psycopg2.connect(**DB_CONFIG)
|
conn = psycopg2.connect(**DB_CONFIG)
|
||||||
|
|
@ -446,18 +339,12 @@ def ensure_tables() -> None:
|
||||||
|
|
||||||
|
|
||||||
def get_recent_news(window_minutes: int | None = None) -> list[dict]:
|
def get_recent_news(window_minutes: int | None = None) -> list[dict]:
|
||||||
"""Fetch articles from the look-back window ``(now - window, now]``.
|
"""Fetch articles from the look-back window (content > 100 chars)."""
|
||||||
|
|
||||||
The upper bound is deliberate: future-dated rows (event listings, bad
|
|
||||||
scrape timestamps) must not be re-graded every interval. Rows with a NULL
|
|
||||||
timestamp have never matched the lower bound and still do not.
|
|
||||||
"""
|
|
||||||
mins = window_minutes if window_minutes is not None else effective_window_minutes()
|
mins = window_minutes if window_minutes is not None else effective_window_minutes()
|
||||||
query = """
|
query = """
|
||||||
SELECT id, title, content, url, domain
|
SELECT title, content, url, domain
|
||||||
FROM articles
|
FROM articles
|
||||||
WHERE timestamp > NOW() - make_interval(mins => %s)
|
WHERE timestamp > NOW() - make_interval(mins => %s)
|
||||||
AND timestamp <= NOW()
|
|
||||||
AND content IS NOT NULL AND length(content) > 100
|
AND content IS NOT NULL AND length(content) > 100
|
||||||
ORDER BY timestamp DESC;
|
ORDER BY timestamp DESC;
|
||||||
"""
|
"""
|
||||||
|
|
@ -469,7 +356,7 @@ def get_recent_news(window_minutes: int | None = None) -> list[dict]:
|
||||||
cur.close()
|
cur.close()
|
||||||
conn.close()
|
conn.close()
|
||||||
return [
|
return [
|
||||||
{"id": r[0], "title": r[1], "content": r[2], "url": r[3], "domain": r[4]}
|
{"title": r[0], "content": r[1], "url": r[2], "domain": r[3]}
|
||||||
for r in rows
|
for r in rows
|
||||||
]
|
]
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
|
|
@ -524,25 +411,15 @@ def _already_recapped_today() -> bool:
|
||||||
|
|
||||||
|
|
||||||
def save_batch(
|
def save_batch(
|
||||||
summary_en: str,
|
summary_en: str, model: str, ticker: list, map_items: list, *, kind: str = "interval"
|
||||||
model: str,
|
) -> None:
|
||||||
ticker: list,
|
"""Insert the master brief plus flagged ticker/map rows."""
|
||||||
map_items: list,
|
|
||||||
*,
|
|
||||||
kind: str = "interval",
|
|
||||||
articles: list | None = None,
|
|
||||||
) -> int | None:
|
|
||||||
"""Insert the master brief plus flagged ticker/map rows. Returns the new summary id.
|
|
||||||
|
|
||||||
``news_items.url`` is the matched selected article's url, never the model's
|
|
||||||
``url`` field. A null article url is stored as ``""``.
|
|
||||||
"""
|
|
||||||
ticker_rows = select_ticker(ticker or [])
|
ticker_rows = select_ticker(ticker or [])
|
||||||
map_rows = select_map(map_items or [])
|
map_rows = select_map(map_items or [])
|
||||||
text = (summary_en or "").strip()
|
text = (summary_en or "").strip()
|
||||||
if len(text) < 10 and not ticker_rows and not map_rows:
|
if len(text) < 10 and not ticker_rows and not map_rows:
|
||||||
logger.info("Summary too short or empty. Skipping save.")
|
logger.info("Summary too short or empty. Skipping save.")
|
||||||
return None
|
return
|
||||||
insert_item = """
|
insert_item = """
|
||||||
INSERT INTO news_items (
|
INSERT INTO news_items (
|
||||||
summary_id, kind, headline, importance, location_name,
|
summary_id, kind, headline, importance, location_name,
|
||||||
|
|
@ -570,7 +447,7 @@ def save_batch(
|
||||||
None,
|
None,
|
||||||
None,
|
None,
|
||||||
None,
|
None,
|
||||||
article_url_for_row(row, articles),
|
row.get("url"),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
for row in map_rows:
|
for row in map_rows:
|
||||||
|
|
@ -586,7 +463,7 @@ def save_batch(
|
||||||
row.get("lon"),
|
row.get("lon"),
|
||||||
row.get("location_confidence"),
|
row.get("location_confidence"),
|
||||||
row.get("category"),
|
row.get("category"),
|
||||||
article_url_for_row(row, articles),
|
row.get("url"),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
@ -596,77 +473,8 @@ def save_batch(
|
||||||
)
|
)
|
||||||
cur.close()
|
cur.close()
|
||||||
conn.close()
|
conn.close()
|
||||||
return summary_id
|
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
logger.error("Error saving batch to DB: %s", exc)
|
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 ──────────────────────────────────────────────────────────
|
# ── Orchestration ──────────────────────────────────────────────────────────
|
||||||
|
|
@ -725,99 +533,34 @@ def summarize_news() -> None:
|
||||||
logger.info("No new articles found in the last %s min.", window)
|
logger.info("No new articles found in the last %s min.", window)
|
||||||
return
|
return
|
||||||
|
|
||||||
min_score, top_n, fallback_top, fallback_min_score = selection_config()
|
|
||||||
logger.info(
|
logger.info(
|
||||||
"Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s, "
|
"Processing %d articles with %s (batch_size=%d, 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,
|
len(articles), model, BATCH_SIZE, recap, window,
|
||||||
min_score, top_n, fallback_top, fallback_min_score,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
graded: list[dict] = []
|
partial_summaries: list[str] = []
|
||||||
for i in range(0, len(articles), BATCH_SIZE):
|
for i in range(0, len(articles), BATCH_SIZE):
|
||||||
batch = articles[i : i + BATCH_SIZE]
|
batch = articles[i : i + BATCH_SIZE]
|
||||||
batch_index = i // BATCH_SIZE
|
|
||||||
logger.info(
|
logger.info(
|
||||||
"map batch %d/%d (%d articles)",
|
"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),
|
build_map_prompt(batch),
|
||||||
api_key=api_key,
|
api_key=api_key,
|
||||||
model=model,
|
model=model,
|
||||||
base_url=base_url,
|
base_url=base_url,
|
||||||
json_mode=False,
|
json_mode=False,
|
||||||
)
|
)
|
||||||
if not response:
|
if summary:
|
||||||
continue
|
partial_summaries.append(summary)
|
||||||
blocks, stats = parse_map_scores(
|
|
||||||
response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE
|
|
||||||
)
|
|
||||||
# Best-effort proximate geo: place-name-only blocks get offline
|
|
||||||
# gazetteer coords (confidence "approx"); misses stay coord-less.
|
|
||||||
for block in blocks:
|
|
||||||
fill_block_geo(block)
|
|
||||||
logger.info(
|
|
||||||
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d, geo=%d)",
|
|
||||||
batch_index + 1, stats["graded"], len(batch),
|
|
||||||
stats["fallback"], stats["unattributed"],
|
|
||||||
sum(1 for b in blocks if b.get("lat") is not None),
|
|
||||||
)
|
|
||||||
graded.extend(blocks)
|
|
||||||
|
|
||||||
if not graded:
|
final_input = "\n\n".join(partial_summaries)
|
||||||
logger.warning("No article blocks parsed from the map phase — nothing to reduce.")
|
if not final_input.strip():
|
||||||
|
logger.warning("No partial summaries produced — nothing to reduce.")
|
||||||
return
|
return
|
||||||
|
|
||||||
dedupe_enabled, dedupe_similarity = dedupe_config()
|
logger.info("reduce phase over %d partial summaries", len(partial_summaries))
|
||||||
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,
|
|
||||||
)
|
|
||||||
|
|
||||||
master_raw = call_llm(
|
master_raw = call_llm(
|
||||||
build_master_prompt(final_input, recap=recap),
|
build_master_prompt(final_input, recap=recap),
|
||||||
api_key=api_key,
|
api_key=api_key,
|
||||||
|
|
@ -829,20 +572,13 @@ def summarize_news() -> None:
|
||||||
logger.warning("Reduce phase returned empty — nothing to persist.")
|
logger.warning("Reduce phase returned empty — nothing to persist.")
|
||||||
return
|
return
|
||||||
parsed = parse_reduce_json(master_raw)
|
parsed = parse_reduce_json(master_raw)
|
||||||
selected_articles = [
|
save_batch(
|
||||||
block["article"]
|
|
||||||
for block in selected
|
|
||||||
if isinstance(block.get("article"), dict)
|
|
||||||
]
|
|
||||||
summary_id = save_batch(
|
|
||||||
parsed["summary_en"],
|
parsed["summary_en"],
|
||||||
model,
|
model,
|
||||||
parsed["ticker"],
|
parsed["ticker"],
|
||||||
parsed["map_items"],
|
parsed["map_items"],
|
||||||
kind="daily_recap" if recap else "interval",
|
kind="daily_recap" if recap else "interval",
|
||||||
articles=selected_articles,
|
|
||||||
)
|
)
|
||||||
persist_article_scores(distinct + duplicate_blocks, summary_id=summary_id, model=model)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
||||||
|
|
@ -1,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)
|
|
||||||
|
|
@ -22,42 +22,12 @@ def test_summary_prompt_focuses_on_breaking_news_not_futures():
|
||||||
assert "commodity" in p or "market" in p
|
assert "commodity" in p or "market" in p
|
||||||
|
|
||||||
|
|
||||||
def test_map_prompt_has_the_grading_rubric_and_score_first_block():
|
def test_summary_prompt_covers_critical_then_incidents():
|
||||||
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()
|
p = SUMMARY_PROMPT_DEFAULT.lower()
|
||||||
assert "critical" in p
|
assert "critical" in p
|
||||||
assert "highest-scoring" in p
|
assert "crime" in p
|
||||||
assert "pre-filtered" in p
|
assert "incident" in p
|
||||||
assert "complete" in p or "truncat" in p or "mid-sentence" in p
|
assert "complete" in p or "truncat" in p or "unfinished" in p or "mid-sentence" in p
|
||||||
|
|
||||||
|
|
||||||
def test_summary_prompt_does_not_bail_out_with_canned_empty_brief():
|
def test_summary_prompt_does_not_bail_out_with_canned_empty_brief():
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,10 @@
|
||||||
"""Summarizer window, recap flag, no futures injection, and grading env knobs."""
|
"""Summarizer window, recap flag, and no futures injection into prompts."""
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
import summarizer
|
|
||||||
from summarizer import (
|
from summarizer import (
|
||||||
build_map_prompt,
|
build_map_prompt,
|
||||||
build_master_prompt,
|
build_master_prompt,
|
||||||
effective_window_minutes,
|
effective_window_minutes,
|
||||||
get_recent_news,
|
|
||||||
is_recap_run,
|
is_recap_run,
|
||||||
selection_config,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -52,164 +43,3 @@ def test_build_master_prompt_recap_uses_daily_template():
|
||||||
assert "partial facts" in prompt
|
assert "partial facts" in prompt
|
||||||
assert "daily recap" in prompt.lower()
|
assert "daily recap" in prompt.lower()
|
||||||
assert "24" in prompt
|
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
|
|
||||||
|
|
|
||||||
|
|
@ -30,38 +30,11 @@ os.environ.setdefault("DB_NAME", "osint_data")
|
||||||
# reused across loops, so force a NullPool (new connection per session).
|
# reused across loops, so force a NullPool (new connection per session).
|
||||||
os.environ.setdefault("DB_NULL_POOL", "1")
|
os.environ.setdefault("DB_NULL_POOL", "1")
|
||||||
|
|
||||||
# ── Single-admin auth test configuration ────────────────────────────────────
|
|
||||||
# Admin routes are denied unless a signed session cookie is present, so the
|
|
||||||
# suite needs known credentials + a signing key. Tests that exercise the
|
|
||||||
# "auth not configured" path monkeypatch these away.
|
|
||||||
ADMIN_TEST_USER = "admin"
|
|
||||||
ADMIN_TEST_PASSWORD = "test-admin-password"
|
|
||||||
ADMIN_TEST_SECRET = "test-admin-session-secret-not-for-production"
|
|
||||||
|
|
||||||
from auth import COOKIE_NAME, create_session_token, hash_password, reset_failures # noqa: E402
|
|
||||||
|
|
||||||
os.environ.setdefault("ADMIN_USER", ADMIN_TEST_USER)
|
|
||||||
os.environ.setdefault("ADMIN_PASSWORD_HASH", hash_password(ADMIN_TEST_PASSWORD))
|
|
||||||
os.environ.setdefault("ADMIN_SESSION_SECRET", ADMIN_TEST_SECRET)
|
|
||||||
|
|
||||||
import asyncpg # noqa: E402
|
import asyncpg # noqa: E402
|
||||||
|
|
||||||
pytestmark = []
|
pytestmark = []
|
||||||
|
|
||||||
|
|
||||||
def admin_cookies() -> dict[str, str]:
|
|
||||||
"""A valid admin session cookie value for in-process API calls."""
|
|
||||||
return {COOKIE_NAME: create_session_token(os.environ["ADMIN_USER"])}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def _clear_login_limiter():
|
|
||||||
"""The login limiter is process-global; never leak failures between tests."""
|
|
||||||
reset_failures()
|
|
||||||
yield
|
|
||||||
reset_failures()
|
|
||||||
|
|
||||||
|
|
||||||
def _db_reachable() -> bool:
|
def _db_reachable() -> bool:
|
||||||
try:
|
try:
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
|
||||||
|
|
@ -1,62 +0,0 @@
|
||||||
"""Tests for the idle ADS-B watch sweep.
|
|
||||||
|
|
||||||
Regression: the refresh loop only persisted aircraft for *connected browser
|
|
||||||
viewports*, so ``aircraft_positions`` went silent for a day whenever nobody had
|
|
||||||
the map open (observed 2026-11-20 04:58 -> 2026-11-21). When no viewport is
|
|
||||||
registered the loop must sweep the chokepoint presets instead.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
from chokepoints import chokepoints
|
|
||||||
from live_layers import bbox_center_radius_nm, parse_bbox
|
|
||||||
from main import _adsb_watch_boxes, _adsb_refresh_loop
|
|
||||||
from ws_manager import manager
|
|
||||||
|
|
||||||
|
|
||||||
def test_watch_boxes_cover_every_chokepoint() -> None:
|
|
||||||
boxes = _adsb_watch_boxes()
|
|
||||||
assert len(boxes) == len(chokepoints())
|
|
||||||
for box in boxes:
|
|
||||||
minlon, minlat, maxlon, maxlat = box
|
|
||||||
# Preset catalog order is minlat,minlon,maxlat,maxlon: a lon/lat swap
|
|
||||||
# would put e.g. Hormuz at lat 56 lon 26.
|
|
||||||
assert -90 <= minlat < maxlat <= 90
|
|
||||||
assert -180 <= minlon < maxlon <= 180
|
|
||||||
# ADSB.lol 403s any dist > 250 nm; live_layer clamps to 150 nm.
|
|
||||||
assert bbox_center_radius_nm(minlon, minlat, maxlon, maxlat)[2] <= 150
|
|
||||||
|
|
||||||
|
|
||||||
def test_watch_box_order_matches_catalog() -> None:
|
|
||||||
hormuz = next(p for p in chokepoints() if p["id"] == "hormuz")
|
|
||||||
minlat, minlon, maxlat, maxlon = (float(v) for v in hormuz["bbox"].split(","))
|
|
||||||
assert (minlon, minlat, maxlon, maxlat) in _adsb_watch_boxes()
|
|
||||||
# parse_bbox (the app's viewport order) agrees with the converted box.
|
|
||||||
assert parse_bbox(f"{minlon},{minlat},{maxlon},{maxlat}") == (minlon, minlat, maxlon, maxlat)
|
|
||||||
|
|
||||||
|
|
||||||
def test_idle_loop_polls_watch_boxes(monkeypatch) -> None:
|
|
||||||
"""With no client viewport the loop must call fetch_aircraft(persist=True)."""
|
|
||||||
calls: list[tuple[str, bool]] = []
|
|
||||||
|
|
||||||
async def fake_fetch(bbox: str, limit: int = 2000, persist: bool = False):
|
|
||||||
calls.append((bbox, persist))
|
|
||||||
return []
|
|
||||||
|
|
||||||
monkeypatch.setattr("live_layers.fetch_aircraft", fake_fetch)
|
|
||||||
assert manager.viewports() == []
|
|
||||||
|
|
||||||
async def run() -> None:
|
|
||||||
try:
|
|
||||||
await asyncio.wait_for(_adsb_refresh_loop(), 0.5)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
asyncio.run(run())
|
|
||||||
assert calls, "idle loop persisted nothing"
|
|
||||||
assert all(persist for _, persist in calls)
|
|
||||||
assert {bbox for bbox, _ in calls} == {
|
|
||||||
f"{b[0]},{b[1]},{b[2]},{b[3]}" for b in _adsb_watch_boxes()
|
|
||||||
}
|
|
||||||
|
|
@ -7,22 +7,18 @@ import httpx
|
||||||
from live_layers import overlay_catalog
|
from live_layers import overlay_catalog
|
||||||
from main import app
|
from main import app
|
||||||
|
|
||||||
from conftest import admin_cookies
|
|
||||||
|
|
||||||
BASE = "http://test"
|
BASE = "http://test"
|
||||||
|
|
||||||
|
|
||||||
async def _get(path: str) -> httpx.Response:
|
async def _get(path: str) -> httpx.Response:
|
||||||
transport = httpx.ASGITransport(app=app)
|
transport = httpx.ASGITransport(app=app)
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||||||
client.cookies.update(admin_cookies())
|
|
||||||
return await client.get(path)
|
return await client.get(path)
|
||||||
|
|
||||||
|
|
||||||
async def _post(path: str, payload: dict | None) -> httpx.Response:
|
async def _post(path: str, payload: dict | None) -> httpx.Response:
|
||||||
transport = httpx.ASGITransport(app=app)
|
transport = httpx.ASGITransport(app=app)
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||||||
client.cookies.update(admin_cookies())
|
|
||||||
return await client.post(path, json=payload)
|
return await client.post(path, json=payload)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import os
|
import os
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
import asyncpg
|
import asyncpg
|
||||||
import httpx
|
import httpx
|
||||||
|
|
@ -157,70 +157,6 @@ def test_api_news_since_filter(clean_news):
|
||||||
assert body[0]["title"] == "after"
|
assert body[0]["title"] == "after"
|
||||||
|
|
||||||
|
|
||||||
@requires_db
|
|
||||||
def test_api_news_excludes_future_dated_rows(clean_news):
|
|
||||||
"""Future-dated event listings must not pin the top of the feed."""
|
|
||||||
now = datetime.now(timezone.utc)
|
|
||||||
future = now + timedelta(days=5)
|
|
||||||
recent = now - timedelta(hours=1)
|
|
||||||
_seed_article("recent", "https://a.example/recent", "a.example", recent.isoformat())
|
|
||||||
_seed_article("future", "https://a.example/future", "a.example", future.isoformat())
|
|
||||||
|
|
||||||
body = _get("/api/news").json()
|
|
||||||
assert [a["title"] for a in body] == ["recent"]
|
|
||||||
|
|
||||||
# limit still caps the (post-filter) result set
|
|
||||||
_seed_article("recent2", "https://a.example/recent2", "a.example", (now - timedelta(hours=2)).isoformat())
|
|
||||||
_seed_article("recent3", "https://a.example/recent3", "a.example", (now - timedelta(hours=3)).isoformat())
|
|
||||||
limited = _get("/api/news?limit=2").json()
|
|
||||||
assert [a["title"] for a in limited] == ["recent", "recent2"]
|
|
||||||
|
|
||||||
|
|
||||||
@requires_db
|
|
||||||
def test_api_news_unwraps_stored_cdata_title(clean_news):
|
|
||||||
"""Dirty rows are fixed on read. A plain title, and HTML that is not a
|
|
||||||
CDATA wrapper, are returned unchanged. No UPDATE of historical rows.
|
|
||||||
"""
|
|
||||||
stored = "\n <![CDATA[Hello]]> "
|
|
||||||
_seed_article(
|
|
||||||
stored,
|
|
||||||
"https://www.excelsior.com.mx/cdata",
|
|
||||||
"www.excelsior.com.mx",
|
|
||||||
"2026-08-24T18:00:00+00:00",
|
|
||||||
)
|
|
||||||
_seed_article(
|
|
||||||
"Hello",
|
|
||||||
"https://a.example/plain",
|
|
||||||
"a.example",
|
|
||||||
"2026-08-24T17:00:00+00:00",
|
|
||||||
)
|
|
||||||
_seed_article(
|
|
||||||
"<b>Keep</b>",
|
|
||||||
"https://a.example/html",
|
|
||||||
"a.example",
|
|
||||||
"2026-08-24T16:00:00+00:00",
|
|
||||||
)
|
|
||||||
|
|
||||||
body = _get("/api/news").json()
|
|
||||||
by_url = {row["url"]: row["title"] for row in body}
|
|
||||||
assert by_url["https://www.excelsior.com.mx/cdata"] == "Hello"
|
|
||||||
assert by_url["https://a.example/plain"] == "Hello"
|
|
||||||
assert by_url["https://a.example/html"] == "<b>Keep</b>"
|
|
||||||
|
|
||||||
# Read-path only: the stored row stays dirty.
|
|
||||||
async def _stored_title() -> str:
|
|
||||||
conn = await asyncpg.connect(**_conn_kwargs())
|
|
||||||
try:
|
|
||||||
return await conn.fetchval(
|
|
||||||
"SELECT title FROM articles WHERE url = $1",
|
|
||||||
"https://www.excelsior.com.mx/cdata",
|
|
||||||
)
|
|
||||||
finally:
|
|
||||||
await conn.close()
|
|
||||||
|
|
||||||
assert asyncio.run(_stored_title()) == stored
|
|
||||||
|
|
||||||
|
|
||||||
@requires_db
|
@requires_db
|
||||||
def test_api_news_summaries_contract(clean_news):
|
def test_api_news_summaries_contract(clean_news):
|
||||||
_seed_summary("master summary markdown…", "2026-08-24T18:05:00+00:00")
|
_seed_summary("master summary markdown…", "2026-08-24T18:05:00+00:00")
|
||||||
|
|
|
||||||
|
|
@ -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
|
|
||||||
|
|
@ -9,7 +9,7 @@ import asyncpg
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from conftest import admin_cookies, requires_db
|
from conftest import requires_db
|
||||||
|
|
||||||
from main import app
|
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:
|
async def _run() -> httpx.Response:
|
||||||
transport = httpx.ASGITransport(app=app)
|
transport = httpx.ASGITransport(app=app)
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||||||
client.cookies.update(admin_cookies())
|
|
||||||
return await client.request(method, path, json=json)
|
return await client.request(method, path, json=json)
|
||||||
|
|
||||||
return asyncio.run(_run())
|
return asyncio.run(_run())
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ from datetime import timezone
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from main import app, _stats_counts, _stats_cache
|
from main import app, _stats_counts
|
||||||
|
|
||||||
BASE = "http://test"
|
BASE = "http://test"
|
||||||
|
|
||||||
|
|
@ -84,80 +84,4 @@ def test_stats_db_failure_degrades_to_zero(monkeypatch):
|
||||||
assert body["cameras"] == 0
|
assert body["cameras"] == 0
|
||||||
assert body["fires"] == 0
|
assert body["fires"] == 0
|
||||||
assert body["quakes"] == 0
|
assert body["quakes"] == 0
|
||||||
assert isinstance(body["timestamp"], str)
|
assert isinstance(body["timestamp"], str)
|
||||||
|
|
||||||
|
|
||||||
def _clear_stats_cache() -> None:
|
|
||||||
_stats_cache.clear()
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_feeds_unconfigured_without_keys(monkeypatch):
|
|
||||||
"""No stored AIS/FIRMS key → both flags false; existing counters stay.
|
|
||||||
|
|
||||||
Env vars do not count. The HUD flag is the api_keys store only.
|
|
||||||
"""
|
|
||||||
monkeypatch.setenv("FIRMS_MAP_KEY", "env-firms-should-not-count")
|
|
||||||
monkeypatch.setenv("AISSTREAM_API_KEY", "env-ais-should-not-count")
|
|
||||||
monkeypatch.setenv("VESSELAPI_API_KEY", "env-vessel-should-not-count")
|
|
||||||
|
|
||||||
async def _unset(name: str):
|
|
||||||
if name == "FIRMS_MAP_KEY":
|
|
||||||
return " "
|
|
||||||
return None
|
|
||||||
|
|
||||||
monkeypatch.setattr("keystore.get_api_key", _unset)
|
|
||||||
_clear_stats_cache()
|
|
||||||
resp = asyncio.run(_get("/api/stats"))
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
for key in EXPECTED_KEYS:
|
|
||||||
assert key in body, f"missing key {key}"
|
|
||||||
assert body["feeds"] == {
|
|
||||||
"vessels": {"configured": False},
|
|
||||||
"fires": {"configured": False},
|
|
||||||
}
|
|
||||||
assert "trains" not in body["feeds"]
|
|
||||||
assert "env-firms-should-not-count" not in resp.text
|
|
||||||
assert "env-ais-should-not-count" not in resp.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_feeds_fires_configured_does_not_leak_key(monkeypatch):
|
|
||||||
secret = "firms-map-key-do-not-leak-9f3a2c1b"
|
|
||||||
|
|
||||||
async def _keys(name: str):
|
|
||||||
if name == "FIRMS_MAP_KEY":
|
|
||||||
return secret
|
|
||||||
return None
|
|
||||||
|
|
||||||
monkeypatch.setattr("keystore.get_api_key", _keys)
|
|
||||||
_clear_stats_cache()
|
|
||||||
resp = asyncio.run(_get("/api/stats"))
|
|
||||||
body = resp.json()
|
|
||||||
assert body["feeds"]["fires"]["configured"] is True
|
|
||||||
assert body["feeds"]["vessels"]["configured"] is False
|
|
||||||
assert secret not in resp.text
|
|
||||||
assert secret[-4:] not in resp.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_stats_feeds_vessels_configured_from_either_key(monkeypatch):
|
|
||||||
async def _ais_only(name: str):
|
|
||||||
if name == "AISSTREAM_API_KEY":
|
|
||||||
return "aisstream-stored-value"
|
|
||||||
return None
|
|
||||||
|
|
||||||
monkeypatch.setattr("keystore.get_api_key", _ais_only)
|
|
||||||
_clear_stats_cache()
|
|
||||||
body = asyncio.run(_get("/api/stats")).json()
|
|
||||||
assert body["feeds"]["vessels"]["configured"] is True
|
|
||||||
assert body["feeds"]["fires"]["configured"] is False
|
|
||||||
|
|
||||||
async def _vesselapi_only(name: str):
|
|
||||||
if name == "VESSELAPI_API_KEY":
|
|
||||||
return "vesselapi-stored-value"
|
|
||||||
return ""
|
|
||||||
|
|
||||||
monkeypatch.setattr("keystore.get_api_key", _vesselapi_only)
|
|
||||||
_clear_stats_cache()
|
|
||||||
body = asyncio.run(_get("/api/stats")).json()
|
|
||||||
assert body["feeds"]["vessels"]["configured"] is True
|
|
||||||
assert body["feeds"]["fires"]["configured"] is False
|
|
||||||
|
|
@ -1,549 +0,0 @@
|
||||||
"""Single-admin auth tests: public read-only site, admin-only everything else.
|
|
||||||
|
|
||||||
Driven in-process through ``httpx.ASGITransport`` exactly like the other API
|
|
||||||
tests. No database is required: the few routes under test that would query
|
|
||||||
Postgres are stubbed with a no-row fake session, so this file runs on a bare
|
|
||||||
checkout.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import time
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
from conftest import ADMIN_TEST_PASSWORD, ADMIN_TEST_USER, admin_cookies
|
|
||||||
|
|
||||||
import auth
|
|
||||||
from main import app
|
|
||||||
|
|
||||||
BASE = "http://test"
|
|
||||||
NOUS_KEY_PATH = "/api/keys/NOUS_API_KEY"
|
|
||||||
|
|
||||||
|
|
||||||
# ── Helpers ─────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
class _FakeResult:
|
|
||||||
def mappings(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
def all(self):
|
|
||||||
return []
|
|
||||||
|
|
||||||
def scalar(self):
|
|
||||||
return 0
|
|
||||||
|
|
||||||
def scalars(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
def unique(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
def one_or_none(self):
|
|
||||||
return None
|
|
||||||
|
|
||||||
def scalar_one_or_none(self):
|
|
||||||
return None
|
|
||||||
|
|
||||||
def __iter__(self):
|
|
||||||
return iter(())
|
|
||||||
|
|
||||||
|
|
||||||
class _FakeSession:
|
|
||||||
async def __aenter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
async def __aexit__(self, *exc):
|
|
||||||
return False
|
|
||||||
|
|
||||||
async def execute(self, *args, **kwargs):
|
|
||||||
return _FakeResult()
|
|
||||||
|
|
||||||
async def commit(self):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _fake_session(*args, **kwargs):
|
|
||||||
return _FakeSession()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
|
||||||
def no_db(monkeypatch):
|
|
||||||
"""Stub the DB session + key/settings stores so reads succeed offline."""
|
|
||||||
import main
|
|
||||||
|
|
||||||
monkeypatch.setattr(main, "async_session", _fake_session)
|
|
||||||
|
|
||||||
async def _empty_keys():
|
|
||||||
return []
|
|
||||||
|
|
||||||
async def _settings():
|
|
||||||
return {"summary_model": "Hermes-4.3-36B",
|
|
||||||
"nous_base_url": "https://inference-api.nousresearch.com/v1"}
|
|
||||||
|
|
||||||
async def _set_model(model: str):
|
|
||||||
return {"summary_model": model,
|
|
||||||
"nous_base_url": "https://inference-api.nousresearch.com/v1"}
|
|
||||||
|
|
||||||
monkeypatch.setattr(main, "list_keys", _empty_keys)
|
|
||||||
monkeypatch.setattr(main, "get_app_settings", _settings)
|
|
||||||
monkeypatch.setattr(main, "set_summary_model", _set_model)
|
|
||||||
|
|
||||||
|
|
||||||
def _request(method: str, path: str, *, cookies=None, json=None, headers=None,
|
|
||||||
data=None) -> httpx.Response:
|
|
||||||
async def _run() -> httpx.Response:
|
|
||||||
transport = httpx.ASGITransport(app=app)
|
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
|
||||||
if cookies:
|
|
||||||
client.cookies.update(cookies)
|
|
||||||
return await client.request(
|
|
||||||
method, path, json=json, headers=headers, data=data,
|
|
||||||
)
|
|
||||||
|
|
||||||
return asyncio.run(_run())
|
|
||||||
|
|
||||||
|
|
||||||
def _login(password: str = ADMIN_TEST_PASSWORD, username: str = ADMIN_TEST_USER,
|
|
||||||
headers=None, form: bool = True) -> httpx.Response:
|
|
||||||
if form:
|
|
||||||
return _request(
|
|
||||||
"POST", "/api/auth/login",
|
|
||||||
data={"username": username, "password": password}, headers=headers,
|
|
||||||
)
|
|
||||||
return _request(
|
|
||||||
"POST", "/api/auth/login", json={"username": username, "password": password},
|
|
||||||
headers=headers,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ── Anonymous: public reads ─────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def test_anonymous_can_read_news(no_db):
|
|
||||||
resp = _request("GET", "/api/news")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert resp.json() == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_anonymous_can_read_public_allowlist(no_db):
|
|
||||||
# Every documented public read must pass the gate (handler errors from the
|
|
||||||
# stubbed DB are irrelevant here — 401/403/redirects are the failure modes).
|
|
||||||
async def _run() -> dict[str, int]:
|
|
||||||
# raise_app_exceptions=False: handler errors from the stubbed DB are
|
|
||||||
# irrelevant here — 401/403/redirects are the failure modes.
|
|
||||||
transport = httpx.ASGITransport(app=app, raise_app_exceptions=False)
|
|
||||||
|
|
||||||
out: dict[str, int] = {}
|
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
|
||||||
for path in (
|
|
||||||
"/api/health",
|
|
||||||
"/api/map/layers",
|
|
||||||
"/api/map/chokepoints",
|
|
||||||
"/api/news",
|
|
||||||
"/api/news/ticker",
|
|
||||||
"/api/news/map",
|
|
||||||
"/api/news/blips",
|
|
||||||
"/api/geofences",
|
|
||||||
"/api/geofence-alerts",
|
|
||||||
"/api/analytics/summary",
|
|
||||||
"/api/tracks/range",
|
|
||||||
"/api/fire-aircraft",
|
|
||||||
):
|
|
||||||
out[path] = (await client.get(path)).status_code
|
|
||||||
return out
|
|
||||||
|
|
||||||
statuses = asyncio.run(_run())
|
|
||||||
for path, status in statuses.items():
|
|
||||||
assert status not in (401, 403, 307), f"{path} -> {status}"
|
|
||||||
|
|
||||||
# DB-free reads answer for real.
|
|
||||||
for path in ("/api/news", "/api/map/layers", "/api/map/chokepoints"):
|
|
||||||
assert _request("GET", path).status_code == 200, path
|
|
||||||
|
|
||||||
|
|
||||||
SPEC_PUBLIC_READS = (
|
|
||||||
"/api/health", "/api/ready", "/api/events", "/api/fires", "/api/sources",
|
|
||||||
"/api/entities", "/api/alerts", "/api/documents",
|
|
||||||
"/api/analytics/summary", "/api/analytics/timeline",
|
|
||||||
"/api/analytics/sentiment/by-source", "/api/cameras",
|
|
||||||
"/api/news", "/api/news/summaries", "/api/news/ticker", "/api/news/map",
|
|
||||||
"/api/news/blips",
|
|
||||||
"/api/map/layers", "/api/map/chokepoints", "/api/map/radar",
|
|
||||||
"/api/map/sentinel1", "/api/aircraft", "/api/aircraft/photo",
|
|
||||||
"/api/trains", "/api/vessels", "/api/tracks/range", "/api/geofences",
|
|
||||||
"/api/geofence-alerts", "/api/fire-aircraft",
|
|
||||||
"/api/events/11111111-1111-1111-1111-111111111111",
|
|
||||||
"/api/entities/11111111-1111-1111-1111-111111111111",
|
|
||||||
"/api/entities/11111111-1111-1111-1111-111111111111/events",
|
|
||||||
"/api/cameras/abc", "/api/cameras/abc/snapshot",
|
|
||||||
"/api/cameras/abc/stream", "/api/cameras/abc/hls.m3u8",
|
|
||||||
"/api/cameras/abc/hlsseg",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def test_public_allowlist_covers_the_spec():
|
|
||||||
for path in SPEC_PUBLIC_READS:
|
|
||||||
assert auth.is_public(path, "GET"), path
|
|
||||||
|
|
||||||
|
|
||||||
def test_public_post_search_is_read_only(no_db):
|
|
||||||
resp = _request("POST", "/api/search", json={"q": "fire", "limit": 5})
|
|
||||||
assert resp.status_code not in (401, 403)
|
|
||||||
|
|
||||||
|
|
||||||
def test_anonymous_can_load_hud():
|
|
||||||
resp = _request("GET", "/")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert "text/html" in resp.headers["content-type"]
|
|
||||||
assert "OSINT" in resp.text
|
|
||||||
assert 'id="view-map"' in resp.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_login_page_is_public():
|
|
||||||
resp = _request("GET", "/login")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert "Sign in" in resp.text
|
|
||||||
assert resp.headers.get("cache-control") == "no-store"
|
|
||||||
assert 'name="username"' in resp.text and 'name="password"' in resp.text
|
|
||||||
assert "/api/auth/login" in resp.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_hud_gates_admin_chrome_client_side():
|
|
||||||
"""Spec item 5: UX hiding is markup-driven and fails closed."""
|
|
||||||
html = _request("GET", "/").text
|
|
||||||
# Fails closed without JS: data-admin is hidden unless body.is-admin.
|
|
||||||
assert "body:not(.is-admin) [data-admin]" in html
|
|
||||||
# Admin nav entries (API Keys is the headline requirement) are marked.
|
|
||||||
for view in ("keys", "ingest", "settings"):
|
|
||||||
assert f'data-view="{view}" data-admin' in html, view
|
|
||||||
# Keys view, ingest view and the summarizer panel are gated too.
|
|
||||||
assert 'id="view-keys" aria-label="API keys" data-admin' in html
|
|
||||||
assert 'id="view-ingest" aria-label="Ingest" data-admin' in html
|
|
||||||
# Discreet sign-in link + the /api/auth/me probe that reveals admin chrome.
|
|
||||||
assert 'id="admin-link"' in html and 'href="/login"' in html
|
|
||||||
assert "/api/auth/me" in html
|
|
||||||
|
|
||||||
|
|
||||||
def test_static_assets_are_public():
|
|
||||||
assert _request("GET", "/static/index.html").status_code == 200
|
|
||||||
|
|
||||||
|
|
||||||
# ── Anonymous: admin surface is closed ──────────────────────────────────────
|
|
||||||
|
|
||||||
def test_anonymous_keys_read_is_401():
|
|
||||||
resp = _request("GET", "/api/keys")
|
|
||||||
assert resp.status_code == 401
|
|
||||||
assert resp.headers["content-type"].startswith("application/json")
|
|
||||||
assert "detail" in resp.json()
|
|
||||||
|
|
||||||
|
|
||||||
def test_anonymous_keys_write_is_401():
|
|
||||||
resp = _request("POST", NOUS_KEY_PATH, json={"value": "sk-nope-1234567890"})
|
|
||||||
assert resp.status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
def test_anonymous_keys_delete_is_401():
|
|
||||||
assert _request("DELETE", NOUS_KEY_PATH).status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
def test_anonymous_settings_write_is_401():
|
|
||||||
resp = _request("PUT", "/api/settings", json={"summary_model": "x/y-z"})
|
|
||||||
assert resp.status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
def test_anonymous_settings_read_is_401():
|
|
||||||
assert _request("GET", "/api/settings").status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
def test_anonymous_news_models_is_401():
|
|
||||||
# /api/news/models spends the stored Nous key — never public.
|
|
||||||
assert _request("GET", "/api/news/models").status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
def test_anonymous_state_changing_routes_are_401():
|
|
||||||
cases = [
|
|
||||||
("POST", "/api/sources", {"name": "x", "url": "https://example.com/feed", "source_type": "rss"}),
|
|
||||||
("POST", "/api/events", {"source_type": "rss", "title": "x"}),
|
|
||||||
("POST", "/api/entities", {"name": "x", "entity_type": "person"}),
|
|
||||||
("POST", "/api/alerts", {"alert_type": "keyword", "severity": "low", "title": "x"}),
|
|
||||||
("POST", "/api/geofences", {"name": "x", "geojson": {"type": "Point", "coordinates": [0, 0]}}),
|
|
||||||
("PATCH", "/api/geofences/abc", {"name": "y"}),
|
|
||||||
("DELETE", "/api/geofences/abc", None),
|
|
||||||
("POST", "/api/vessels/subscribe", {"bbox": "-70,40,-60,45"}),
|
|
||||||
("POST", "/api/ingest/rss", None),
|
|
||||||
("POST", "/api/ingest/earthquakes", None),
|
|
||||||
("POST", "/api/ingest/process", None),
|
|
||||||
]
|
|
||||||
for method, path, body in cases:
|
|
||||||
resp = _request(method, path, json=body)
|
|
||||||
assert resp.status_code == 401, f"{method} {path} -> {resp.status_code}"
|
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_api_path_is_denied_anonymously():
|
|
||||||
assert _request("GET", "/api/does-not-exist").status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
# ── /api/auth/me ────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def test_auth_me_anonymous():
|
|
||||||
resp = _request("GET", "/api/auth/me")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert resp.json() == {"authenticated": False, "admin": False}
|
|
||||||
|
|
||||||
|
|
||||||
def test_auth_me_with_session():
|
|
||||||
resp = _request("GET", "/api/auth/me", cookies=admin_cookies())
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert resp.json() == {"authenticated": True, "admin": True}
|
|
||||||
|
|
||||||
|
|
||||||
# ── Login / logout ──────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def test_login_wrong_password_is_401():
|
|
||||||
resp = _login(password="wrong-password")
|
|
||||||
assert resp.status_code == 401
|
|
||||||
assert "invalid credentials" in resp.json()["detail"]
|
|
||||||
assert auth.COOKIE_NAME not in resp.cookies
|
|
||||||
|
|
||||||
|
|
||||||
def test_login_wrong_username_is_401():
|
|
||||||
resp = _login(username="root")
|
|
||||||
assert resp.status_code == 401
|
|
||||||
# Generic message: never reveal which half was wrong / that the user exists.
|
|
||||||
assert "root" not in resp.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_login_missing_fields_is_401_not_500():
|
|
||||||
resp = _request("POST", "/api/auth/login", data={})
|
|
||||||
assert resp.status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
def test_login_success_sets_httponly_cookie(monkeypatch):
|
|
||||||
monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False)
|
|
||||||
resp = _login()
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert resp.json() == {"authenticated": True, "admin": True}
|
|
||||||
raw = resp.headers.get("set-cookie", "")
|
|
||||||
assert auth.COOKIE_NAME in raw
|
|
||||||
assert "HttpOnly" in raw
|
|
||||||
assert "SameSite=lax" in raw.replace("samesite=lax", "SameSite=lax")
|
|
||||||
assert "Path=/" in raw
|
|
||||||
assert "Secure" not in raw # plain http in tests
|
|
||||||
assert resp.cookies.get(auth.COOKIE_NAME)
|
|
||||||
|
|
||||||
|
|
||||||
def test_login_accepts_json_body():
|
|
||||||
resp = _login(form=False)
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert resp.json()["authenticated"] is True
|
|
||||||
|
|
||||||
|
|
||||||
def test_login_cookie_marks_secure_behind_https_proxy(monkeypatch):
|
|
||||||
monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False)
|
|
||||||
resp = _login(headers={"X-Forwarded-Proto": "https"})
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert "Secure" in resp.headers.get("set-cookie", "")
|
|
||||||
|
|
||||||
|
|
||||||
def test_login_cookie_secure_via_env_flag_over_http_origin(monkeypatch):
|
|
||||||
"""ADMIN_COOKIE_SECURE is what makes the cookie Secure in the cluster:
|
|
||||||
the header arrives as ``http`` from the Cilium Gateway."""
|
|
||||||
monkeypatch.setenv("ADMIN_COOKIE_SECURE", "1")
|
|
||||||
resp = _login(headers={"X-Forwarded-Proto": "http"})
|
|
||||||
assert resp.status_code == 200
|
|
||||||
raw = resp.headers.get("set-cookie", "")
|
|
||||||
assert "Secure" in raw
|
|
||||||
assert "SameSite=lax" in raw.replace("samesite=lax", "SameSite=lax")
|
|
||||||
assert "HttpOnly" in raw
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("value", ["true", "TRUE", " Yes ", "yes"])
|
|
||||||
def test_login_cookie_env_flag_accepts_truthy_spellings(monkeypatch, value):
|
|
||||||
monkeypatch.setenv("ADMIN_COOKIE_SECURE", value)
|
|
||||||
resp = _login()
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert "Secure" in resp.headers.get("set-cookie", "")
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("value", ["", "0", "false", "no", "off"])
|
|
||||||
def test_login_cookie_env_flag_ignores_falsey_spellings(monkeypatch, value):
|
|
||||||
monkeypatch.setenv("ADMIN_COOKIE_SECURE", value)
|
|
||||||
resp = _login(headers={"X-Forwarded-Proto": "http"})
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert "Secure" not in resp.headers.get("set-cookie", "")
|
|
||||||
|
|
||||||
|
|
||||||
def test_login_cookie_without_header_or_flag_is_not_secure_locally(monkeypatch):
|
|
||||||
monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False)
|
|
||||||
resp = _login()
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert "Secure" not in resp.headers.get("set-cookie", "")
|
|
||||||
|
|
||||||
|
|
||||||
def test_session_cookie_unlocks_admin_routes(no_db):
|
|
||||||
login = _login()
|
|
||||||
cookie = {auth.COOKIE_NAME: login.cookies.get(auth.COOKIE_NAME)}
|
|
||||||
assert _request("GET", "/api/keys", cookies=cookie).status_code == 200
|
|
||||||
assert _request("PUT", "/api/settings",
|
|
||||||
json={"summary_model": "m"}, cookies=cookie).status_code == 200
|
|
||||||
assert _request("GET", "/api/settings", cookies=cookie).status_code == 200
|
|
||||||
|
|
||||||
|
|
||||||
def test_logout_clears_session(no_db):
|
|
||||||
login = _login()
|
|
||||||
cookie = {auth.COOKIE_NAME: login.cookies.get(auth.COOKIE_NAME)}
|
|
||||||
out = _request("POST", "/api/auth/logout", cookies=cookie)
|
|
||||||
assert out.status_code == 200
|
|
||||||
assert out.json() == {"authenticated": False, "admin": False}
|
|
||||||
assert "Max-Age=0" in out.headers.get("set-cookie", "") or "expires" in \
|
|
||||||
out.headers.get("set-cookie", "").lower()
|
|
||||||
# A cleared cookie no longer authenticates (simulate the browser dropping it).
|
|
||||||
assert _request("GET", "/api/keys", cookies={}).status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
def test_tampered_cookie_is_401():
|
|
||||||
login = _login()
|
|
||||||
token = login.cookies.get(auth.COOKIE_NAME)
|
|
||||||
body, signature = token.rsplit(".", 1)
|
|
||||||
tampered = f"{body}.{'A' * len(signature)}"
|
|
||||||
assert _request("GET", "/api/keys", cookies={auth.COOKIE_NAME: tampered}).status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
def test_cookie_for_another_user_is_401(monkeypatch):
|
|
||||||
forged = auth.create_session_token("intruder")
|
|
||||||
assert _request("GET", "/api/keys",
|
|
||||||
cookies={auth.COOKIE_NAME: forged}).status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
def test_expired_token_is_rejected():
|
|
||||||
token = auth.create_session_token(ADMIN_TEST_USER, now=time.time() - auth.SESSION_TTL_SECONDS - 5)
|
|
||||||
assert auth.verify_session_token(token) is None
|
|
||||||
|
|
||||||
|
|
||||||
# ── Fail closed ─────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def test_admin_env_unset_fails_closed(monkeypatch, no_db):
|
|
||||||
monkeypatch.delenv("ADMIN_PASSWORD_HASH", raising=False)
|
|
||||||
monkeypatch.delenv("ADMIN_SESSION_SECRET", raising=False)
|
|
||||||
|
|
||||||
resp = _request("GET", "/api/keys")
|
|
||||||
assert resp.status_code == 403
|
|
||||||
assert resp.json() == {"detail": "admin auth not configured"}
|
|
||||||
|
|
||||||
# Public site keeps working, and /login explains the situation.
|
|
||||||
assert _request("GET", "/api/news").status_code == 200
|
|
||||||
page = _request("GET", "/login")
|
|
||||||
assert page.status_code == 200
|
|
||||||
assert "not configured" in page.text
|
|
||||||
|
|
||||||
|
|
||||||
def test_login_without_password_hash_is_403(monkeypatch):
|
|
||||||
monkeypatch.delenv("ADMIN_PASSWORD_HASH", raising=False)
|
|
||||||
resp = _login()
|
|
||||||
assert resp.status_code == 403
|
|
||||||
assert resp.json() == {"detail": "admin auth not configured"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_session_secret_unset_invalidates_existing_cookie(monkeypatch):
|
|
||||||
cookie = admin_cookies()
|
|
||||||
monkeypatch.delenv("ADMIN_SESSION_SECRET", raising=False)
|
|
||||||
resp = _request("GET", "/api/keys", cookies=cookie)
|
|
||||||
assert resp.status_code == 403
|
|
||||||
assert resp.json() == {"detail": "admin auth not configured"}
|
|
||||||
|
|
||||||
|
|
||||||
# ── Rate limiting ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def test_rate_limit_after_five_failures():
|
|
||||||
for attempt in range(5):
|
|
||||||
assert _login(password="nope").status_code == 401, f"attempt {attempt}"
|
|
||||||
assert _login(password="nope").status_code == 429
|
|
||||||
# Correct credentials are refused too while the window is open.
|
|
||||||
assert _login().status_code == 429
|
|
||||||
|
|
||||||
|
|
||||||
def test_rate_limit_is_per_client_ip():
|
|
||||||
for _ in range(5):
|
|
||||||
_login(password="nope", headers={"X-Forwarded-For": "203.0.113.9"})
|
|
||||||
assert _login(password="nope", headers={"X-Forwarded-For": "203.0.113.9"}).status_code == 429
|
|
||||||
# A different client is unaffected.
|
|
||||||
assert _login(password="nope", headers={"X-Forwarded-For": "203.0.113.10"}).status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
def test_logout_does_not_reset_the_login_limiter():
|
|
||||||
"""Regression: logout is unauthenticated — it must not clear lockouts."""
|
|
||||||
for _ in range(5):
|
|
||||||
assert _login(password="nope").status_code == 401
|
|
||||||
assert _request("POST", "/api/auth/logout").status_code == 200
|
|
||||||
assert _login().status_code == 429
|
|
||||||
|
|
||||||
|
|
||||||
def test_non_ascii_garbage_cookie_is_rejected_not_500():
|
|
||||||
assert auth.verify_session_token("abc.\u00e9\u00e9\u00e9") is None
|
|
||||||
assert auth.verify_session_token("\u00e9\u00e9\u00e9") is None
|
|
||||||
resp = _request("GET", "/api/keys", cookies={auth.COOKIE_NAME: "garbage"})
|
|
||||||
assert resp.status_code == 401
|
|
||||||
|
|
||||||
|
|
||||||
# ── CSRF ────────────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def test_cross_origin_admin_write_is_403(no_db):
|
|
||||||
cookies = admin_cookies()
|
|
||||||
resp = _request("PUT", "/api/settings", json={"summary_model": "m"},
|
|
||||||
cookies=cookies, headers={"Origin": "https://evil.example"})
|
|
||||||
assert resp.status_code == 403
|
|
||||||
assert "cross-origin" in resp.json()["detail"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_same_origin_admin_write_is_allowed(no_db):
|
|
||||||
cookies = admin_cookies()
|
|
||||||
resp = _request("PUT", "/api/settings", json={"summary_model": "m"},
|
|
||||||
cookies=cookies, headers={"Origin": BASE})
|
|
||||||
assert resp.status_code == 200
|
|
||||||
|
|
||||||
|
|
||||||
def test_same_host_referer_admin_write_is_allowed(no_db):
|
|
||||||
cookies = admin_cookies()
|
|
||||||
resp = _request("PUT", "/api/settings", json={"summary_model": "m"},
|
|
||||||
cookies=cookies, headers={"Referer": f"{BASE}/login"})
|
|
||||||
assert resp.status_code == 200
|
|
||||||
|
|
||||||
|
|
||||||
# ── Unit: hashing + token helpers ───────────────────────────────────────────
|
|
||||||
|
|
||||||
def test_password_hash_round_trip():
|
|
||||||
stored = auth.hash_password("s3cret-pw", iterations=2000)
|
|
||||||
assert stored.startswith("pbkdf2_sha256$")
|
|
||||||
assert auth.verify_password("s3cret-pw", stored)
|
|
||||||
assert not auth.verify_password("s3cret-pW", stored)
|
|
||||||
assert not auth.verify_password("", stored)
|
|
||||||
|
|
||||||
|
|
||||||
def test_password_hash_rejects_malformed_values():
|
|
||||||
for bad in ("", "plain", "pbkdf2_sha256$abc$x$y", "md5$1$a$b",
|
|
||||||
"pbkdf2_sha256$0$AAAA$AAAA"):
|
|
||||||
assert not auth.verify_password("x", bad)
|
|
||||||
|
|
||||||
|
|
||||||
def test_session_token_round_trip():
|
|
||||||
token = auth.create_session_token(ADMIN_TEST_USER)
|
|
||||||
assert auth.verify_session_token(token) == ADMIN_TEST_USER
|
|
||||||
assert auth.verify_session_token(token + "x") is None
|
|
||||||
assert auth.verify_session_token(None) is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_public_allowlist_classification():
|
|
||||||
assert auth.is_public("/api/news", "GET")
|
|
||||||
assert auth.is_public("/api/news/", "GET")
|
|
||||||
assert auth.is_public("/api/events/abc-123", "GET")
|
|
||||||
assert auth.is_public("/api/cameras/abc/hls.m3u8", "GET")
|
|
||||||
assert auth.is_public("/api/search", "POST")
|
|
||||||
assert not auth.is_public("/api/news/models", "GET")
|
|
||||||
assert not auth.is_public("/api/keys", "GET")
|
|
||||||
assert not auth.is_public("/api/settings", "GET")
|
|
||||||
assert not auth.is_public("/api/ingest/rss", "POST")
|
|
||||||
assert not auth.is_public("/api/vessels/subscribe", "POST")
|
|
||||||
assert not auth.is_public("/api/geofences", "POST")
|
|
||||||
assert auth.is_public("/ws/live", "GET")
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
"""ffmpeg snapshots stay off the request path (asyncio.create_task)."""
|
"""masscan/ffmpeg stay off the request path (asyncio.create_task)."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
@ -7,27 +7,36 @@ import asyncio
|
||||||
import bg_jobs
|
import bg_jobs
|
||||||
|
|
||||||
|
|
||||||
def test_bg_jobs_has_no_pps_cap():
|
def test_schedule_masscan_pass_returns_without_awaiting_scan(monkeypatch):
|
||||||
assert not any(name.endswith("_PPS_CAP") for name in dir(bg_jobs))
|
started = {"n": 0}
|
||||||
|
|
||||||
|
async def slow_pass():
|
||||||
|
started["n"] += 1
|
||||||
|
await asyncio.sleep(30)
|
||||||
|
|
||||||
|
monkeypatch.setattr(bg_jobs, "_run_masscan_capped", slow_pass)
|
||||||
|
bg_jobs._masscan_task = None
|
||||||
|
|
||||||
|
async def run():
|
||||||
|
launched = bg_jobs.schedule_masscan_pass()
|
||||||
|
assert launched is True
|
||||||
|
# Must not have blocked for the 30s pass.
|
||||||
|
assert bg_jobs._masscan_task is not None
|
||||||
|
assert not bg_jobs._masscan_task.done()
|
||||||
|
launched2 = bg_jobs.schedule_masscan_pass()
|
||||||
|
assert launched2 is False # already running
|
||||||
|
bg_jobs._masscan_task.cancel()
|
||||||
|
try:
|
||||||
|
await bg_jobs._masscan_task
|
||||||
|
except (asyncio.CancelledError, Exception):
|
||||||
|
pass
|
||||||
|
bg_jobs._masscan_task = None
|
||||||
|
|
||||||
|
asyncio.run(run())
|
||||||
|
|
||||||
|
|
||||||
def test_camera_preview_has_no_public_feed_probe():
|
def test_masscan_rate_cap_is_200():
|
||||||
import camera_preview
|
assert bg_jobs.MASSCAN_PPS_CAP == 200
|
||||||
|
|
||||||
assert not hasattr(camera_preview, "probe_public_feed")
|
|
||||||
assert not hasattr(camera_preview, "_http_feed_url")
|
|
||||||
|
|
||||||
|
|
||||||
def test_ingest_routes_exclude_active_discovery():
|
|
||||||
from main import app
|
|
||||||
|
|
||||||
ingest = [
|
|
||||||
getattr(r, "path", "")
|
|
||||||
for r in app.routes
|
|
||||||
if getattr(r, "path", "").startswith("/api/ingest/")
|
|
||||||
]
|
|
||||||
assert "/api/ingest/fires" in ingest
|
|
||||||
assert all("scan" not in path for path in ingest)
|
|
||||||
|
|
||||||
|
|
||||||
def test_schedule_ffmpeg_snapshot_is_a_task_not_inline(monkeypatch):
|
def test_schedule_ffmpeg_snapshot_is_a_task_not_inline(monkeypatch):
|
||||||
|
|
|
||||||
|
|
@ -1,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,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
|
|
||||||
|
|
@ -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) == []
|
assert matching_geofences(-122.4, 37.7, fences) == []
|
||||||
|
|
||||||
|
|
||||||
FENCE_ID = "11111111-1111-1111-1111-111111111111"
|
|
||||||
NC_VIEW = (-80.0, 35.0, -78.0, 36.0)
|
|
||||||
SF_VIEW = (-123.0, 37.0, -121.0, 38.0)
|
|
||||||
|
|
||||||
|
|
||||||
def _alert_payload(gid=FENCE_ID):
|
|
||||||
return {
|
|
||||||
"geofence_id": gid,
|
|
||||||
"geofence_name": "NC",
|
|
||||||
"source_kind": "ais",
|
|
||||||
"entity_id": "366123456",
|
|
||||||
"lat": 35.5,
|
|
||||||
"lon": -79.0,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_geofence_alert_fans_out_only_to_viewport_clients():
|
def test_geofence_alert_fans_out_only_to_viewport_clients():
|
||||||
mgr = ConnectionManager()
|
mgr = ConnectionManager()
|
||||||
q_nc = mgr.register("nc")
|
q_nc = mgr.register("nc")
|
||||||
q_sf = mgr.register("sf")
|
q_sf = mgr.register("sf")
|
||||||
mgr.set_viewport("nc", NC_VIEW)
|
mgr.set_viewport("nc", (-80.0, 35.0, -78.0, 36.0))
|
||||||
mgr.set_viewport("sf", SF_VIEW)
|
mgr.set_viewport("sf", (-123.0, 37.0, -121.0, 38.0))
|
||||||
|
|
||||||
async def run():
|
async def run():
|
||||||
n = await mgr.publish_point(
|
payload = {
|
||||||
"geofence_alert", _alert_payload(), lat=35.5, lon=-79.0,
|
"geofence_id": "a",
|
||||||
)
|
"geofence_name": "NC",
|
||||||
|
"source_kind": "ais",
|
||||||
|
"entity_id": "366123456",
|
||||||
|
"lat": 35.5,
|
||||||
|
"lon": -79.0,
|
||||||
|
}
|
||||||
|
n = await mgr.publish_point("geofence_alert", payload, lat=35.5, lon=-79.0)
|
||||||
assert n == 1
|
assert n == 1
|
||||||
msg = q_nc.get_nowait()
|
msg = q_nc.get_nowait()
|
||||||
assert msg["type"] == "geofence_alert"
|
assert msg["type"] == "geofence_alert"
|
||||||
|
|
@ -87,109 +77,6 @@ def test_geofence_alert_fans_out_only_to_viewport_clients():
|
||||||
asyncio.run(run())
|
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):
|
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."""
|
"""FIRMS ingest in the ingester has an empty in-process cache — still ST_Intersects."""
|
||||||
import geofence
|
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)]
|
inserts = [p for p in executed if isinstance(p, dict)]
|
||||||
assert inserts and inserts[0]["source_kind"] == "firms"
|
assert inserts and inserts[0]["source_kind"] == "firms"
|
||||||
assert "commit" in executed
|
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,10 +1,7 @@
|
||||||
"""Geofence layer panel: draw, watch, inbox, delete (HTML contract)."""
|
"""Geofence layer panel: draw + delete (DELETE /api/geofences/{id})."""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
|
||||||
import subprocess
|
|
||||||
import tempfile
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
@ -27,181 +24,3 @@ def test_load_geofences_renders_delete_controls():
|
||||||
assert "deleteGeofence" in js
|
assert "deleteGeofence" in js
|
||||||
assert "onEachFeature" in js
|
assert "onEachFeature" in js
|
||||||
assert "bindPopup" 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
|
|
||||||
|
|
|
||||||
|
|
@ -3,21 +3,12 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import os
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
|
|
||||||
import asyncpg
|
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
|
||||||
|
|
||||||
from conftest import requires_db
|
|
||||||
from main import app
|
from main import app
|
||||||
|
|
||||||
BASE = "http://test"
|
BASE = "http://test"
|
||||||
_FIXTURE_URLS = (
|
|
||||||
"https://test.invalid/t_ceb74e64/future",
|
|
||||||
"https://test.invalid/t_ceb74e64/fresh",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def _get(path: str) -> httpx.Response:
|
async def _get(path: str) -> httpx.Response:
|
||||||
|
|
@ -40,67 +31,3 @@ def test_ready_endpoint_exists():
|
||||||
body = resp.json()
|
body = resp.json()
|
||||||
assert "checks" in body
|
assert "checks" in body
|
||||||
assert "status" 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,70 +0,0 @@
|
||||||
"""SSRF guard on ingest triggers + PATCH /api/sources allowlist."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
import pytest
|
|
||||||
from pydantic import ValidationError
|
|
||||||
|
|
||||||
from main import app
|
|
||||||
|
|
||||||
from conftest import admin_cookies
|
|
||||||
|
|
||||||
BASE = "http://test"
|
|
||||||
LINK_LOCAL_META = "http://169.254.169.254/latest/meta-data/"
|
|
||||||
LOOPBACK = "http://127.0.0.1/secret"
|
|
||||||
|
|
||||||
|
|
||||||
async def _req(method: str, path: str, **kw) -> httpx.Response:
|
|
||||||
transport = httpx.ASGITransport(app=app)
|
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
|
||||||
client.cookies.update(admin_cookies())
|
|
||||||
return await client.request(method, path, **kw)
|
|
||||||
|
|
||||||
|
|
||||||
def test_rss_ingest_rejects_link_local_metadata_url(monkeypatch):
|
|
||||||
called = {"n": 0}
|
|
||||||
|
|
||||||
async def _boom(*_a, **_k):
|
|
||||||
called["n"] += 1
|
|
||||||
raise AssertionError("ingest_rss_feed must not run for a private URL")
|
|
||||||
|
|
||||||
monkeypatch.setattr("main.ingest_rss_feed", _boom)
|
|
||||||
resp = asyncio.run(_req("POST", "/api/ingest/rss", params={"feed_url": LINK_LOCAL_META}))
|
|
||||||
assert resp.status_code == 400
|
|
||||||
assert called["n"] == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_gdelt_ingest_rejects_private_query_url(monkeypatch):
|
|
||||||
called = {"n": 0}
|
|
||||||
|
|
||||||
async def _boom(*_a, **_k):
|
|
||||||
called["n"] += 1
|
|
||||||
raise AssertionError("ingest_gdelt must not run for a private URL query")
|
|
||||||
|
|
||||||
monkeypatch.setattr("main.ingest_gdelt", _boom)
|
|
||||||
resp = asyncio.run(_req("POST", "/api/ingest/gdelt", params={"query": LOOPBACK}))
|
|
||||||
assert resp.status_code == 400
|
|
||||||
assert called["n"] == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_update_source_rejects_unknown_fields():
|
|
||||||
sid = "00000000-0000-0000-0000-000000000001"
|
|
||||||
resp = asyncio.run(_req("PATCH", f"/api/sources/{sid}", json={"enabled": True, "source_type": "rss"}))
|
|
||||||
assert resp.status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_feed_source_update_allowlist_only():
|
|
||||||
from schemas import FeedSourceUpdate
|
|
||||||
|
|
||||||
payload = FeedSourceUpdate(name="n", url="https://example.com/rss", config={"k": 1}, enabled=False)
|
|
||||||
assert payload.model_dump(exclude_unset=True) == {
|
|
||||||
"name": "n",
|
|
||||||
"url": "https://example.com/rss",
|
|
||||||
"config": {"k": 1},
|
|
||||||
"enabled": False,
|
|
||||||
}
|
|
||||||
with pytest.raises(ValidationError):
|
|
||||||
FeedSourceUpdate.model_validate({"enabled": True, "id": "00000000-0000-0000-0000-000000000001"})
|
|
||||||
|
|
@ -2,12 +2,9 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import datetime as _dt
|
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parent.parent
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
_SCRAPER = ROOT / "news/scraper"
|
_SCRAPER = ROOT / "news/scraper"
|
||||||
if str(_SCRAPER) not in sys.path:
|
if str(_SCRAPER) not in sys.path:
|
||||||
|
|
@ -43,141 +40,3 @@ def test_spider_skips_audio_before_request():
|
||||||
assert "is_audio_url" in src
|
assert "is_audio_url" in src
|
||||||
assert "article_timestamp" in src
|
assert "article_timestamp" in src
|
||||||
assert "datetime.datetime.now()" not in src
|
assert "datetime.datetime.now()" not in src
|
||||||
|
|
||||||
|
|
||||||
# ── future-dated guard (ingest) ───────────────────────────────────────────
|
|
||||||
|
|
||||||
class _FakeCursor:
|
|
||||||
rowcount = 1
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self.executed = []
|
|
||||||
|
|
||||||
def execute(self, sql, params=None):
|
|
||||||
self.executed.append((sql, params))
|
|
||||||
|
|
||||||
|
|
||||||
class _FakeConnection:
|
|
||||||
def commit(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def rollback(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class _FakeStats:
|
|
||||||
def __init__(self):
|
|
||||||
self.values = {}
|
|
||||||
|
|
||||||
def inc_value(self, key, count=1):
|
|
||||||
self.values[key] = self.values.get(key, 0) + count
|
|
||||||
|
|
||||||
|
|
||||||
class _FakeSpider:
|
|
||||||
class _Logger:
|
|
||||||
def info(self, *a, **kw):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def error(self, *a, **kw):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self.logger = self._Logger()
|
|
||||||
self.crawler = type("C", (), {"stats": _FakeStats()})()
|
|
||||||
|
|
||||||
|
|
||||||
def _pipeline():
|
|
||||||
from newsScraper.pipelines import PostgresPipeline
|
|
||||||
|
|
||||||
pipe = PostgresPipeline(db_config={})
|
|
||||||
pipe.cur = _FakeCursor()
|
|
||||||
pipe.connection = _FakeConnection()
|
|
||||||
return pipe
|
|
||||||
|
|
||||||
|
|
||||||
def _item(ts: _dt.datetime) -> dict:
|
|
||||||
return {
|
|
||||||
"title": "t",
|
|
||||||
"url": f"https://a.example/{ts.isoformat()}",
|
|
||||||
"text": "body",
|
|
||||||
"domain": "a.example",
|
|
||||||
"timestamp": ts.isoformat(),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def test_pipeline_drops_future_dated_item():
|
|
||||||
from scrapy.exceptions import DropItem
|
|
||||||
|
|
||||||
pipe = _pipeline()
|
|
||||||
spider = _FakeSpider()
|
|
||||||
future = _dt.datetime.now(_dt.timezone.utc) + _dt.timedelta(days=5)
|
|
||||||
with pytest.raises(DropItem):
|
|
||||||
pipe.process_item(_item(future), spider)
|
|
||||||
assert pipe.future_dated_dropped == 1
|
|
||||||
assert spider.crawler.stats.values["future_dated_dropped"] == 1
|
|
||||||
assert pipe.cur.executed == [] # never reached the INSERT
|
|
||||||
|
|
||||||
|
|
||||||
def test_pipeline_keeps_recent_item():
|
|
||||||
pipe = _pipeline()
|
|
||||||
spider = _FakeSpider()
|
|
||||||
recent = _dt.datetime.now(_dt.timezone.utc) - _dt.timedelta(days=1)
|
|
||||||
assert pipe.process_item(_item(recent), spider)["domain"] == "a.example"
|
|
||||||
assert pipe.future_dated_dropped == 0
|
|
||||||
assert len(pipe.cur.executed) == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_pipeline_keeps_unparseable_timestamp():
|
|
||||||
from newsScraper.pipelines import is_future_dated
|
|
||||||
|
|
||||||
assert is_future_dated("not a date") is False
|
|
||||||
assert is_future_dated(None) is False
|
|
||||||
|
|
||||||
|
|
||||||
# ── CDATA title unwrap (ingest) ───────────────────────────────────────────
|
|
||||||
# Excelsior stores the wrapper as text, including the leading newline the
|
|
||||||
# feed leaves around <![CDATA[...]]>. A plain title, and real HTML that is
|
|
||||||
# not that wrapper, must pass through unchanged.
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
"raw,expected",
|
|
||||||
[
|
|
||||||
("<![CDATA[Hello]]>", "Hello"),
|
|
||||||
("\n <![CDATA[Hello]]>", "Hello"),
|
|
||||||
(
|
|
||||||
"\n <![CDATA[Hello]]> ",
|
|
||||||
"Hello",
|
|
||||||
),
|
|
||||||
("Hello", "Hello"),
|
|
||||||
(" Hello ", " Hello "),
|
|
||||||
("<b>Hello</b>", "<b>Hello</b>"),
|
|
||||||
("See <![CDATA[Hello]]>", "See <![CDATA[Hello]]>"),
|
|
||||||
(None, None),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_unwrap_cdata_title(raw, expected):
|
|
||||||
from newsScraper.feed_util import unwrap_cdata_title
|
|
||||||
|
|
||||||
assert unwrap_cdata_title(raw) == expected
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
|
||||||
"raw,expected",
|
|
||||||
[
|
|
||||||
("<![CDATA[Hello]]>", "Hello"),
|
|
||||||
("\n <![CDATA[Hello]]>", "Hello"),
|
|
||||||
("Hello", "Hello"),
|
|
||||||
("<b>Hello</b>", "<b>Hello</b>"),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_pipeline_stores_cdata_title_unwrapped(raw, expected):
|
|
||||||
pipe = _pipeline()
|
|
||||||
spider = _FakeSpider()
|
|
||||||
recent = _dt.datetime.now(_dt.timezone.utc) - _dt.timedelta(hours=1)
|
|
||||||
item = _item(recent)
|
|
||||||
item["title"] = raw
|
|
||||||
returned = pipe.process_item(item, spider)
|
|
||||||
assert returned["title"] == expected
|
|
||||||
stored = pipe.cur.executed[0][1][0]
|
|
||||||
assert stored == expected
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -31,35 +31,3 @@ def test_no_redis_kafka_celery():
|
||||||
assert "kafka" not in blob
|
assert "kafka" not in blob
|
||||||
assert "celery" not in blob
|
assert "celery" not in blob
|
||||||
assert "cachetools" in req
|
assert "cachetools" in req
|
||||||
|
|
||||||
|
|
||||||
def test_titiler_image_pinned_by_digest():
|
|
||||||
text = (ROOT / "docker-compose.yml").read_text()
|
|
||||||
assert (
|
|
||||||
"ghcr.io/developmentseed/titiler:latest@sha256:"
|
|
||||||
"1809958d063543e3ec858259536002b2de78e9f8f09a22a8d9591bdc2b550b14"
|
|
||||||
in text
|
|
||||||
)
|
|
||||||
# Unpinned :latest would drift on every pull.
|
|
||||||
for line in text.splitlines():
|
|
||||||
if "titiler" in line.lower() and "image:" in line:
|
|
||||||
assert "@sha256:" in line
|
|
||||||
|
|
||||||
|
|
||||||
def test_uvicorn_single_worker_guard():
|
|
||||||
text = (ROOT / "app" / "main.py").read_text()
|
|
||||||
main_block = text.split('if __name__ == "__main__":', 1)[1]
|
|
||||||
assert "workers=1" in main_block
|
|
||||||
|
|
||||||
|
|
||||||
def test_bbox_gist_migration_keeps_btree_and_adds_gist():
|
|
||||||
text = (ROOT / "alembic" / "versions" / "010_bbox_gist.py").read_text()
|
|
||||||
assert "down_revision" in text and "009_vessels" in text
|
|
||||||
assert "ix_events_geom_gist" in text
|
|
||||||
assert "ix_fires_geom_gist" in text
|
|
||||||
assert "ST_MakePoint(location_lon, location_lat)" in text
|
|
||||||
assert "ST_MakePoint(longitude, latitude)" in text
|
|
||||||
assert "USING gist" in text
|
|
||||||
models = (ROOT / "app" / "models.py").read_text()
|
|
||||||
assert 'Index("ix_events_location"' in models
|
|
||||||
assert 'Index("ix_fires_bbox"' in models
|
|
||||||
|
|
|
||||||
|
|
@ -8,21 +8,15 @@ import httpx
|
||||||
|
|
||||||
from main import app
|
from main import app
|
||||||
|
|
||||||
from conftest import admin_cookies
|
|
||||||
|
|
||||||
BASE = "http://test"
|
BASE = "http://test"
|
||||||
|
|
||||||
|
|
||||||
async def _req(method: str, path: str, **kw) -> httpx.Response:
|
async def _req(method: str, path: str, **kw) -> httpx.Response:
|
||||||
transport = httpx.ASGITransport(app=app)
|
transport = httpx.ASGITransport(app=app)
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||||||
client.cookies.update(admin_cookies())
|
|
||||||
return await client.request(method, path, **kw)
|
return await client.request(method, path, **kw)
|
||||||
|
|
||||||
|
|
||||||
FENCE_ID = "11111111-1111-1111-1111-111111111111"
|
|
||||||
|
|
||||||
|
|
||||||
def test_geofence_post_rejects_point():
|
def test_geofence_post_rejects_point():
|
||||||
resp = asyncio.run(_req(
|
resp = asyncio.run(_req(
|
||||||
"POST", "/api/geofences",
|
"POST", "/api/geofences",
|
||||||
|
|
@ -31,147 +25,6 @@ def test_geofence_post_rejects_point():
|
||||||
assert resp.status_code == 422
|
assert resp.status_code == 422
|
||||||
|
|
||||||
|
|
||||||
def test_delete_geofence_404_when_missing(monkeypatch):
|
|
||||||
async def missing(_gid: str) -> bool:
|
|
||||||
return False
|
|
||||||
|
|
||||||
monkeypatch.setattr("geofence.delete_geofence", missing)
|
|
||||||
resp = asyncio.run(_req("DELETE", f"/api/geofences/{FENCE_ID}"))
|
|
||||||
assert resp.status_code == 404
|
|
||||||
|
|
||||||
|
|
||||||
def test_geofence_alerts_passes_filters(monkeypatch):
|
|
||||||
seen = {}
|
|
||||||
|
|
||||||
async def fake_list(**kwargs):
|
|
||||||
seen.update(kwargs)
|
|
||||||
return [{"id": "a", "geofence_id": FENCE_ID, "source_kind": "ais"}]
|
|
||||||
|
|
||||||
monkeypatch.setattr("geofence.list_alerts", fake_list)
|
|
||||||
resp = asyncio.run(_req(
|
|
||||||
"GET", "/api/geofence-alerts",
|
|
||||||
params={
|
|
||||||
"geofence_id": FENCE_ID,
|
|
||||||
"since": "2026-08-28T00:00:00Z",
|
|
||||||
"until": "2026-08-29T00:00:00Z",
|
|
||||||
"source_kind": "ais",
|
|
||||||
"limit": 10,
|
|
||||||
},
|
|
||||||
))
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert resp.json()[0]["source_kind"] == "ais"
|
|
||||||
assert seen["geofence_id"] == FENCE_ID
|
|
||||||
assert seen["source_kind"] == "ais"
|
|
||||||
assert seen["limit"] == 10
|
|
||||||
assert seen["since"] is not None
|
|
||||||
assert seen["until"] is not None
|
|
||||||
|
|
||||||
|
|
||||||
def test_geofence_at_accepts_ts_alias(monkeypatch):
|
|
||||||
seen = {}
|
|
||||||
|
|
||||||
async def snap(gid: str, ts):
|
|
||||||
seen["gid"] = gid
|
|
||||||
seen["ts"] = ts
|
|
||||||
return {
|
|
||||||
"geofence_id": gid,
|
|
||||||
"timestamp": ts.isoformat(),
|
|
||||||
"aircraft": [],
|
|
||||||
"vessels": [],
|
|
||||||
"fires": [],
|
|
||||||
}
|
|
||||||
|
|
||||||
monkeypatch.setattr("geofence.snapshot_at", snap)
|
|
||||||
resp = asyncio.run(_req(
|
|
||||||
"GET", f"/api/geofences/{FENCE_ID}/at",
|
|
||||||
params={"ts": "2026-08-28T12:04:00Z"},
|
|
||||||
))
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert seen["gid"] == FENCE_ID
|
|
||||||
assert seen["ts"].year == 2026
|
|
||||||
|
|
||||||
|
|
||||||
def test_geofence_alerts_accepts_new_kinds(monkeypatch):
|
|
||||||
seen = {}
|
|
||||||
|
|
||||||
async def fake_list(**kwargs):
|
|
||||||
seen.update(kwargs)
|
|
||||||
return []
|
|
||||||
|
|
||||||
monkeypatch.setattr("geofence.list_alerts", fake_list)
|
|
||||||
resp = asyncio.run(_req(
|
|
||||||
"GET", "/api/geofence-alerts", params={"source_kind": "earthquake"},
|
|
||||||
))
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert seen["source_kind"] == "earthquake"
|
|
||||||
resp = asyncio.run(_req(
|
|
||||||
"GET", "/api/geofence-alerts", params={"source_kind": "camera"},
|
|
||||||
))
|
|
||||||
assert resp.status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_geofence_at_404_when_missing(monkeypatch):
|
|
||||||
async def no_snap(gid: str, ts):
|
|
||||||
return None
|
|
||||||
|
|
||||||
monkeypatch.setattr("geofence.snapshot_at", no_snap)
|
|
||||||
resp = asyncio.run(_req(
|
|
||||||
"GET", f"/api/geofences/{FENCE_ID}/at",
|
|
||||||
params={"timestamp": "2026-08-28T12:04:00Z"},
|
|
||||||
))
|
|
||||||
assert resp.status_code == 404
|
|
||||||
|
|
||||||
|
|
||||||
def test_geofence_at_empty_lists_when_db_down(monkeypatch):
|
|
||||||
async def empty_snap(gid: str, ts):
|
|
||||||
return {
|
|
||||||
"geofence_id": gid,
|
|
||||||
"timestamp": ts.isoformat(),
|
|
||||||
"aircraft": [],
|
|
||||||
"vessels": [],
|
|
||||||
"fires": [],
|
|
||||||
}
|
|
||||||
|
|
||||||
monkeypatch.setattr("geofence.snapshot_at", empty_snap)
|
|
||||||
resp = asyncio.run(_req(
|
|
||||||
"GET", f"/api/geofences/{FENCE_ID}/at",
|
|
||||||
params={"timestamp": "2026-08-28T12:04:00Z"},
|
|
||||||
))
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert body["geofence_id"] == FENCE_ID
|
|
||||||
assert body["aircraft"] == []
|
|
||||||
assert body["vessels"] == []
|
|
||||||
assert body["fires"] == []
|
|
||||||
assert "timestamp" in body
|
|
||||||
|
|
||||||
|
|
||||||
def test_geofence_at_does_not_notify(monkeypatch):
|
|
||||||
called = {"notify": 0}
|
|
||||||
|
|
||||||
async def empty_snap(gid: str, ts):
|
|
||||||
return {
|
|
||||||
"geofence_id": gid,
|
|
||||||
"timestamp": ts.isoformat(),
|
|
||||||
"aircraft": [],
|
|
||||||
"vessels": [],
|
|
||||||
"fires": [],
|
|
||||||
}
|
|
||||||
|
|
||||||
async def boom(**_kw):
|
|
||||||
called["notify"] += 1
|
|
||||||
raise AssertionError("GET /at must not record_and_notify")
|
|
||||||
|
|
||||||
monkeypatch.setattr("geofence.snapshot_at", empty_snap)
|
|
||||||
monkeypatch.setattr("geofence.record_and_notify", boom)
|
|
||||||
resp = asyncio.run(_req(
|
|
||||||
"GET", f"/api/geofences/{FENCE_ID}/at",
|
|
||||||
params={"timestamp": "2026-08-28T12:04:00Z"},
|
|
||||||
))
|
|
||||||
assert resp.status_code == 200
|
|
||||||
assert called["notify"] == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_geofences_list_does_not_collide_with_alerts():
|
def test_geofences_list_does_not_collide_with_alerts():
|
||||||
resp = asyncio.run(_req("GET", "/api/geofences"))
|
resp = asyncio.run(_req("GET", "/api/geofences"))
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
|
|
|
||||||
|
|
@ -1,200 +0,0 @@
|
||||||
"""CelesTrak satellites overlay: GP JSON parser, 2h cache, groups, bbox."""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
import satellites
|
|
||||||
from live_layers import _cache, overlay_catalog
|
|
||||||
from main import app
|
|
||||||
|
|
||||||
BASE = "http://test"
|
|
||||||
|
|
||||||
# Two real CelesTrak GP JSON records (trimmed to the OMM fields sgp4 needs).
|
|
||||||
ISS = {
|
|
||||||
"OBJECT_NAME": "ISS (ZARYA)", "OBJECT_ID": "1998-067A",
|
|
||||||
"EPOCH": "2026-08-31T11:11:23.184384", "MEAN_MOTION": 15.4894954,
|
|
||||||
"ECCENTRICITY": 0.00050456, "INCLINATION": 51.6314,
|
|
||||||
"RA_OF_ASC_NODE": 287.5025, "ARG_OF_PERICENTER": 92.8598,
|
|
||||||
"MEAN_ANOMALY": 267.2968, "EPHEMERIS_TYPE": 0,
|
|
||||||
"CLASSIFICATION_TYPE": "U", "NORAD_CAT_ID": 25544,
|
|
||||||
"ELEMENT_SET_NO": 999, "REV_AT_EPOCH": 58342,
|
|
||||||
"BSTAR": 9.9862358e-5, "MEAN_MOTION_DOT": 5.046e-5,
|
|
||||||
"MEAN_MOTION_DDOT": 0,
|
|
||||||
}
|
|
||||||
HST = {
|
|
||||||
"OBJECT_NAME": "HST", "OBJECT_ID": "1990-037B",
|
|
||||||
"EPOCH": "2026-08-31T11:11:23.184384", "MEAN_MOTION": 15.0865888,
|
|
||||||
"ECCENTRICITY": 0.0002426, "INCLINATION": 28.4697,
|
|
||||||
"RA_OF_ASC_NODE": 102.1854, "ARG_OF_PERICENTER": 152.8462,
|
|
||||||
"MEAN_ANOMALY": 207.2795, "EPHEMERIS_TYPE": 0,
|
|
||||||
"CLASSIFICATION_TYPE": "U", "NORAD_CAT_ID": 20580,
|
|
||||||
"ELEMENT_SET_NO": 999, "REV_AT_EPOCH": 12345,
|
|
||||||
"BSTAR": 2.9e-5, "MEAN_MOTION_DOT": 0.0,
|
|
||||||
"MEAN_MOTION_DDOT": 0,
|
|
||||||
}
|
|
||||||
FIXTURE = [ISS, HST]
|
|
||||||
|
|
||||||
NOW = datetime(2026, 8, 31, 12, 0, 0, tzinfo=timezone.utc)
|
|
||||||
|
|
||||||
|
|
||||||
async def _get(path: str) -> httpx.Response:
|
|
||||||
transport = httpx.ASGITransport(app=app)
|
|
||||||
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
|
||||||
return await client.get(path)
|
|
||||||
|
|
||||||
|
|
||||||
def test_propagate_gp_shape():
|
|
||||||
rows = satellites.propagate_gp(FIXTURE, "stations", NOW)
|
|
||||||
assert len(rows) == 2
|
|
||||||
by_id = {r["id"]: r for r in rows}
|
|
||||||
assert set(by_id) == {"25544", "20580"}
|
|
||||||
iss = by_id["25544"]
|
|
||||||
assert iss["name"] == "ISS (ZARYA)"
|
|
||||||
assert iss["group"] == "stations"
|
|
||||||
# ISS is in LEO: ~400 km, |lat| <= inclination 51.63, lon in range.
|
|
||||||
assert 300 < iss["alt_km"] < 500
|
|
||||||
assert -51.7 <= iss["lat"] <= 51.7
|
|
||||||
assert -180 <= iss["lon"] <= 180
|
|
||||||
for key in ("id", "name", "lat", "lon", "alt_km", "group"):
|
|
||||||
assert key in iss
|
|
||||||
|
|
||||||
|
|
||||||
def test_propagate_gp_skips_malformed():
|
|
||||||
bad = [{"OBJECT_NAME": "x"}, None, 42, {"NORAD_CAT_ID": 1}]
|
|
||||||
assert satellites.propagate_gp(bad, "stations", NOW) == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_groups_defaults_and_validation():
|
|
||||||
assert satellites.parse_groups("stations,weather") == ["stations", "weather"]
|
|
||||||
assert satellites.parse_groups("weather,gps-ops") == ["weather", "gps-ops"]
|
|
||||||
# starlink is allowed only when explicitly requested
|
|
||||||
assert satellites.parse_groups("starlink") == ["starlink"]
|
|
||||||
assert satellites.parse_groups("stations,stations") == ["stations"]
|
|
||||||
for bad in ("", None, "debris", "stations,active", "stations, weather, active"):
|
|
||||||
try:
|
|
||||||
satellites.parse_groups(bad)
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
raise AssertionError(f"expected ValueError for {bad!r}")
|
|
||||||
|
|
||||||
|
|
||||||
def test_overlay_catalog_has_satellites_stub():
|
|
||||||
entry = overlay_catalog()["satellites"]
|
|
||||||
assert entry["kind"] == "points"
|
|
||||||
assert entry["endpoint"] == "/api/satellites"
|
|
||||||
assert "CelesTrak" in entry["attribution"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_group_400():
|
|
||||||
resp = asyncio.run(_get("/api/satellites?groups=debris"))
|
|
||||||
assert resp.status_code == 400
|
|
||||||
|
|
||||||
|
|
||||||
def test_default_groups_ok_with_fake_fetch(monkeypatch):
|
|
||||||
async def fake(groups, bbox=None, limit=2000):
|
|
||||||
return {"satellites": [], "source": "celestrak",
|
|
||||||
"tle_epoch": None, "timestamp": "t"}
|
|
||||||
|
|
||||||
monkeypatch.setattr("main.fetch_satellites", fake)
|
|
||||||
resp = asyncio.run(_get("/api/satellites"))
|
|
||||||
assert resp.status_code == 200
|
|
||||||
body = resp.json()
|
|
||||||
assert body["source"] == "celestrak"
|
|
||||||
assert "max-age" in (resp.headers.get("cache-control") or "").lower()
|
|
||||||
|
|
||||||
|
|
||||||
def test_2h_cache_does_not_refetch(monkeypatch):
|
|
||||||
satellites._last_good.clear()
|
|
||||||
_cache.clear()
|
|
||||||
hits = {"n": 0}
|
|
||||||
|
|
||||||
class FakeResp:
|
|
||||||
def __init__(self, data):
|
|
||||||
self._data = data
|
|
||||||
|
|
||||||
def raise_for_status(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def json(self):
|
|
||||||
return self._data
|
|
||||||
|
|
||||||
class FakeClient:
|
|
||||||
def __init__(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def get(self, url, params=None, headers=None):
|
|
||||||
hits["n"] += 1
|
|
||||||
assert "celestrak.org/NORAD/elements/gp.php" in url
|
|
||||||
return FakeResp(FIXTURE)
|
|
||||||
|
|
||||||
monkeypatch.setattr("live_layers._http", FakeClient())
|
|
||||||
|
|
||||||
async def run():
|
|
||||||
p1 = await satellites.fetch_satellites(["stations"])
|
|
||||||
p2 = await satellites.fetch_satellites(["stations"])
|
|
||||||
return p1, p2
|
|
||||||
|
|
||||||
p1, p2 = asyncio.run(run())
|
|
||||||
assert len(p1["satellites"]) == 2
|
|
||||||
assert p1["tle_epoch"] == "2026-08-31T11:11:23.184384"
|
|
||||||
# Same element blob served from cache (no refetch), same ids/epochs.
|
|
||||||
assert [s["id"] for s in p2["satellites"]] == [s["id"] for s in p1["satellites"]]
|
|
||||||
assert p2["tle_epoch"] == p1["tle_epoch"]
|
|
||||||
assert hits["n"] == 1
|
|
||||||
_cache.clear()
|
|
||||||
satellites._last_good.clear()
|
|
||||||
|
|
||||||
|
|
||||||
def test_bbox_culls_satellites(monkeypatch):
|
|
||||||
"""bbox filtering in fetch_satellites, deterministic via fake propagation."""
|
|
||||||
|
|
||||||
async def fake_elements(group):
|
|
||||||
return [{"x": 1}], "2026-08-31T11:11:23.184384"
|
|
||||||
|
|
||||||
monkeypatch.setattr("satellites._group_elements", fake_elements)
|
|
||||||
|
|
||||||
def fake_propagate(elements, group, now):
|
|
||||||
return [
|
|
||||||
{"id": "a", "name": "A", "lat": 10.0, "lon": 20.0, "alt_km": 400.0, "group": group},
|
|
||||||
{"id": "b", "name": "B", "lat": 45.0, "lon": -70.0, "alt_km": 400.0, "group": group},
|
|
||||||
{"id": "c", "name": "C", "lat": -10.0, "lon": 30.0, "alt_km": 400.0, "group": group},
|
|
||||||
]
|
|
||||||
|
|
||||||
monkeypatch.setattr("satellites.propagate_gp", fake_propagate)
|
|
||||||
|
|
||||||
payload = asyncio.run(
|
|
||||||
satellites.fetch_satellites(["stations"], bbox="-80,0,-60,50")
|
|
||||||
)
|
|
||||||
ids = [s["id"] for s in payload["satellites"]]
|
|
||||||
assert ids == ["b"] # only (45, -70) falls inside the box
|
|
||||||
|
|
||||||
|
|
||||||
def test_bbox_culls_nothing_when_empty():
|
|
||||||
from satellites import fetch_satellites
|
|
||||||
|
|
||||||
# No bbox: all rows returned up to limit.
|
|
||||||
# (skip network; just sanity-check the arg is accepted by signature)
|
|
||||||
assert callable(fetch_satellites)
|
|
||||||
|
|
||||||
|
|
||||||
def test_satnogs_fallback_parser():
|
|
||||||
payload = [{
|
|
||||||
"tle0": "0 ISS (ZARYA)",
|
|
||||||
"tle1": "1 25544U 98067A 26243.85334329 .00004554 00000-0 90917-4 0 9992",
|
|
||||||
"tle2": "2 25544 51.6312 285.5873 0005057 94.2999 265.8567 15.48953200583481",
|
|
||||||
"norad_cat_id": 25544,
|
|
||||||
"updated": "2026-09-01T01:19:54.327653Z",
|
|
||||||
}]
|
|
||||||
rows, epoch = satellites.propagate_satnogs_tle(payload, "stations", NOW)
|
|
||||||
assert len(rows) == 1
|
|
||||||
row = rows[0]
|
|
||||||
assert row["id"] == "25544"
|
|
||||||
assert row["name"] == "ISS (ZARYA)"
|
|
||||||
assert row["group"] == "stations"
|
|
||||||
assert epoch == "2026-09-01T01:19:54.327653Z"
|
|
||||||
assert 300 < row["alt_km"] < 500
|
|
||||||
Loading…
Reference in a new issue