fix(ingest): skip known KEV/FIRMS rows; CI skips unchanged images
CISA KEV republished 1685 NIST URLs every 5 min; FIRMS re-inserted ~325k global hotspots every 15 min. Producer now skips URLs already in event_dedup and FIRMS CSVs that are unchanged (delta-only persist). CI rebuilds only images whose paths changed and never pulls/rebuilds Timescale or bounces osint-db unless Dockerfile.pg changes.
This commit is contained in:
parent
0406eb6b7b
commit
5651d251d0
9 changed files with 438 additions and 94 deletions
|
|
@ -22,6 +22,7 @@ UTC date (YYYY-MM-DD).
|
|||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
|
|
@ -44,6 +45,11 @@ from upstream_cache import firms_cache
|
|||
|
||||
logger = logging.getLogger("osint.firms")
|
||||
|
||||
# In-process poll state: skip byte-identical CSVs, persist only new hotspots.
|
||||
# Survives the 15-minute loop; one full ON CONFLICT after process start.
|
||||
_csv_digest: dict[tuple, bytes] = {}
|
||||
_seen_ids: dict[tuple, set[int]] = {}
|
||||
|
||||
# ── FIRMS API ─────────────────────────────────────────────────────────────
|
||||
|
||||
FIRMS_AREA_CSV = (
|
||||
|
|
@ -86,33 +92,34 @@ def normalize_acq_time(acq_date: object, acq_time: object) -> datetime | None:
|
|||
return None
|
||||
|
||||
|
||||
def parse_firms_csv(text: str) -> list[dict]:
|
||||
"""Parse a FIRMS area CSV payload into normalized fire messages.
|
||||
def _hotspot_id(lat: float, lon: float, acq_iso: str, satellite: str) -> int:
|
||||
return hash((round(lat, 5), round(lon, 5), acq_iso, satellite))
|
||||
|
||||
Returns one dict per hotspot with the fields stored in the ``fires`` table
|
||||
(acq_time already combined into a UTC ISO timestamp). Rows that don't look
|
||||
like valid VIIRS detections are skipped rather than failing the whole poll.
|
||||
|
||||
def parse_firms_csv_delta(
|
||||
text: str, skip_ids: set[int] | None = None,
|
||||
) -> tuple[list[dict], set[int]]:
|
||||
"""Parse FIRMS CSV; optionally drop hotspots already seen this process.
|
||||
|
||||
Returns (new_or_all_points, ids_for_every_valid_row). Streaming — does not
|
||||
materialize the raw CSV as a list of lists.
|
||||
"""
|
||||
rows = list(csv.reader(io.StringIO(text)))
|
||||
if not rows:
|
||||
return []
|
||||
|
||||
# Locate the real header row. FIRMS normally returns the CSV header first,
|
||||
# but occasionally prepends a legend/info line, so scan until we see the
|
||||
# canonical header.
|
||||
header_idx = 0
|
||||
for i, row in enumerate(rows):
|
||||
reader = csv.reader(io.StringIO(text))
|
||||
header = None
|
||||
for row in reader:
|
||||
if row and row[0].strip().lower() == "latitude" and len(row) >= 4:
|
||||
header_idx = i
|
||||
header = [c.strip().lower() for c in row]
|
||||
break
|
||||
header = [c.strip().lower() for c in rows[header_idx]]
|
||||
# Guard against a header that isn't actually the FIRMS one.
|
||||
if "latitude" not in header or "longitude" not in header:
|
||||
logger.warning("FIRMS payload does not look like a hotspot CSV (first row: %r)", header[:6])
|
||||
return []
|
||||
if not header or "latitude" not in header or "longitude" not in header:
|
||||
logger.warning(
|
||||
"FIRMS payload does not look like a hotspot CSV (first row: %r)",
|
||||
(header or [])[:6],
|
||||
)
|
||||
return [], set()
|
||||
|
||||
points: list[dict] = []
|
||||
for row in rows[header_idx + 1:]:
|
||||
ids: set[int] = set()
|
||||
for row in reader:
|
||||
if len(row) < len(header):
|
||||
continue
|
||||
rec = dict(zip(header, row))
|
||||
|
|
@ -123,13 +130,19 @@ def parse_firms_csv(text: str) -> list[dict]:
|
|||
acq_time = normalize_acq_time(rec.get("acq_date"), rec.get("acq_time"))
|
||||
if acq_time is None:
|
||||
continue
|
||||
sat = str(rec.get("satellite") or "").strip()
|
||||
acq_iso = acq_time.isoformat()
|
||||
hid = _hotspot_id(lat, lon, acq_iso, sat)
|
||||
ids.add(hid)
|
||||
if skip_ids is not None and hid in skip_ids:
|
||||
continue
|
||||
points.append({
|
||||
"latitude": lat,
|
||||
"longitude": lon,
|
||||
"brightness": _to_float(rec.get("bright_ti4")),
|
||||
"confidence": str(rec.get("confidence") or "").strip(),
|
||||
"acq_time": acq_time.isoformat(),
|
||||
"satellite": str(rec.get("satellite") or "").strip(),
|
||||
"acq_time": acq_iso,
|
||||
"satellite": sat,
|
||||
"instrument": str(rec.get("instrument") or "").strip(),
|
||||
"bright_ti5": _to_float(rec.get("bright_ti5")),
|
||||
"frp": _to_float(rec.get("frp")),
|
||||
|
|
@ -138,6 +151,17 @@ def parse_firms_csv(text: str) -> list[dict]:
|
|||
"track": _to_float(rec.get("track")),
|
||||
"version": str(rec.get("version") or "").strip(),
|
||||
})
|
||||
return points, ids
|
||||
|
||||
|
||||
def parse_firms_csv(text: str) -> list[dict]:
|
||||
"""Parse a FIRMS area CSV payload into normalized fire messages.
|
||||
|
||||
Returns one dict per hotspot with the fields stored in the ``fires`` table
|
||||
(acq_time already combined into a UTC ISO timestamp). Rows that don't look
|
||||
like valid VIIRS detections are skipped rather than failing the whole poll.
|
||||
"""
|
||||
points, _ids = parse_firms_csv_delta(text)
|
||||
return points
|
||||
|
||||
|
||||
|
|
@ -215,11 +239,18 @@ async def ingest_fires(bbox: str | None = None) -> int:
|
|||
dataset, first_line,
|
||||
)
|
||||
continue
|
||||
points = parse_firms_csv(text)
|
||||
published = await persist_hotspots(points)
|
||||
poll_key = (dataset, area, FIRMS_DAYS)
|
||||
digest = hashlib.sha256(text.encode("utf-8", "surrogatepass")).digest()
|
||||
if _csv_digest.get(poll_key) == digest:
|
||||
logger.info("FIRMS %s CSV unchanged, skip parse/insert", dataset)
|
||||
continue
|
||||
points, ids = parse_firms_csv_delta(text, skip_ids=_seen_ids.get(poll_key))
|
||||
published = await persist_hotspots(points) if points else 0
|
||||
_csv_digest[poll_key] = digest
|
||||
_seen_ids[poll_key] = ids
|
||||
total_published += published
|
||||
logger.info(
|
||||
"FIRMS: fetched %d hotspot(s) for bbox=%s (%s), published %d",
|
||||
len(points), area, dataset, published,
|
||||
len(ids), area, dataset, published,
|
||||
)
|
||||
return total_published
|
||||
|
|
|
|||
|
|
@ -213,7 +213,7 @@ async def ingest_event(msg: dict):
|
|||
claimed = await session.execute(dedup)
|
||||
if not claimed.rowcount:
|
||||
await session.commit()
|
||||
logger.info("skip duplicate event url=%s", key)
|
||||
logger.debug("skip duplicate event url=%s", key)
|
||||
return None
|
||||
result = await session.execute(events_table.insert().values(**event_row))
|
||||
await session.commit()
|
||||
|
|
|
|||
|
|
@ -55,6 +55,35 @@ def event_dedup_key(msg: dict) -> str | None:
|
|||
return url or None
|
||||
|
||||
|
||||
async def existing_event_urls(urls: list[str]) -> set[str]:
|
||||
"""URLs already claimed in event_dedup. Empty input -> empty set."""
|
||||
if not urls:
|
||||
return set()
|
||||
from sqlalchemy import select
|
||||
|
||||
from database import async_session
|
||||
from models import event_dedup as event_dedup_table
|
||||
|
||||
async with async_session() as session:
|
||||
result = await session.execute(
|
||||
select(event_dedup_table.c.url).where(event_dedup_table.c.url.in_(urls))
|
||||
)
|
||||
return {row[0] for row in result}
|
||||
|
||||
|
||||
async def _publish_unknown(subject: str, events: list[dict]) -> int:
|
||||
"""Publish only events whose URL is not already in event_dedup."""
|
||||
keys = [event_dedup_key(e) for e in events]
|
||||
known = await existing_event_urls([k for k in keys if k])
|
||||
published = 0
|
||||
for event, key in zip(events, keys):
|
||||
if key and key in known:
|
||||
continue
|
||||
await publish_event(subject, event)
|
||||
published += 1
|
||||
return published
|
||||
|
||||
|
||||
def _ua_headers() -> dict[str, str]:
|
||||
return {"User-Agent": OSINT_USER_AGENT}
|
||||
|
||||
|
|
@ -283,10 +312,9 @@ async def ingest_eonet():
|
|||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
events = parse_eonet_events(data if isinstance(data, dict) else {})
|
||||
for event in events:
|
||||
await publish_event("events.disaster", event)
|
||||
logger.info("Ingested %d EONET events", len(events))
|
||||
return len(events)
|
||||
published = await _publish_unknown("events.disaster", events)
|
||||
logger.info("Ingested %d EONET events (%d already known)", published, len(events) - published)
|
||||
return published
|
||||
|
||||
|
||||
# ─── CISA KEV ───────────────────────────────────────────────────────────
|
||||
|
|
@ -330,10 +358,9 @@ async def ingest_cisa_kev():
|
|||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
events = parse_cisa_kev(data if isinstance(data, dict) else {})
|
||||
for event in events:
|
||||
await publish_event("events.disaster", event)
|
||||
logger.info("Ingested %d CISA KEV rows", len(events))
|
||||
return len(events)
|
||||
published = await _publish_unknown("events.disaster", events)
|
||||
logger.info("Ingested %d CISA KEV rows (%d already known)", published, len(events) - published)
|
||||
return published
|
||||
|
||||
|
||||
# ─── Social Signals (Twitter/X-like placeholder) ────────────────────────
|
||||
|
|
|
|||
Loading…
Reference in a new issue