Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 76035535bc | |||
|
|
8f38ff6ff8 | ||
| fc0cd41b7a | |||
|
|
56908aed03 | ||
| 54897b49bc | |||
|
|
366ee12b46 | ||
| 915f6cbe25 | |||
|
|
a72ddc30f8 | ||
| a268eefb84 | |||
|
|
577a96658d | ||
| fe2b5df369 | |||
| 44897a86d4 | |||
|
|
e6ef6b79f9 | ||
|
|
ca1c73e1a6 | ||
| 5ea43a3d0b | |||
|
|
88b95f6a95 | ||
|
|
005d271175 | ||
| 7c77aa3103 | |||
| 23286e14da | |||
|
|
0f91127233 | ||
| 3f11e647f0 | |||
| eefcc08b31 | |||
|
|
13a4049137 | ||
|
|
d878655617 | ||
|
|
02a9a5626b | ||
|
|
653e02b09f |
38 changed files with 42647 additions and 165 deletions
|
|
@ -1,21 +1,28 @@
|
||||||
# Build changed OSINT images, publish to the Forgejo container registry, then
|
# Build changed OSINT images and publish them to the Forgejo container
|
||||||
# redeploy on the Pi runner (docker.sock mounted).
|
# registry. Deployment is NOT done here: the cluster (homek8s, namespace
|
||||||
|
# `osint`) runs amd64 images pinned by tag in apps/base/osint/*.yaml, so the
|
||||||
|
# final step prints the tag to pin and a human opens that manifest PR.
|
||||||
#
|
#
|
||||||
# Unchanged images are skipped. Dockerfile.pg / osint-dashboard-pg is NOT
|
# Unchanged images are skipped. Dockerfile.pg / osint-dashboard-pg is NOT
|
||||||
# rebuilt or pulled on a normal merge — Postgres stays up. Rebuild it only
|
# rebuilt on a normal merge — Postgres stays up. Rebuild it only when
|
||||||
# when Dockerfile.pg changes, or via workflow_dispatch rebuild_pg.
|
# 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
|
# forgejo.siriusdevops.com/sirius/osint-dashboard:amd64-<sha12>
|
||||||
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg
|
# forgejo.siriusdevops.com/sirius/osint-dashboard-pg:amd64-<sha12>
|
||||||
# forgejo.siriusdevops.com/sirius/osint-news-scraper
|
# forgejo.siriusdevops.com/sirius/osint-news-scraper:amd64-<sha12>
|
||||||
# forgejo.siriusdevops.com/sirius/osint-news-summarizer
|
# forgejo.siriusdevops.com/sirius/osint-news-summarizer:amd64-<sha12>
|
||||||
#
|
#
|
||||||
# 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
|
||||||
|
|
||||||
|
|
@ -35,17 +42,19 @@ on:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }}
|
PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }}
|
||||||
PUSH_REGISTRY: 127.0.0.1:3000
|
PUSH_REGISTRY: forgejo.forgejo.svc.cluster.local:3000
|
||||||
OWNER: sirius
|
OWNER: sirius
|
||||||
# Keep compose project/volumes stable on the Pi
|
|
||||||
COMPOSE_PROJECT_NAME: osint-dashboard
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build-push-deploy:
|
build-push:
|
||||||
runs-on: docker
|
# `amd64` only exists on siriussec-amd64, which is also the node the
|
||||||
permissions:
|
# workloads run on — so the images are built on the architecture they are
|
||||||
contents: read
|
# pulled to. `runs-on: docker` matched the Pi's arm64 runner, which
|
||||||
packages: write
|
# produced images the amd64 cluster could never run.
|
||||||
|
# No job-level `permissions:` block: Forgejo ignores it (it emits a
|
||||||
|
# pre-execution warning) and the push authenticates with the FORGEJO_TOKEN
|
||||||
|
# user PAT instead, because the package registry rejects the Actions token.
|
||||||
|
runs-on: amd64
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: https://code.forgejo.org/actions/checkout@v4
|
uses: https://code.forgejo.org/actions/checkout@v4
|
||||||
|
|
@ -60,7 +69,6 @@ jobs:
|
||||||
SCRAPER=0
|
SCRAPER=0
|
||||||
SUM=0
|
SUM=0
|
||||||
PG=0
|
PG=0
|
||||||
COMPOSE=0
|
|
||||||
|
|
||||||
mark() {
|
mark() {
|
||||||
case "$1" in
|
case "$1" in
|
||||||
|
|
@ -72,8 +80,6 @@ jobs:
|
||||||
SCRAPER=1 ;;
|
SCRAPER=1 ;;
|
||||||
news/summerizer/*)
|
news/summerizer/*)
|
||||||
SUM=1 ;;
|
SUM=1 ;;
|
||||||
docker-compose.yml|scripts/compose-reup.sh)
|
|
||||||
COMPOSE=1 ;;
|
|
||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -108,9 +114,8 @@ 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 compose=$COMPOSE"
|
echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG"
|
||||||
|
|
||||||
- name: Image refs
|
- name: Image refs
|
||||||
id: img
|
id: img
|
||||||
|
|
@ -120,10 +125,11 @@ 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 "sha=$SHA"
|
echo "tag=$TAG"
|
||||||
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"
|
||||||
|
|
@ -131,113 +137,69 @@ jobs:
|
||||||
} >> "$GITHUB_OUTPUT"
|
} >> "$GITHUB_OUTPUT"
|
||||||
echo "Push registry: $PUSH"
|
echo "Push registry: $PUSH"
|
||||||
echo "Public pull: $PUB"
|
echo "Public pull: $PUB"
|
||||||
echo "SHA tag: $SHA"
|
echo "Image tag: $TAG"
|
||||||
|
|
||||||
- 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 with write:package.
|
# reject the Actions token). Use a user PAT.
|
||||||
if [ -z "${{ secrets.FORGEJO_TOKEN }}" ]; then
|
# The PAT must carry the `write:package` scope: Forgejo mints a push
|
||||||
echo "Missing repo secret FORGEJO_TOKEN (user PAT, not GITHUB_TOKEN)"
|
# token even without it and then rejects every blob upload with
|
||||||
|
# `unauthorized: reqPackageAccess` (routers/api/packages/api.go
|
||||||
|
# reqPackageAccess -> AccessTokenScopeWritePackage).
|
||||||
|
# Name is REGISTRY_TOKEN, not FORGEJO_TOKEN: Forgejo reserves the
|
||||||
|
# FORGEJO_/GITHUB_ prefixes and refuses to create or update them via
|
||||||
|
# the API.
|
||||||
|
if [ -z "${{ secrets.REGISTRY_TOKEN }}" ]; then
|
||||||
|
echo "Missing repo secret REGISTRY_TOKEN (user PAT with write:package, not GITHUB_TOKEN)"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
echo "${{ secrets.FORGEJO_TOKEN }}" | docker login "${{ steps.img.outputs.reg }}" \
|
echo "${{ secrets.REGISTRY_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
|
||||||
APP="${{ steps.img.outputs.app }}"
|
IMG="${{ steps.img.outputs.app }}"
|
||||||
SHA="${{ steps.img.outputs.sha }}"
|
TAG="${{ steps.img.outputs.tag }}"
|
||||||
docker build -f Dockerfile -t "${APP}:latest" -t "${APP}:${SHA}" \
|
docker build -f Dockerfile -t "${IMG}:${TAG}" .
|
||||||
-t "localhost/osint-dashboard:latest" .
|
docker push "${IMG}:${TAG}"
|
||||||
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 }}"
|
||||||
SHA="${{ steps.img.outputs.sha }}"
|
TAG="${{ steps.img.outputs.tag }}"
|
||||||
docker build -f news/scraper/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \
|
docker build -f news/scraper/Dockerfile -t "${IMG}:${TAG}" news/scraper
|
||||||
-t "localhost/osint-news-scraper:latest" news/scraper
|
docker push "${IMG}:${TAG}"
|
||||||
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 }}"
|
||||||
SHA="${{ steps.img.outputs.sha }}"
|
TAG="${{ steps.img.outputs.tag }}"
|
||||||
docker build -f news/summerizer/Dockerfile -t "${IMG}:latest" -t "${IMG}:${SHA}" \
|
docker build -f news/summerizer/Dockerfile -t "${IMG}:${TAG}" news/summerizer
|
||||||
-t "localhost/osint-news-summarizer:latest" news/summerizer
|
docker push "${IMG}:${TAG}"
|
||||||
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
|
||||||
PG="${{ steps.img.outputs.pg }}"
|
IMG="${{ steps.img.outputs.pg }}"
|
||||||
SHA="${{ steps.img.outputs.sha }}"
|
TAG="${{ steps.img.outputs.tag }}"
|
||||||
if docker build -f Dockerfile.pg -t "${PG}:latest" -t "${PG}:${SHA}" \
|
docker build -f Dockerfile.pg -t "${IMG}:${TAG}" .
|
||||||
-t "localhost/osint-dashboard-pg:latest" .; then
|
docker push "${IMG}:${TAG}"
|
||||||
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 }}\`"
|
||||||
|
|
@ -245,5 +207,23 @@ 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
|
||||||
echo "Postgres is rebuilt/pulled only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)."
|
if [ -n "$TAG" ]; then
|
||||||
|
echo "## Pin in homek8s (apps/base/osint)"
|
||||||
|
echo "Pushed tag: \`${TAG}\`. Set the workload images in"
|
||||||
|
echo "\`apps/base/osint/kustomization.yaml\` to:"
|
||||||
|
echo
|
||||||
|
echo '```yaml'
|
||||||
|
echo "images:"
|
||||||
|
echo " - name: ${PUB}/${OWNER}/osint-dashboard"
|
||||||
|
echo " newTag: ${TAG}"
|
||||||
|
echo " - name: ${PUB}/${OWNER}/osint-news-scraper"
|
||||||
|
echo " newTag: ${TAG}"
|
||||||
|
echo " - name: ${PUB}/${OWNER}/osint-news-summarizer"
|
||||||
|
echo " newTag: ${TAG}"
|
||||||
|
echo '```'
|
||||||
|
else
|
||||||
|
echo "_No tag computed — the earlier steps failed before Image refs._"
|
||||||
|
fi
|
||||||
|
echo
|
||||||
|
echo "Postgres is rebuilt only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)."
|
||||||
} >> "$GITHUB_STEP_SUMMARY"
|
} >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
|
||||||
40
alembic/versions/014_article_scores_geo.py
Normal file
40
alembic/versions/014_article_scores_geo.py
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
"""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")
|
||||||
|
|
@ -96,6 +96,7 @@ PUBLIC_GET_EXACT = frozenset({
|
||||||
"/api/news/summaries",
|
"/api/news/summaries",
|
||||||
"/api/news/ticker",
|
"/api/news/ticker",
|
||||||
"/api/news/map",
|
"/api/news/map",
|
||||||
|
"/api/news/blips",
|
||||||
# map / live layers
|
# map / live layers
|
||||||
"/api/map/layers",
|
"/api/map/layers",
|
||||||
"/api/map/chokepoints",
|
"/api/map/chokepoints",
|
||||||
|
|
|
||||||
|
|
@ -107,3 +107,12 @@ 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"))
|
||||||
|
|
|
||||||
376
app/geofence.py
376
app/geofence.py
|
|
@ -7,6 +7,7 @@ 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
|
||||||
|
|
@ -15,6 +16,19 @@ 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):
|
||||||
|
|
@ -99,6 +113,160 @@ _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:
|
||||||
|
|
@ -249,12 +417,24 @@ 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
|
||||||
|
|
@ -275,6 +455,33 @@ 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,
|
||||||
|
|
@ -284,7 +491,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": payload or {},
|
"payload": body_payload,
|
||||||
"created_at": now.isoformat(),
|
"created_at": now.isoformat(),
|
||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
|
|
@ -306,7 +513,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(payload or {}),
|
"payload": json.dumps(body_payload),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|
@ -314,6 +521,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:
|
||||||
|
|
@ -470,3 +679,166 @@ async def snapshot_at(gid: str, ts: datetime) -> dict | None:
|
||||||
"vessels": vessels,
|
"vessels": vessels,
|
||||||
"fires": fires,
|
"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,9 +219,32 @@ 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)
|
||||||
|
|
|
||||||
|
|
@ -743,18 +743,25 @@ 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
|
||||||
|
|
||||||
|
|
@ -1084,17 +1091,27 @@ def _wfigs_params(bbox: str | None, *, offset_m: float = 250.0) -> dict:
|
||||||
return params
|
return params
|
||||||
|
|
||||||
|
|
||||||
async def fetch_fire_incidents(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]:
|
_WFIGS_INCIDENT_FIELDS = (
|
||||||
|
"IncidentName,IncidentSize,FireDiscoveryDateTime,POOState,"
|
||||||
|
"PercentContained,IncidentTypeCategory,FireCause,"
|
||||||
|
"IrwinID,UniqueFireIdentifier"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def load_fire_incidents(bbox: str | None) -> list[dict]:
|
||||||
|
"""WFIGS points for a bbox. No last-known mutation, no aircraft correlate."""
|
||||||
params = _wfigs_params(bbox)
|
params = _wfigs_params(bbox)
|
||||||
params["outFields"] = (
|
params["outFields"] = _WFIGS_INCIDENT_FIELDS
|
||||||
"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
|
||||||
|
|
|
||||||
208
app/main.py
208
app/main.py
|
|
@ -37,13 +37,13 @@ from database import async_session, init_extensions
|
||||||
from auth import AdminAuthMiddleware, router as auth_router
|
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_summaries, news_items,
|
articles, article_scores, 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, NewsMapItemOut,
|
EventCreate, EventOut, FireOut, NewsArticleOut, NewsBlipOut, NewsMapItemOut,
|
||||||
NewsSummaryOut, NewsTickerItemOut,
|
NewsSummaryOut, NewsTickerItemOut,
|
||||||
FeedSourceCreate, FeedSourceOut, FeedSourceUpdate,
|
FeedSourceCreate, FeedSourceOut, FeedSourceUpdate,
|
||||||
KeyOut, KeyValueIn,
|
KeyOut, KeyValueIn,
|
||||||
|
|
@ -57,6 +57,7 @@ from camera_scraper import is_public_url
|
||||||
from sources import GDELT_API, ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals
|
from sources import 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,
|
||||||
|
|
@ -125,14 +126,49 @@ 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:
|
||||||
|
|
@ -141,7 +177,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(8)
|
await asyncio.sleep(interval)
|
||||||
|
|
||||||
|
|
||||||
class CachedStaticFiles(StaticFiles):
|
class CachedStaticFiles(StaticFiles):
|
||||||
|
|
@ -272,7 +308,14 @@ 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)
|
||||||
await _age("SELECT max(timestamp) FROM articles", "articles", 2 * 3600)
|
# Same closed-at-now window as GET /api/news. A future max() made age_s
|
||||||
|
# negative and hid a fresh list. NULL timestamps are not fresh.
|
||||||
|
await _age(
|
||||||
|
"SELECT max(timestamp) FROM articles "
|
||||||
|
"WHERE timestamp IS NOT NULL AND timestamp <= now()",
|
||||||
|
"articles",
|
||||||
|
2 * 3600,
|
||||||
|
)
|
||||||
await _age("SELECT max(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600)
|
await _age("SELECT max(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600)
|
||||||
return checks
|
return checks
|
||||||
|
|
||||||
|
|
@ -298,7 +341,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[str, int | str] = {
|
counts: dict = {
|
||||||
"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,
|
||||||
|
|
@ -330,9 +373,41 @@ 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."""
|
||||||
|
|
@ -1309,7 +1384,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=r["title"], url=r["url"],
|
id=r["id"], title=unwrap_cdata_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"],
|
||||||
)
|
)
|
||||||
|
|
@ -1462,6 +1537,94 @@ 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."""
|
||||||
|
|
@ -1788,24 +1951,31 @@ async def api_delete_geofence(gid: str):
|
||||||
@app.get("/api/geofences/{gid}/at")
|
@app.get("/api/geofences/{gid}/at")
|
||||||
async def api_geofence_at(
|
async def api_geofence_at(
|
||||||
gid: str,
|
gid: str,
|
||||||
timestamp: str = Query(..., description="ISO-8601 instant for the 1-minute DVR bucket"),
|
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."""
|
"""Aircraft/vessels/fires inside this fence at time T. Never writes."""
|
||||||
from geofence import snapshot_at
|
from geofence import snapshot_at
|
||||||
from tracks import parse_timestamp
|
from tracks import parse_timestamp
|
||||||
|
|
||||||
|
raw_ts = timestamp or ts
|
||||||
try:
|
try:
|
||||||
ts = parse_timestamp(timestamp)
|
ts_parsed = parse_timestamp(raw_ts)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
raise HTTPException(422, str(exc)) from exc
|
raise HTTPException(422, str(exc)) from exc
|
||||||
if ts is None:
|
if ts_parsed is None:
|
||||||
raise HTTPException(422, "timestamp required")
|
raise HTTPException(422, "timestamp required")
|
||||||
try:
|
try:
|
||||||
body = await snapshot_at(gid, ts)
|
body = await snapshot_at(gid, ts_parsed)
|
||||||
except Exception:
|
except Exception:
|
||||||
body = {
|
body = {
|
||||||
"geofence_id": gid,
|
"geofence_id": gid,
|
||||||
"timestamp": ts.isoformat(),
|
"timestamp": ts_parsed.isoformat(),
|
||||||
"aircraft": [],
|
"aircraft": [],
|
||||||
"vessels": [],
|
"vessels": [],
|
||||||
"fires": [],
|
"fires": [],
|
||||||
|
|
@ -1820,15 +1990,23 @@ async def api_geofence_alerts(
|
||||||
geofence_id: UUID | None = Query(None),
|
geofence_id: UUID | None = Query(None),
|
||||||
since: str | None = Query(None, description="ISO-8601 inclusive lower bound"),
|
since: str | None = Query(None, description="ISO-8601 inclusive lower bound"),
|
||||||
until: str | None = Query(None, description="ISO-8601 inclusive upper bound"),
|
until: str | None = Query(None, description="ISO-8601 inclusive upper bound"),
|
||||||
source_kind: str | None = Query(None, description="firms|ais|adsb"),
|
source_kind: str | None = Query(
|
||||||
|
None,
|
||||||
|
description="firms|ais|adsb|earthquake|fire_incident|news",
|
||||||
|
),
|
||||||
limit: int = Query(100, ge=1, le=500),
|
limit: int = Query(100, ge=1, le=500),
|
||||||
):
|
):
|
||||||
"""Hit log for drawn fences. Not /api/alerts (entity/keyword)."""
|
"""Hit log for drawn fences. Not /api/alerts (entity/keyword)."""
|
||||||
from geofence import list_alerts
|
from geofence import list_alerts
|
||||||
from tracks import parse_timestamp
|
from tracks import parse_timestamp
|
||||||
|
|
||||||
if source_kind is not None and source_kind not in ("firms", "ais", "adsb"):
|
if source_kind is not None and source_kind not in (
|
||||||
raise HTTPException(422, "source_kind must be one of: firms, ais, adsb")
|
"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
|
since_ts = parse_timestamp(since) if since else None
|
||||||
until_ts = parse_timestamp(until) if until else None
|
until_ts = parse_timestamp(until) if until else None
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ from datetime import datetime, timezone
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from sqlalchemy import (
|
from sqlalchemy import (
|
||||||
Column, Enum, Float, Index, Integer, String, Text,
|
Boolean, 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,3 +242,34 @@ 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),
|
||||||
|
)
|
||||||
|
|
|
||||||
33
app/news_title.py
Normal file
33
app/news_title.py
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
"""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()
|
||||||
|
|
@ -56,8 +56,11 @@ 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: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
logger.exception("GDELT fetch failed")
|
# Quota/backoff cases are handled inside ingest_gdelt (one clean
|
||||||
|
# line); anything reaching here is a real failure and a stack
|
||||||
|
# trace every 5 minutes is not actionable, so keep it to one line.
|
||||||
|
logger.warning("GDELT fetch failed: %s", exc)
|
||||||
if ENABLE_QUAKES:
|
if ENABLE_QUAKES:
|
||||||
try:
|
try:
|
||||||
q = await ingest_earthquakes()
|
q = await ingest_earthquakes()
|
||||||
|
|
@ -116,6 +119,24 @@ 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)",
|
||||||
|
|
@ -126,7 +147,9 @@ 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).
|
||||||
|
|
|
||||||
|
|
@ -314,6 +314,26 @@ 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."""
|
||||||
|
|
||||||
|
|
|
||||||
345
app/sources.py
345
app/sources.py
|
|
@ -2,9 +2,15 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import html
|
||||||
|
import io
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime, timezone
|
import os
|
||||||
|
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
|
||||||
|
|
@ -143,6 +149,61 @@ 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:
|
||||||
|
|
@ -175,25 +236,59 @@ def parse_gdelt_articles(data: dict) -> list[dict]:
|
||||||
return events
|
return events
|
||||||
|
|
||||||
|
|
||||||
async def ingest_gdelt(query: str = "", max_articles: int = 50):
|
async def _ingest_gdelt_doc(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)
|
||||||
resp.raise_for_status()
|
except httpx.TransportError as exc:
|
||||||
data = resp.json()
|
|
||||||
except (httpx.TransportError, httpx.HTTPStatusError) as exc:
|
|
||||||
# gdeltproject.org certs have expired in the wild; HTTP fallback.
|
# gdeltproject.org certs have expired in the wild; HTTP fallback.
|
||||||
logger.warning("GDELT HTTPS failed (%s); retrying HTTP", exc)
|
# 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)
|
http_url = GDELT_API.replace("https://", "http://", 1)
|
||||||
resp = await client.get(http_url, params=params)
|
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:
|
||||||
|
# GDELT also signals errors/throttling as HTTP 200 + prose, so a
|
||||||
|
# JSON decode failure is "busy", not "no results".
|
||||||
|
_gdelt_start_backoff(_gdelt_retry_after(resp))
|
||||||
|
logger.warning(
|
||||||
|
"GDELT unusable response (HTTP %s: %s) -> backing off until %s",
|
||||||
|
resp.status_code, str(exc).splitlines()[0][:120], _gdelt_backoff_until_iso(),
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
_gdelt_clear_backoff()
|
||||||
events = parse_gdelt_articles(data if isinstance(data, dict) else {})
|
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)
|
||||||
|
|
@ -201,6 +296,240 @@ async def ingest_gdelt(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:
|
||||||
|
|
|
||||||
|
|
@ -274,6 +274,21 @@
|
||||||
.marker-cluster-medium div { font-size: 11px; }
|
.marker-cluster-medium div { font-size: 11px; }
|
||||||
.marker-cluster-large div { font-size: 12px; }
|
.marker-cluster-large div { font-size: 12px; }
|
||||||
|
|
||||||
|
/* ── Article blip clusters (quiet violet, matches the small blips) ── */
|
||||||
|
.marker-cluster-articles { background-color: rgba(160, 108, 213, 0.16); }
|
||||||
|
.marker-cluster-articles div {
|
||||||
|
background-color: rgba(122, 74, 160, 0.88);
|
||||||
|
color: #efe6f9;
|
||||||
|
font-weight: 600;
|
||||||
|
box-shadow: 0 0 10px rgba(160, 108, 213, 0.35), 0 0 2px rgba(3, 6, 9, 0.9);
|
||||||
|
}
|
||||||
|
.articles-sm div { font-size: 10px; }
|
||||||
|
.articles-md div { font-size: 11px; }
|
||||||
|
.articles-lg div { font-size: 12px; }
|
||||||
|
/* FIRMS heat is visual-only (no listeners) but its canvas sits on top
|
||||||
|
of the overlay pane and eats clicks meant for vector blips/pins. */
|
||||||
|
.leaflet-heatmap-layer { pointer-events: none; }
|
||||||
|
|
||||||
/* ── Map hint + HUD chips ── */
|
/* ── Map hint + HUD chips ── */
|
||||||
.map-hint {
|
.map-hint {
|
||||||
position: absolute; left: 12px; bottom: 12px; z-index: 500;
|
position: absolute; left: 12px; bottom: 12px; z-index: 500;
|
||||||
|
|
@ -299,6 +314,7 @@
|
||||||
.hud-chip .c.cams { background: #4ade80; box-shadow: 0 0 6px #4ade80; }
|
.hud-chip .c.cams { background: #4ade80; box-shadow: 0 0 6px #4ade80; }
|
||||||
.hud-chip .c.blips { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); }
|
.hud-chip .c.blips { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); }
|
||||||
.hud-chip .c.news { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); border-radius: 1px; transform: rotate(45deg); }
|
.hud-chip .c.news { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); border-radius: 1px; transform: rotate(45deg); }
|
||||||
|
.hud-chip .c.articles { background: #a06cd5; box-shadow: 0 0 6px rgba(160,108,213,0.6); }
|
||||||
.hud-chip.off { opacity: 0.4; }
|
.hud-chip.off { opacity: 0.4; }
|
||||||
#dvr-bar {
|
#dvr-bar {
|
||||||
position: absolute; left: 50%; bottom: 12px; transform: translateX(-50%);
|
position: absolute; left: 50%; bottom: 12px; transform: translateX(-50%);
|
||||||
|
|
@ -357,6 +373,7 @@
|
||||||
.lp-dot.cams { background: #4ade80; box-shadow: 0 0 7px #4ade80; }
|
.lp-dot.cams { background: #4ade80; box-shadow: 0 0 7px #4ade80; }
|
||||||
.lp-dot.blips { background: var(--magenta); box-shadow: 0 0 7px var(--magenta); }
|
.lp-dot.blips { background: var(--magenta); box-shadow: 0 0 7px var(--magenta); }
|
||||||
.lp-dot.news { background: var(--cyan); box-shadow: 0 0 7px var(--cyan); }
|
.lp-dot.news { background: var(--cyan); box-shadow: 0 0 7px var(--cyan); }
|
||||||
|
.lp-dot.articles { background: #a06cd5; box-shadow: 0 0 7px rgba(160,108,213,0.6); }
|
||||||
.lp-dot.weather { background: var(--amber); box-shadow: 0 0 7px var(--amber); }
|
.lp-dot.weather { background: var(--amber); box-shadow: 0 0 7px var(--amber); }
|
||||||
.lp-dot.flights { background: #7dd3fc; box-shadow: 0 0 7px #7dd3fc; }
|
.lp-dot.flights { background: #7dd3fc; box-shadow: 0 0 7px #7dd3fc; }
|
||||||
.lp-dot.mil { background: #f472b6; box-shadow: 0 0 7px #f472b6; }
|
.lp-dot.mil { background: #f472b6; box-shadow: 0 0 7px #f472b6; }
|
||||||
|
|
@ -703,7 +720,7 @@
|
||||||
-webkit-mask-image: linear-gradient(90deg, transparent 0, #000 26px, #000 calc(100% - 26px), transparent 100%);
|
-webkit-mask-image: linear-gradient(90deg, transparent 0, #000 26px, #000 calc(100% - 26px), transparent 100%);
|
||||||
}
|
}
|
||||||
.tick-track { display: flex; width: max-content; animation: marquee 60s linear infinite; }
|
.tick-track { display: flex; width: max-content; animation: marquee 60s linear infinite; }
|
||||||
.ticker.news .tick-track { animation-duration: 90s; }
|
.ticker.news .tick-track { animation-duration: 240s; } /* fallback; JS sets constant px/s */
|
||||||
.tick-wrap:hover .tick-track, .tick-wrap:focus-within .tick-track { animation-play-state: paused; }
|
.tick-wrap:hover .tick-track, .tick-wrap:focus-within .tick-track { animation-play-state: paused; }
|
||||||
@keyframes marquee { from { transform: translateX(0); } to { transform: translateX(-50%); } }
|
@keyframes marquee { from { transform: translateX(0); } to { transform: translateX(-50%); } }
|
||||||
.tick-group { display: flex; align-items: center; }
|
.tick-group { display: flex; align-items: center; }
|
||||||
|
|
@ -1017,6 +1034,12 @@
|
||||||
<span class="lp-count" id="lp-news-count">0</span>
|
<span class="lp-count" id="lp-news-count">0</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="lp-layer">
|
||||||
|
<div class="lp-row">
|
||||||
|
<label class="lp-name" title="Per-article proximate locations from the news feed (last 24h)"><input type="checkbox" id="lp-articles-on" onchange="toggleArticleBlips()"> <span class="lp-dot articles"></span> Article Blips</label>
|
||||||
|
<span class="lp-count" id="lp-articles-count">0</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="lp-layer">
|
<div class="lp-layer">
|
||||||
<div class="lp-row">
|
<div class="lp-row">
|
||||||
|
|
@ -1121,6 +1144,7 @@
|
||||||
<div class="hud-chip" id="hud-cams"><span class="c cams"></span>CAMS <b id="hud-cams-n">—</b></div>
|
<div class="hud-chip" id="hud-cams"><span class="c cams"></span>CAMS <b id="hud-cams-n">—</b></div>
|
||||||
<div class="hud-chip" id="hud-blips"><span class="c blips"></span>BLIPS <b id="hud-blips-n">—</b></div>
|
<div class="hud-chip" id="hud-blips"><span class="c blips"></span>BLIPS <b id="hud-blips-n">—</b></div>
|
||||||
<div class="hud-chip" id="hud-news"><span class="c news"></span>NEWS <b id="hud-news-n">—</b></div>
|
<div class="hud-chip" id="hud-news"><span class="c news"></span>NEWS <b id="hud-news-n">—</b></div>
|
||||||
|
<div class="hud-chip" id="hud-articles"><span class="c articles"></span>ARTICLES <b id="hud-articles-n">—</b></div>
|
||||||
</div>
|
</div>
|
||||||
<div id="cheat-sheet" class="cheat-sheet" hidden role="dialog" aria-label="Keyboard shortcuts">
|
<div id="cheat-sheet" class="cheat-sheet" hidden role="dialog" aria-label="Keyboard shortcuts">
|
||||||
<h3>Shortcuts</h3>
|
<h3>Shortcuts</h3>
|
||||||
|
|
@ -1497,6 +1521,7 @@ const COUNT_HUD = {
|
||||||
'lp-cams-count': 'hud-cams-n',
|
'lp-cams-count': 'hud-cams-n',
|
||||||
'lp-blips-count': 'hud-blips-n',
|
'lp-blips-count': 'hud-blips-n',
|
||||||
'lp-news-count': 'hud-news-n',
|
'lp-news-count': 'hud-news-n',
|
||||||
|
'lp-articles-count': 'hud-articles-n',
|
||||||
};
|
};
|
||||||
function setLayerCount(id, value) {
|
function setLayerCount(id, value) {
|
||||||
const el = document.getElementById(id);
|
const el = document.getElementById(id);
|
||||||
|
|
@ -1756,6 +1781,7 @@ function showView(name) {
|
||||||
if (camsOn) loadCams();
|
if (camsOn) loadCams();
|
||||||
if (blipsOn) loadBlips();
|
if (blipsOn) loadBlips();
|
||||||
if (newsOn) loadNewsPins();
|
if (newsOn) loadNewsPins();
|
||||||
|
if (articlesOn) loadArticleBlips();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (name === 'news') loadNews(false);
|
if (name === 'news') loadNews(false);
|
||||||
|
|
@ -1848,6 +1874,7 @@ function initMarketTicker() {
|
||||||
/* ═══════════════ NEWS FEED + TICKER ═══════════════ */
|
/* ═══════════════ NEWS FEED + TICKER ═══════════════ */
|
||||||
let newsInterval = null;
|
let newsInterval = null;
|
||||||
const NEWS_REFRESH_MS = 180000; // 3-min ticker/brief poll
|
const NEWS_REFRESH_MS = 180000; // 3-min ticker/brief poll
|
||||||
|
const NEWS_TICKER_PX_PER_S = 28; // constant readable scroll speed for the news ticker
|
||||||
let newsTickerBuilt = false;
|
let newsTickerBuilt = false;
|
||||||
|
|
||||||
function newsEsc(s) {
|
function newsEsc(s) {
|
||||||
|
|
@ -1990,6 +2017,13 @@ function renderNewsTicker(articles, summaries, tickerItems) {
|
||||||
items = `<span class="tick-item standby">No headlines yet — scraper idle</span>`;
|
items = `<span class="tick-item standby">No headlines yet — scraper idle</span>`;
|
||||||
}
|
}
|
||||||
track.innerHTML = `<span class="tick-group">${items}</span><span class="tick-group">${items}</span>`;
|
track.innerHTML = `<span class="tick-group">${items}</span><span class="tick-group">${items}</span>`;
|
||||||
|
// Constant pixel speed regardless of headline count: the marquee travels
|
||||||
|
// one group width (track = two identical copies, keyframe goes to -50%).
|
||||||
|
// Recomputed on every rebuild; market ticker keeps its own CSS duration.
|
||||||
|
const groupWidth = track.scrollWidth / 2;
|
||||||
|
track.style.animationDuration = groupWidth > 0
|
||||||
|
? `${(groupWidth / NEWS_TICKER_PX_PER_S).toFixed(2)}s`
|
||||||
|
: '';
|
||||||
newsTickerBuilt = true;
|
newsTickerBuilt = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2323,7 +2357,8 @@ async function saveSummaryModel() {
|
||||||
let map = null, mapLayer = null, mapInitStarted = false;
|
let map = null, mapLayer = null, mapInitStarted = false;
|
||||||
let firesHeat = null, camsGroup = null, firesOn = false, camsOn = false;
|
let firesHeat = null, camsGroup = null, firesOn = false, camsOn = false;
|
||||||
let blipsGroup = null, blipsOn = false, blipsSince = '24h';
|
let blipsGroup = null, blipsOn = false, blipsSince = '24h';
|
||||||
let newsGroup = null, newsOn = false, newsReq = 0;
|
let newsGroup = null, newsOn = false, newsReq = 0, newsRenderer = null;
|
||||||
|
let articlesGroup = null, articlesOn = false, articlesReq = 0, articlesTimer = null, articlesRenderer = null;
|
||||||
let firesOpacity = 0.65, firesColor = 'brightness', firesSince = '24h';
|
let firesOpacity = 0.65, firesColor = 'brightness', firesSince = '24h';
|
||||||
let camsOpacity = 1.0, baseOpacity = 1.0;
|
let camsOpacity = 1.0, baseOpacity = 1.0;
|
||||||
let camReq = 0, fireReq = 0, blipReq = 0; // stale-response guards (rapid zoom races)
|
let camReq = 0, fireReq = 0, blipReq = 0; // stale-response guards (rapid zoom races)
|
||||||
|
|
@ -2487,6 +2522,17 @@ function overlayFetch(url) {
|
||||||
return fetch(url, overlayAbort ? { signal: overlayAbort.signal } : {});
|
return fetch(url, overlayAbort ? { signal: overlayAbort.signal } : {});
|
||||||
}
|
}
|
||||||
function isAbort(e) { return e && e.name === 'AbortError'; }
|
function isAbort(e) { return e && e.name === 'AbortError'; }
|
||||||
|
/* Leaflet 1.9.4 race guard: a moveend-driven _updatePaths() calls _redraw()
|
||||||
|
directly, which nulls _redrawRequest WITHOUT cancelling an already-pending
|
||||||
|
animation frame. If the renderer is removed before that orphaned frame
|
||||||
|
fires (e.g. layer toggle-off), _redraw crashes on the deleted 2d context
|
||||||
|
("Cannot read properties of undefined (reading 'clearRect')"). No-op
|
||||||
|
redraws on detached renderers instead; live renderers are unaffected. */
|
||||||
|
const _canvasRedraw = L.Canvas.prototype._redraw;
|
||||||
|
L.Canvas.prototype._redraw = function () {
|
||||||
|
if (!this._ctx) return;
|
||||||
|
return _canvasRedraw.apply(this, arguments);
|
||||||
|
};
|
||||||
const pointCanvas = () => L.canvas({ padding: 0.5 });
|
const pointCanvas = () => L.canvas({ padding: 0.5 });
|
||||||
|
|
||||||
async function initMap() {
|
async function initMap() {
|
||||||
|
|
@ -2501,10 +2547,12 @@ async function initMap() {
|
||||||
const sel = document.getElementById('map-layer');
|
const sel = document.getElementById('map-layer');
|
||||||
sel.innerHTML = mapLayers.map(l =>
|
sel.innerHTML = mapLayers.map(l =>
|
||||||
`<option value="${l.id}">${l.title}</option>`).join('');
|
`<option value="${l.id}">${l.title}</option>`).join('');
|
||||||
|
// Blue Marble first: static, gap-free basemap. Satellite true-color
|
||||||
|
// (VIIRS/MODIS) has cloud/coverage gaps — still selectable below.
|
||||||
const preferred =
|
const preferred =
|
||||||
mapLayers.find(l => l.id === 'VIIRS_SNPP_CorrectedReflectance_TrueColor')
|
mapLayers.find(l => l.id === 'BlueMarble_ShadedRelief_Bathymetry')
|
||||||
|
|| mapLayers.find(l => l.id === 'VIIRS_SNPP_CorrectedReflectance_TrueColor')
|
||||||
|| mapLayers.find(l => l.id === 'MODIS_Terra_CorrectedReflectance_TrueColor')
|
|| mapLayers.find(l => l.id === 'MODIS_Terra_CorrectedReflectance_TrueColor')
|
||||||
|| mapLayers.find(l => l.id === 'BlueMarble_ShadedRelief_Bathymetry')
|
|
||||||
|| mapLayers.find(l => !l.has_time)
|
|| mapLayers.find(l => !l.has_time)
|
||||||
|| mapLayers[0];
|
|| mapLayers[0];
|
||||||
if (preferred) sel.value = preferred.id;
|
if (preferred) sel.value = preferred.id;
|
||||||
|
|
@ -2611,6 +2659,7 @@ async function initMap() {
|
||||||
if (camsOn) loadCams();
|
if (camsOn) loadCams();
|
||||||
if (blipsOn) loadBlips();
|
if (blipsOn) loadBlips();
|
||||||
if (newsOn) loadNewsPins();
|
if (newsOn) loadNewsPins();
|
||||||
|
if (articlesOn) loadArticleBlips();
|
||||||
refreshLiveOverlays();
|
refreshLiveOverlays();
|
||||||
sendLiveViewport();
|
sendLiveViewport();
|
||||||
}, 500);
|
}, 500);
|
||||||
|
|
@ -2623,6 +2672,7 @@ async function initMap() {
|
||||||
camsOn = document.getElementById('lp-cams-on').checked;
|
camsOn = document.getElementById('lp-cams-on').checked;
|
||||||
blipsOn = document.getElementById('lp-blips-on').checked;
|
blipsOn = document.getElementById('lp-blips-on').checked;
|
||||||
newsOn = document.getElementById('lp-news-on').checked;
|
newsOn = document.getElementById('lp-news-on').checked;
|
||||||
|
articlesOn = document.getElementById('lp-articles-on').checked;
|
||||||
firesSince = document.getElementById('lp-fires-since').value;
|
firesSince = document.getElementById('lp-fires-since').value;
|
||||||
blipsSince = document.getElementById('lp-blips-since').value;
|
blipsSince = document.getElementById('lp-blips-since').value;
|
||||||
radarOn = document.getElementById('lp-radar-on').checked;
|
radarOn = document.getElementById('lp-radar-on').checked;
|
||||||
|
|
@ -2645,6 +2695,7 @@ async function initMap() {
|
||||||
if (camsOn) loadCams();
|
if (camsOn) loadCams();
|
||||||
if (blipsOn) loadBlips();
|
if (blipsOn) loadBlips();
|
||||||
if (newsOn) loadNewsPins();
|
if (newsOn) loadNewsPins();
|
||||||
|
if (articlesOn) loadArticleBlips();
|
||||||
refreshLiveOverlays();
|
refreshLiveOverlays();
|
||||||
}, 250);
|
}, 250);
|
||||||
});
|
});
|
||||||
|
|
@ -2667,8 +2718,9 @@ function syncHud() {
|
||||||
set('cams', camsOn);
|
set('cams', camsOn);
|
||||||
set('blips', blipsOn);
|
set('blips', blipsOn);
|
||||||
set('news', newsOn);
|
set('news', newsOn);
|
||||||
|
set('articles', articlesOn);
|
||||||
}
|
}
|
||||||
let hudFiresCount = null, hudCamsCount = null, hudBlipsCount = null, hudNewsCount = null;
|
let hudFiresCount = null, hudCamsCount = null, hudBlipsCount = null, hudNewsCount = null, hudArticlesCount = null;
|
||||||
|
|
||||||
function setMapAttribution(text) {
|
function setMapAttribution(text) {
|
||||||
if (!map) return;
|
if (!map) return;
|
||||||
|
|
@ -3250,6 +3302,7 @@ async function toggleNewsPins() {
|
||||||
}
|
}
|
||||||
newsReq++;
|
newsReq++;
|
||||||
if (newsGroup && map) { map.removeLayer(newsGroup); newsGroup = null; }
|
if (newsGroup && map) { map.removeLayer(newsGroup); newsGroup = null; }
|
||||||
|
if (newsRenderer && map) { map.removeLayer(newsRenderer); newsRenderer = null; }
|
||||||
hudNewsCount = null;
|
hudNewsCount = null;
|
||||||
setLayerCount('lp-news-count', '0');
|
setLayerCount('lp-news-count', '0');
|
||||||
syncHud();
|
syncHud();
|
||||||
|
|
@ -3265,11 +3318,16 @@ async function loadNewsPins() {
|
||||||
const items = Array.isArray(data) ? data : [];
|
const items = Array.isArray(data) ? data : [];
|
||||||
if (newsGroup) map.removeLayer(newsGroup);
|
if (newsGroup) map.removeLayer(newsGroup);
|
||||||
const col = '#35e0ff';
|
const col = '#35e0ff';
|
||||||
|
// One persistent canvas renderer shared by ALL pins: L.Canvas
|
||||||
|
// hit-tests every drawn path, so each pin stays clickable (a fresh
|
||||||
|
// canvas per pin stacked empty siblings over all but the last), and
|
||||||
|
// reusing it across refreshes leaks no full-viewport containers.
|
||||||
|
const renderer = newsRenderer || (newsRenderer = L.canvas({ padding: 0.5 }));
|
||||||
const pins = items.filter(it => Number.isFinite(Number(it.lat)) && Number.isFinite(Number(it.lon)));
|
const pins = items.filter(it => Number.isFinite(Number(it.lat)) && Number.isFinite(Number(it.lon)));
|
||||||
newsGroup = L.layerGroup(pins.map(it => {
|
newsGroup = L.layerGroup(pins.map(it => {
|
||||||
return L.circleMarker([it.lat, it.lon], {
|
return L.circleMarker([it.lat, it.lon], {
|
||||||
radius: 6, weight: 1, color: col, fillColor: col, fillOpacity: 0.7,
|
radius: 6, weight: 1, color: col, fillColor: col, fillOpacity: 0.7,
|
||||||
renderer: pointCanvas(),
|
renderer,
|
||||||
})
|
})
|
||||||
.bindPopup(`<div class="blip-pop">` +
|
.bindPopup(`<div class="blip-pop">` +
|
||||||
`<div class="blip-src">◈ ${esc(it.importance || '')}${it.category ? ' · ' + esc(it.category) : ''}</div>` +
|
`<div class="blip-src">◈ ${esc(it.importance || '')}${it.category ? ' · ' + esc(it.category) : ''}</div>` +
|
||||||
|
|
@ -3289,6 +3347,106 @@ async function loadNewsPins() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── ARTICLE BLIPS (per-article proximate geo, all severities) ──
|
||||||
|
GET /api/news/blips — dense field of small clustered circleMarkers.
|
||||||
|
Separate from the critical-pin layer above; default OFF. Until the
|
||||||
|
backend endpoint lands, a 404 idles the layer at 0 without breaking
|
||||||
|
the map or the critical pins. */
|
||||||
|
const ARTICLE_BLIP_COL = '#a06cd5'; // quiet violet — critical pins are cyan
|
||||||
|
function articleBlipPopup(b) {
|
||||||
|
const loc = esc(b.location_name || 'no location label') +
|
||||||
|
(b.location_confidence ? ' (' + esc(b.location_confidence) + ')' : '');
|
||||||
|
const meta = [newsTimeAgo(b.created_at), loc];
|
||||||
|
if (b.score != null) meta.push('score ' + esc(b.score));
|
||||||
|
return `<div class="blip-pop">` +
|
||||||
|
`<div class="blip-src">◈ ${esc(b.domain || 'article')}${b.category ? ' · ' + esc(b.category) : ''}</div>` +
|
||||||
|
`<b>${esc(b.headline || 'Untitled article')}</b>` +
|
||||||
|
`<div class="blip-time">${meta.join(' · ')}</div>` +
|
||||||
|
(b.url ? `<a href="${esc(b.url)}" target="_blank" rel="noopener">source ↗</a>` : '') +
|
||||||
|
`</div>`;
|
||||||
|
}
|
||||||
|
async function toggleArticleBlips() {
|
||||||
|
articlesOn = document.getElementById('lp-articles-on').checked;
|
||||||
|
if (articlesOn) {
|
||||||
|
await loadArticleBlips();
|
||||||
|
// Same cadence as the news poll; own timer so the layer refreshes
|
||||||
|
// even when the News view (which starts newsInterval) was never opened.
|
||||||
|
if (!articlesTimer) articlesTimer = setInterval(() => { if (articlesOn) loadArticleBlips(); }, NEWS_REFRESH_MS);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
articlesReq++;
|
||||||
|
if (articlesTimer) { clearInterval(articlesTimer); articlesTimer = null; }
|
||||||
|
articlesGroup = dropLayer(articlesGroup);
|
||||||
|
if (articlesRenderer && map) { map.removeLayer(articlesRenderer); articlesRenderer = null; }
|
||||||
|
hudArticlesCount = null;
|
||||||
|
setLayerCount('lp-articles-count', '0');
|
||||||
|
syncHud();
|
||||||
|
}
|
||||||
|
async function loadArticleBlips() {
|
||||||
|
if (!map) return;
|
||||||
|
const req = ++articlesReq;
|
||||||
|
const zero = () => {
|
||||||
|
articlesGroup = dropLayer(articlesGroup);
|
||||||
|
hudArticlesCount = 0;
|
||||||
|
setLayerCount('lp-articles-count', '0');
|
||||||
|
syncHud();
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const r = await overlayFetch(`${API}/api/news/blips?bbox=${currentBBox()}&limit=1000`);
|
||||||
|
if (req !== articlesReq) return; // superseded by a newer pan/zoom
|
||||||
|
if (!r.ok) {
|
||||||
|
console.warn(`Article blips: /api/news/blips ${r.status} — layer idle`);
|
||||||
|
zero();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = await r.json();
|
||||||
|
if (req !== articlesReq) return;
|
||||||
|
const seen = new Set();
|
||||||
|
const rows = (Array.isArray(data) ? data : []).filter(b => {
|
||||||
|
if (!Number.isFinite(Number(b.lat)) || !Number.isFinite(Number(b.lon))) return false;
|
||||||
|
if (b.id != null) { if (seen.has(b.id)) return false; seen.add(b.id); }
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
articlesGroup = dropLayer(articlesGroup);
|
||||||
|
// One persistent SVG renderer: paths are individually clickable and
|
||||||
|
// the pe:none root lets clicks fall through to the canvas pins below
|
||||||
|
// (Leaflet stacks svg z200 over canvas z100). A fresh renderer per
|
||||||
|
// refresh would leak a full-viewport container on every pan/zoom.
|
||||||
|
const renderer = articlesRenderer || (articlesRenderer = L.svg({ padding: 0.5 }));
|
||||||
|
const markers = rows.map(b => L.circleMarker([Number(b.lat), Number(b.lon)], {
|
||||||
|
radius: 3, weight: 1, color: ARTICLE_BLIP_COL, fillColor: ARTICLE_BLIP_COL,
|
||||||
|
fillOpacity: 0.5, opacity: 0.75, renderer,
|
||||||
|
}).bindPopup(articleBlipPopup(b)));
|
||||||
|
articlesGroup = L.markerClusterGroup({
|
||||||
|
maxClusterRadius: 40,
|
||||||
|
showCoverageOnHover: false,
|
||||||
|
spiderfyOnMaxZoom: true,
|
||||||
|
chunkedLoading: true,
|
||||||
|
chunkInterval: 100,
|
||||||
|
chunkDelay: 10,
|
||||||
|
iconCreateFunction: (cluster) => {
|
||||||
|
const n = cluster.getChildCount();
|
||||||
|
const size = n < 10 ? 'sm' : n < 100 ? 'md' : 'lg';
|
||||||
|
return L.divIcon({
|
||||||
|
html: '<div><span>' + n + '</span></div>',
|
||||||
|
className: 'marker-cluster marker-cluster-articles articles-' + size,
|
||||||
|
iconSize: L.point(40, 40),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
articlesGroup.addLayers(markers);
|
||||||
|
articlesGroup.addTo(map);
|
||||||
|
setLayerCount('lp-articles-count', rows.length.toLocaleString());
|
||||||
|
hudArticlesCount = rows.length;
|
||||||
|
syncHud();
|
||||||
|
} catch (e) {
|
||||||
|
if (isAbort(e)) return;
|
||||||
|
if (req !== articlesReq) return;
|
||||||
|
console.warn('Article blips load failed', e);
|
||||||
|
zero();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* ── Live overlays (radar / alerts / WFIGS / aircraft / trains / AIS / NHC) ── */
|
/* ── Live overlays (radar / alerts / WFIGS / aircraft / trains / AIS / NHC) ── */
|
||||||
function refreshLiveOverlays() {
|
function refreshLiveOverlays() {
|
||||||
if (!map) return;
|
if (!map) return;
|
||||||
|
|
@ -4367,6 +4525,53 @@ function gfHitTime(p) {
|
||||||
if (Number.isNaN(d.getTime())) return String(raw).slice(11, 19) || '—';
|
if (Number.isNaN(d.getTime())) return String(raw).slice(11, 19) || '—';
|
||||||
return d.toISOString().slice(11, 19) + 'Z';
|
return d.toISOString().slice(11, 19) + 'Z';
|
||||||
}
|
}
|
||||||
|
function gfEvidence(p) {
|
||||||
|
if (!p || typeof p !== 'object') return null;
|
||||||
|
let payload = p.payload;
|
||||||
|
if (typeof payload === 'string') {
|
||||||
|
try { payload = JSON.parse(payload); }
|
||||||
|
catch (e) { payload = null; }
|
||||||
|
}
|
||||||
|
if (payload && typeof payload === 'object' && payload.evidence && typeof payload.evidence === 'object') {
|
||||||
|
return payload.evidence;
|
||||||
|
}
|
||||||
|
if (p.evidence && typeof p.evidence === 'object') return p.evidence;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
function gfNewsHref(url) {
|
||||||
|
const u = String(url == null ? '' : url).trim();
|
||||||
|
if (!u) return '';
|
||||||
|
const low = u.slice(0, 16).toLowerCase();
|
||||||
|
if (low.startsWith('rtsp:') || low.startsWith('javascript:') || low.startsWith('data:')) return '';
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
function gfHitEvidenceHtml(ev) {
|
||||||
|
if (!ev || typeof ev !== 'object' || Array.isArray(ev)) return '';
|
||||||
|
const cams = Array.isArray(ev.cameras) ? ev.cameras.slice(0, 5) : [];
|
||||||
|
const news = Array.isArray(ev.news) ? ev.news.slice(0, 3) : [];
|
||||||
|
const bits = [];
|
||||||
|
if (cams.length) {
|
||||||
|
const first = cams[0] && typeof cams[0] === 'object' ? cams[0] : {};
|
||||||
|
const name = first.name == null ? '' : String(first.name).trim();
|
||||||
|
let line = cams.length + ' cams';
|
||||||
|
if (name) line += ' · ' + newsEsc(name);
|
||||||
|
bits.push(line);
|
||||||
|
}
|
||||||
|
const item = news[0] && typeof news[0] === 'object' ? news[0] : null;
|
||||||
|
const headline = item && item.headline != null ? String(item.headline).trim() : '';
|
||||||
|
if (headline) {
|
||||||
|
const href = gfNewsHref(item.url);
|
||||||
|
if (href) {
|
||||||
|
bits.push(
|
||||||
|
`<a href="${newsEsc(href)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">${newsEsc(headline)}</a>`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
bits.push(newsEsc(headline));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!bits.length) return '';
|
||||||
|
return `<span class="gf-hit-ev">${bits.join(' · ')}</span>`;
|
||||||
|
}
|
||||||
function pushGfInbox(p) {
|
function pushGfInbox(p) {
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const box = document.getElementById('gf-inbox');
|
const box = document.getElementById('gf-inbox');
|
||||||
|
|
@ -4379,9 +4584,16 @@ function pushGfInbox(p) {
|
||||||
el.dataset.gid = gid;
|
el.dataset.gid = gid;
|
||||||
if (p.lat != null) el.dataset.lat = String(p.lat);
|
if (p.lat != null) el.dataset.lat = String(p.lat);
|
||||||
if (p.lon != null) el.dataset.lon = String(p.lon);
|
if (p.lon != null) el.dataset.lon = String(p.lon);
|
||||||
el.innerHTML = `<span class="gf-hit-meta">${newsEsc(gfHitTime(p))}</span> · ${newsEsc(name)}` +
|
const meta = `<span class="gf-hit-meta">${newsEsc(gfHitTime(p))}</span> · ${newsEsc(name)}` +
|
||||||
` · ${newsEsc(p.source_kind || '')} · ${newsEsc(p.entity_id || '')}`;
|
` · ${newsEsc(p.source_kind || '')} · ${newsEsc(p.entity_id || '')}`;
|
||||||
el.onclick = () => onGfHitClick(el);
|
let ev = '';
|
||||||
|
try { ev = gfHitEvidenceHtml(gfEvidence(p)); } catch (e) { ev = ''; }
|
||||||
|
el.innerHTML = ev ? meta + '<br>' + ev : meta;
|
||||||
|
el.onclick = (clickEv) => {
|
||||||
|
const t = clickEv && clickEv.target;
|
||||||
|
if (t && t.closest && t.closest('a')) return;
|
||||||
|
onGfHitClick(el);
|
||||||
|
};
|
||||||
box.prepend(el);
|
box.prepend(el);
|
||||||
while (box.children.length > 50) box.removeChild(box.lastChild);
|
while (box.children.length > 50) box.removeChild(box.lastChild);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@
|
||||||
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
|
||||||
|
|
||||||
|
|
@ -30,3 +31,26 @@ 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()
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,8 @@ 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__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Feed items dated further ahead than this are event listings (or clock skew
|
# Feed items dated further ahead than this are event listings (or clock skew
|
||||||
|
|
@ -104,6 +106,7 @@ class PostgresPipeline:
|
||||||
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)
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,8 @@ 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 ./
|
COPY summarizer.py run_news_summarizer.py intel.py nous_client.py gazetteer.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
|
||||||
|
|
|
||||||
28
news/summerizer/data/README.md
Normal file
28
news/summerizer/data/README.md
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
# 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.
|
||||||
3865
news/summerizer/data/admin1.tsv
Normal file
3865
news/summerizer/data/admin1.tsv
Normal file
File diff suppressed because it is too large
Load diff
34248
news/summerizer/data/cities15000.tsv
Normal file
34248
news/summerizer/data/cities15000.tsv
Normal file
File diff suppressed because it is too large
Load diff
252
news/summerizer/data/countries.tsv
Normal file
252
news/summerizer/data/countries.tsv
Normal file
|
|
@ -0,0 +1,252 @@
|
||||||
|
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
|
||||||
|
193
news/summerizer/gazetteer.py
Normal file
193
news/summerizer/gazetteer.py
Normal file
|
|
@ -0,0 +1,193 @@
|
||||||
|
"""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
|
||||||
|
|
@ -26,6 +26,84 @@ _ARTICLE_RE = re.compile(r"^[ \t>*_#\-]*Article[ \t]+(\d{1,3})[ \t]*:", re.IGNOR
|
||||||
_SCORE_RE = re.compile(r"Score:\s*(\d{1,3})", re.IGNORECASE)
|
_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)
|
_IMPORTANCE_RE = re.compile(r"Importance:\s*(critical|high|medium|low|none)", re.IGNORECASE)
|
||||||
_CATEGORY_RE = re.compile(r"Category:\s*(.+)", 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:
|
||||||
|
|
@ -157,7 +235,14 @@ def parse_map_scores(
|
||||||
Returns ``(blocks, stats)`` where each block is::
|
Returns ``(blocks, stats)`` where each block is::
|
||||||
|
|
||||||
{"n", "article", "article_id", "score", "importance", "category",
|
{"n", "article", "article_id", "score", "importance", "category",
|
||||||
|
"location_name", "lat", "lon", "location_confidence",
|
||||||
"text", "position"}
|
"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 ""
|
text = raw or ""
|
||||||
matches = list(_ARTICLE_RE.finditer(text))
|
matches = list(_ARTICLE_RE.finditer(text))
|
||||||
|
|
@ -198,6 +283,7 @@ def parse_map_scores(
|
||||||
"score": score,
|
"score": score,
|
||||||
"importance": importance,
|
"importance": importance,
|
||||||
"category": _category_from_block(block_text),
|
"category": _category_from_block(block_text),
|
||||||
|
**_geo_from_block(block_text),
|
||||||
"text": block_text,
|
"text": block_text,
|
||||||
"position": offset,
|
"position": offset,
|
||||||
}
|
}
|
||||||
|
|
@ -291,6 +377,69 @@ def normalize_title(title) -> str:
|
||||||
return " ".join(_NON_ALNUM_RE.sub(" ", text).split())
|
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:
|
def title_similarity(normalised_left: str, normalised_right: str) -> float:
|
||||||
"""0..1 story-similarity of two already-normalised titles.
|
"""0..1 story-similarity of two already-normalised titles.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,12 @@ from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
import psycopg2
|
import psycopg2
|
||||||
|
|
||||||
|
from gazetteer import fill_block_geo
|
||||||
from intel import (
|
from intel import (
|
||||||
|
GEO_CONFIDENCES,
|
||||||
|
article_url_for_row,
|
||||||
|
clamp_coords,
|
||||||
|
clean_location_name,
|
||||||
dedupe_blocks,
|
dedupe_blocks,
|
||||||
join_blocks,
|
join_blocks,
|
||||||
parse_map_scores,
|
parse_map_scores,
|
||||||
|
|
@ -175,7 +180,7 @@ Grade every article with this rubric before writing anything else in its block:
|
||||||
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. Score: the integer 0-100 from the rubric above, first line of the block.
|
||||||
2. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
2. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
||||||
3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit.
|
3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit. Confidence: how precise that location is — exact (a specific site/address), city, region, or country. Never invent a place.
|
||||||
4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
||||||
5. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
5. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
||||||
6. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
|
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."
|
||||||
|
|
@ -191,6 +196,7 @@ Article 1:
|
||||||
- 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: ...
|
||||||
|
|
@ -418,8 +424,15 @@ def ensure_tables() -> None:
|
||||||
PRIMARY KEY (article_id, created_at)
|
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 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
|
CREATE INDEX IF NOT EXISTS ix_article_scores_summary
|
||||||
ON article_scores (summary_id);
|
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)
|
||||||
|
|
@ -511,9 +524,19 @@ def _already_recapped_today() -> bool:
|
||||||
|
|
||||||
|
|
||||||
def save_batch(
|
def save_batch(
|
||||||
summary_en: str, model: str, ticker: list, map_items: list, *, kind: str = "interval"
|
summary_en: str,
|
||||||
|
model: str,
|
||||||
|
ticker: list,
|
||||||
|
map_items: list,
|
||||||
|
*,
|
||||||
|
kind: str = "interval",
|
||||||
|
articles: list | None = None,
|
||||||
) -> int | None:
|
) -> int | None:
|
||||||
"""Insert the master brief plus flagged ticker/map rows. Returns the new summary id."""
|
"""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()
|
||||||
|
|
@ -547,7 +570,7 @@ def save_batch(
|
||||||
None,
|
None,
|
||||||
None,
|
None,
|
||||||
None,
|
None,
|
||||||
row.get("url"),
|
article_url_for_row(row, articles),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
for row in map_rows:
|
for row in map_rows:
|
||||||
|
|
@ -563,7 +586,7 @@ def save_batch(
|
||||||
row.get("lon"),
|
row.get("lon"),
|
||||||
row.get("location_confidence"),
|
row.get("location_confidence"),
|
||||||
row.get("category"),
|
row.get("category"),
|
||||||
row.get("url"),
|
article_url_for_row(row, articles),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
@ -587,6 +610,9 @@ def persist_article_scores(
|
||||||
Syndication duplicates are written too, with ``selected=false`` and
|
Syndication duplicates are written too, with ``selected=false`` and
|
||||||
``duplicate_of`` pointing at the surviving article id — the representative
|
``duplicate_of`` pointing at the surviving article id — the representative
|
||||||
carries the selection even when the copy itself scores above the bar.
|
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.
|
Best-effort: a failure here is logged and never aborts the run.
|
||||||
"""
|
"""
|
||||||
rows = []
|
rows = []
|
||||||
|
|
@ -597,6 +623,12 @@ def persist_article_scores(
|
||||||
duplicate_of = block.get("duplicate_of")
|
duplicate_of = block.get("duplicate_of")
|
||||||
if not isinstance(duplicate_of, int):
|
if not isinstance(duplicate_of, int):
|
||||||
duplicate_of = None
|
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(
|
rows.append(
|
||||||
(
|
(
|
||||||
article_id,
|
article_id,
|
||||||
|
|
@ -606,6 +638,10 @@ def persist_article_scores(
|
||||||
bool(block.get("selected")) and duplicate_of is None,
|
bool(block.get("selected")) and duplicate_of is None,
|
||||||
model,
|
model,
|
||||||
duplicate_of,
|
duplicate_of,
|
||||||
|
location_name,
|
||||||
|
lat,
|
||||||
|
lon,
|
||||||
|
confidence,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if not rows:
|
if not rows:
|
||||||
|
|
@ -615,17 +651,19 @@ def persist_article_scores(
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.executemany(
|
cur.executemany(
|
||||||
"INSERT INTO article_scores "
|
"INSERT INTO article_scores "
|
||||||
"(article_id, summary_id, score, category, selected, model, duplicate_of) "
|
"(article_id, summary_id, score, category, selected, model, duplicate_of, "
|
||||||
"VALUES (%s, %s, %s, %s, %s, %s, %s)",
|
" location_name, lat, lon, location_confidence) "
|
||||||
|
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
||||||
rows,
|
rows,
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
cur.close()
|
cur.close()
|
||||||
conn.close()
|
conn.close()
|
||||||
logger.info(
|
logger.info(
|
||||||
"article_scores persisted rows=%d selected=%d duplicates=%d summary_id=%s",
|
"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]),
|
len(rows), sum(1 for r in rows if r[4]),
|
||||||
sum(1 for r in rows if r[6] is not None), summary_id,
|
sum(1 for r in rows if r[6] is not None),
|
||||||
|
sum(1 for r in rows if r[8] is not None), summary_id,
|
||||||
)
|
)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
logger.error("Error persisting article_scores (run continues): %s", exc)
|
logger.error("Error persisting article_scores (run continues): %s", exc)
|
||||||
|
|
@ -715,10 +753,15 @@ def summarize_news() -> None:
|
||||||
blocks, stats = parse_map_scores(
|
blocks, stats = parse_map_scores(
|
||||||
response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE
|
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(
|
logger.info(
|
||||||
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d)",
|
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d, geo=%d)",
|
||||||
batch_index + 1, stats["graded"], len(batch),
|
batch_index + 1, stats["graded"], len(batch),
|
||||||
stats["fallback"], stats["unattributed"],
|
stats["fallback"], stats["unattributed"],
|
||||||
|
sum(1 for b in blocks if b.get("lat") is not None),
|
||||||
)
|
)
|
||||||
graded.extend(blocks)
|
graded.extend(blocks)
|
||||||
|
|
||||||
|
|
@ -786,12 +829,18 @@ 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 = [
|
||||||
|
block["article"]
|
||||||
|
for block in selected
|
||||||
|
if isinstance(block.get("article"), dict)
|
||||||
|
]
|
||||||
summary_id = save_batch(
|
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)
|
persist_article_scores(distinct + duplicate_blocks, summary_id=summary_id, model=model)
|
||||||
|
|
||||||
|
|
|
||||||
214
news/summerizer/tests/test_article_url.py
Normal file
214
news/summerizer/tests/test_article_url.py
Normal file
|
|
@ -0,0 +1,214 @@
|
||||||
|
"""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",
|
||||||
|
"",
|
||||||
|
]
|
||||||
405
news/summerizer/tests/test_geo.py
Normal file
405
news/summerizer/tests/test_geo.py
Normal file
|
|
@ -0,0 +1,405 @@
|
||||||
|
"""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
|
||||||
62
tests/test_adsb_watch.py
Normal file
62
tests/test_adsb_watch.py
Normal file
|
|
@ -0,0 +1,62 @@
|
||||||
|
"""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()
|
||||||
|
}
|
||||||
|
|
@ -176,6 +176,50 @@ def test_api_news_excludes_future_dated_rows(clean_news):
|
||||||
assert [a["title"] for a in limited] == ["recent", "recent2"]
|
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):
|
||||||
|
|
|
||||||
337
tests/test_api_news_blips.py
Normal file
337
tests/test_api_news_blips.py
Normal file
|
|
@ -0,0 +1,337 @@
|
||||||
|
"""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
|
||||||
|
|
@ -8,7 +8,7 @@ from datetime import timezone
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from main import app, _stats_counts
|
from main import app, _stats_counts, _stats_cache
|
||||||
|
|
||||||
BASE = "http://test"
|
BASE = "http://test"
|
||||||
|
|
||||||
|
|
@ -85,3 +85,79 @@ def test_stats_db_failure_degrades_to_zero(monkeypatch):
|
||||||
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
|
||||||
|
|
@ -144,6 +144,7 @@ def test_anonymous_can_read_public_allowlist(no_db):
|
||||||
"/api/news",
|
"/api/news",
|
||||||
"/api/news/ticker",
|
"/api/news/ticker",
|
||||||
"/api/news/map",
|
"/api/news/map",
|
||||||
|
"/api/news/blips",
|
||||||
"/api/geofences",
|
"/api/geofences",
|
||||||
"/api/geofence-alerts",
|
"/api/geofence-alerts",
|
||||||
"/api/analytics/summary",
|
"/api/analytics/summary",
|
||||||
|
|
@ -168,6 +169,7 @@ SPEC_PUBLIC_READS = (
|
||||||
"/api/analytics/summary", "/api/analytics/timeline",
|
"/api/analytics/summary", "/api/analytics/timeline",
|
||||||
"/api/analytics/sentiment/by-source", "/api/cameras",
|
"/api/analytics/sentiment/by-source", "/api/cameras",
|
||||||
"/api/news", "/api/news/summaries", "/api/news/ticker", "/api/news/map",
|
"/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/layers", "/api/map/chokepoints", "/api/map/radar",
|
||||||
"/api/map/sentinel1", "/api/aircraft", "/api/aircraft/photo",
|
"/api/map/sentinel1", "/api/aircraft", "/api/aircraft/photo",
|
||||||
"/api/trains", "/api/vessels", "/api/tracks/range", "/api/geofences",
|
"/api/trains", "/api/vessels", "/api/tracks/range", "/api/geofences",
|
||||||
|
|
|
||||||
199
tests/test_gdelt_backoff.py
Normal file
199
tests/test_gdelt_backoff.py
Normal file
|
|
@ -0,0 +1,199 @@
|
||||||
|
"""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
|
||||||
274
tests/test_gdelt_bulk.py
Normal file
274
tests/test_gdelt_bulk.py
Normal file
|
|
@ -0,0 +1,274 @@
|
||||||
|
"""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
|
||||||
|
|
@ -361,3 +361,484 @@ def test_snapshot_queries_st_intersects(monkeypatch):
|
||||||
assert "aircraft_tracks_1min" in blob
|
assert "aircraft_tracks_1min" in blob
|
||||||
assert "vessel_tracks_1min" in blob
|
assert "vessel_tracks_1min" in blob
|
||||||
assert "from fires" 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
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,9 @@
|
||||||
|
|
||||||
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
|
||||||
|
|
@ -54,3 +57,151 @@ def test_fence_dvr_at_endpoint():
|
||||||
assert "/at?timestamp=" in HTML or "/at?timestamp=${" in HTML
|
assert "/at?timestamp=" in HTML or "/at?timestamp=${" in HTML
|
||||||
assert "function dvrScrubFence" in HTML
|
assert "function dvrScrubFence" in HTML
|
||||||
assert "gfSelectedId" 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,12 +3,21 @@
|
||||||
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:
|
||||||
|
|
@ -31,3 +40,67 @@ 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
|
||||||
|
|
|
||||||
|
|
@ -133,3 +133,51 @@ def test_pipeline_keeps_unparseable_timestamp():
|
||||||
assert is_future_dated("not a date") is False
|
assert is_future_dated("not a date") is False
|
||||||
assert is_future_dated(None) 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
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -67,7 +67,43 @@ def test_geofence_alerts_passes_filters(monkeypatch):
|
||||||
assert seen["until"] is not None
|
assert seen["until"] is not None
|
||||||
|
|
||||||
|
|
||||||
def test_geofence_alerts_rejects_bad_source_kind():
|
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(
|
resp = asyncio.run(_req(
|
||||||
"GET", "/api/geofence-alerts", params={"source_kind": "camera"},
|
"GET", "/api/geofence-alerts", params={"source_kind": "camera"},
|
||||||
))
|
))
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue