Merge pull request 'fix(gdelt): ingest the 15-minute GKG bulk file' (#70) from fix/gdelt-bulk-gkg into master
All checks were successful
build-and-deploy / build-push (push) Successful in 21s

This commit is contained in:
sirius 2026-11-21 23:37:46 +00:00
commit 76035535bc
3 changed files with 516 additions and 1 deletions

View file

@ -2,10 +2,14 @@
from __future__ import annotations from __future__ import annotations
import html
import io
import json import json
import logging import logging
import os import os
import re
import time import time
import zipfile
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from email.utils import parsedate_to_datetime from email.utils import parsedate_to_datetime
@ -232,7 +236,7 @@ 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 GDELT enforces a per-IP quota that answers ``429`` with a plain-text body
@ -292,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:

View file

@ -21,6 +21,9 @@ def _reset_backoff(monkeypatch):
sources._gdelt_clear_backoff() sources._gdelt_clear_backoff()
monkeypatch.setattr(sources, "GDELT_BACKOFF_BASE", 300) monkeypatch.setattr(sources, "GDELT_BACKOFF_BASE", 300)
monkeypatch.setattr(sources, "GDELT_BACKOFF_MAX", 1800) 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 yield
sources._gdelt_clear_backoff() sources._gdelt_clear_backoff()

274
tests/test_gdelt_bulk.py Normal file
View 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 &amp; 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