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
|
||||
|
|
|
|||
Loading…
Reference in a new issue