views-datafactory 1.9.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- datafactory_adapters/ARCHITECTURE.md +54 -0
- datafactory_adapters/__init__.py +38 -0
- datafactory_adapters/_conservation.py +95 -0
- datafactory_adapters/_reconciliation.py +92 -0
- datafactory_adapters/_validation.py +39 -0
- datafactory_adapters/feature_frame.py +25 -0
- datafactory_adapters/grid_from_feature_frame.py +89 -0
- datafactory_adapters/grid_to_country_month.py +169 -0
- datafactory_adapters/grid_to_dataframe.py +176 -0
- datafactory_compilation/ARCHITECTURE.md +63 -0
- datafactory_compilation/__init__.py +39 -0
- datafactory_compilation/aggregation.py +64 -0
- datafactory_compilation/compilation_config.py +97 -0
- datafactory_compilation/conservation.py +36 -0
- datafactory_compilation/grid_compilation.py +352 -0
- datafactory_compilation/output.py +85 -0
- datafactory_compilation/preflight.py +61 -0
- datafactory_compilation/pregridded_compilation.py +291 -0
- datafactory_consolidation/ARCHITECTURE.md +58 -0
- datafactory_consolidation/__init__.py +28 -0
- datafactory_consolidation/consolidation_result.py +27 -0
- datafactory_consolidation/consolidators/__init__.py +32 -0
- datafactory_consolidation/consolidators/acled.py +462 -0
- datafactory_consolidation/consolidators/ucdp.py +524 -0
- datafactory_consolidation/event_store.py +67 -0
- datafactory_consolidation/tagging.py +46 -0
- datafactory_harvester/ARCHITECTURE.md +103 -0
- datafactory_harvester/__init__.py +37 -0
- datafactory_harvester/event_validation.py +372 -0
- datafactory_harvester/harvest_runner.py +72 -0
- datafactory_harvester/pipeline_runner.py +125 -0
- datafactory_harvester/snapshot_storage.py +117 -0
- datafactory_harvester/sources/__init__.py +36 -0
- datafactory_harvester/sources/_ucdp_common.py +34 -0
- datafactory_harvester/sources/acled.py +743 -0
- datafactory_harvester/sources/gaul_admin.py +567 -0
- datafactory_harvester/sources/ghsbuilts.py +271 -0
- datafactory_harvester/sources/ghspop.py +267 -0
- datafactory_harvester/sources/priogrid_static.py +359 -0
- datafactory_harvester/sources/shdi.py +625 -0
- datafactory_harvester/sources/ucdp_annual.py +616 -0
- datafactory_harvester/sources/ucdp_candidate.py +419 -0
- datafactory_harvester/sources/ucdp_dot9.py +407 -0
- datafactory_harvester/sources/vdem.py +350 -0
- datafactory_harvester/validation.py +74 -0
- datafactory_http/__init__.py +10 -0
- datafactory_http/retry.py +102 -0
- datafactory_priogrid/ARCHITECTURE.md +62 -0
- datafactory_priogrid/__init__.py +51 -0
- datafactory_priogrid/cell_generator.py +137 -0
- datafactory_priogrid/grid_config.py +107 -0
- datafactory_priogrid/land_mask.py +62 -0
- datafactory_priogrid/parity_validation.py +176 -0
- datafactory_priogrid/shapefile_harvester.py +174 -0
- datafactory_priogrid/shapefile_reader.py +125 -0
- datafactory_priogrid/spatiotemporal.py +66 -0
- datafactory_priogrid/temporal_config.py +78 -0
- datafactory_priogrid/temporal_generator.py +65 -0
- datafactory_provenance/ARCHITECTURE.md +61 -0
- datafactory_provenance/__init__.py +81 -0
- datafactory_provenance/constants.py +3 -0
- datafactory_provenance/digests_and_ledgers.py +370 -0
- datafactory_provenance/health.py +310 -0
- datafactory_provenance/pipeline_lock.py +200 -0
- datafactory_provenance/registry.py +92 -0
- datafactory_provenance/skip.py +212 -0
- datafactory_provenance/source_registry.py +466 -0
- datafactory_query/ARCHITECTURE.md +60 -0
- datafactory_query/__init__.py +36 -0
- datafactory_query/africa_me_gaul_pgids.json +1 -0
- datafactory_query/africa_me_legacy_pgids.json +1 -0
- datafactory_query/backends_npy.py +90 -0
- datafactory_query/backends_zarr.py +259 -0
- datafactory_query/coverage.py +64 -0
- datafactory_query/dataset.py +263 -0
- datafactory_query/defaults.py +101 -0
- datafactory_query/land_gaul_pgids.json +1 -0
- datafactory_query/land_pgids.json +1 -0
- datafactory_query/output_format.py +52 -0
- datafactory_query/regions.py +293 -0
- datafactory_query/temporal.py +115 -0
- datafactory_viewpoint/ARCHITECTURE.md +68 -0
- datafactory_viewpoint/__init__.py +33 -0
- datafactory_viewpoint/builders/__init__.py +32 -0
- datafactory_viewpoint/builders/acled_v1.py +213 -0
- datafactory_viewpoint/builders/ghsbuilts_v1.py +351 -0
- datafactory_viewpoint/builders/ghspop_v1.py +471 -0
- datafactory_viewpoint/builders/shdi_v1.py +389 -0
- datafactory_viewpoint/builders/ucdp_v1.py +437 -0
- datafactory_viewpoint/builders/vdem_v1.py +419 -0
- datafactory_viewpoint/profiles.py +169 -0
- datafactory_viewpoint/raster_io.py +49 -0
- datafactory_viewpoint/spatial_distribution.py +203 -0
- datafactory_viewpoint/spatial_weights.py +207 -0
- datafactory_viewpoint/survivorship.py +108 -0
- datafactory_viewpoint/temporal.py +111 -0
- datafactory_viewpoint/temporal_distribution.py +295 -0
- datafactory_viewpoint/viewpoint_config.py +124 -0
- datafactory_viewpoint/viewpoint_result.py +33 -0
- views_datafactory-1.9.0.dist-info/METADATA +528 -0
- views_datafactory-1.9.0.dist-info/RECORD +103 -0
- views_datafactory-1.9.0.dist-info/WHEEL +4 -0
- views_datafactory-1.9.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,743 @@
|
|
|
1
|
+
"""ACLED (Armed Conflict Location & Event Data) source.
|
|
2
|
+
|
|
3
|
+
Fetches event-level conflict and protest data from the ACLED API.
|
|
4
|
+
API docs: https://apidocs.acleddata.com/
|
|
5
|
+
|
|
6
|
+
Authentication: OAuth2 password grant (ADR-026). Each user must
|
|
7
|
+
authenticate with their own credentials — credential sharing is
|
|
8
|
+
prohibited by ACLED's EULA.
|
|
9
|
+
|
|
10
|
+
Source-specific concerns: OAuth token lifecycle, event type taxonomy,
|
|
11
|
+
daily granularity, pagination via page parameter. Uses the shared
|
|
12
|
+
harvester skeleton (validation, storage, provenance).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import datetime
|
|
18
|
+
import json
|
|
19
|
+
import logging
|
|
20
|
+
import os
|
|
21
|
+
import time
|
|
22
|
+
from collections.abc import Callable
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
import pyarrow as pa
|
|
27
|
+
import pyarrow.parquet as pq
|
|
28
|
+
import requests
|
|
29
|
+
|
|
30
|
+
from datafactory_harvester.event_validation import (
|
|
31
|
+
ComparisonResult,
|
|
32
|
+
compare_snapshots,
|
|
33
|
+
date_range,
|
|
34
|
+
validate_dgp_assumptions,
|
|
35
|
+
validate_events,
|
|
36
|
+
)
|
|
37
|
+
from datafactory_harvester.snapshot_storage import (
|
|
38
|
+
archive_snapshot,
|
|
39
|
+
save_event_snapshot,
|
|
40
|
+
)
|
|
41
|
+
from datafactory_harvester.sources import register_source
|
|
42
|
+
from datafactory_harvester.validation import (
|
|
43
|
+
validate_positive_float,
|
|
44
|
+
validate_positive_int,
|
|
45
|
+
validate_year_range,
|
|
46
|
+
)
|
|
47
|
+
from datafactory_http import request_with_retry
|
|
48
|
+
from datafactory_provenance import (
|
|
49
|
+
DIGEST_SCHEME,
|
|
50
|
+
LEDGER_VERSION,
|
|
51
|
+
append_ledger_entry,
|
|
52
|
+
compute_content_digest,
|
|
53
|
+
last_digest_for_version,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
logger = logging.getLogger(__name__)
|
|
57
|
+
|
|
58
|
+
DATASET_ID = "acled"
|
|
59
|
+
_LOG_EVERY_N_PAGES: int = 10
|
|
60
|
+
_FETCH_DURATION_PRECISION: int = 1
|
|
61
|
+
_TOKEN_REFRESH_MARGIN_S: float = 300.0 # Refresh 5 min before expiry
|
|
62
|
+
|
|
63
|
+
ACLED_API_BASE = "https://acleddata.com/api/acled/read"
|
|
64
|
+
ACLED_TOKEN_URL = "https://acleddata.com/oauth/token"
|
|
65
|
+
|
|
66
|
+
ALL_EVENT_TYPES: tuple[str, ...] = (
|
|
67
|
+
"Battles",
|
|
68
|
+
"Explosions/Remote violence",
|
|
69
|
+
"Violence against civilians",
|
|
70
|
+
"Protests",
|
|
71
|
+
"Riots",
|
|
72
|
+
"Strategic developments",
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
# ---- ACLED schema definition (preliminary, from documentation) ----
|
|
76
|
+
|
|
77
|
+
REQUIRED_FIELDS: set[str] = {
|
|
78
|
+
"event_id_cnty",
|
|
79
|
+
"event_date",
|
|
80
|
+
"event_type",
|
|
81
|
+
"sub_event_type",
|
|
82
|
+
"actor1",
|
|
83
|
+
"country",
|
|
84
|
+
"latitude",
|
|
85
|
+
"longitude",
|
|
86
|
+
"fatalities",
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
# Preliminary types from ACLED docs — tighten after Phase 2 API investigation.
|
|
90
|
+
FIELD_TYPES: dict[str, tuple[type, ...]] = {
|
|
91
|
+
"event_id_cnty": (str,),
|
|
92
|
+
"event_date": (str,),
|
|
93
|
+
"event_type": (str,),
|
|
94
|
+
"sub_event_type": (str,),
|
|
95
|
+
"actor1": (str,),
|
|
96
|
+
"actor2": (str,),
|
|
97
|
+
"country": (str,),
|
|
98
|
+
"admin1": (str,),
|
|
99
|
+
"latitude": (str, float, int),
|
|
100
|
+
"longitude": (str, float, int),
|
|
101
|
+
"fatalities": (int, float, str),
|
|
102
|
+
"notes": (str,),
|
|
103
|
+
"source": (str,),
|
|
104
|
+
"source_scale": (str,),
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
# ---- DGP assumption checks (C-257) ----
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _check_fatality_non_negative(event: dict) -> str | None:
|
|
111
|
+
"""Fatalities must be >= 0."""
|
|
112
|
+
val = event.get("fatalities")
|
|
113
|
+
if val is not None:
|
|
114
|
+
try:
|
|
115
|
+
if float(val) < 0:
|
|
116
|
+
return f"Negative fatalities: {val}"
|
|
117
|
+
except (TypeError, ValueError):
|
|
118
|
+
pass
|
|
119
|
+
return None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _check_known_event_type(event: dict) -> str | None:
|
|
123
|
+
"""Event type must be in ALL_EVENT_TYPES."""
|
|
124
|
+
et = event.get("event_type")
|
|
125
|
+
if et is not None and et not in ALL_EVENT_TYPES:
|
|
126
|
+
return f"Unknown event_type: {et!r}"
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _check_coordinate_bounds(event: dict) -> str | None:
|
|
131
|
+
"""Latitude in [-90,90], longitude in [-180,180]."""
|
|
132
|
+
for field, lo, hi in (
|
|
133
|
+
("latitude", -90, 90),
|
|
134
|
+
("longitude", -180, 180),
|
|
135
|
+
):
|
|
136
|
+
val = event.get(field)
|
|
137
|
+
if val is not None:
|
|
138
|
+
try:
|
|
139
|
+
fval = float(val)
|
|
140
|
+
if not (lo <= fval <= hi):
|
|
141
|
+
return f"{field}={fval} outside [{lo},{hi}]"
|
|
142
|
+
except (TypeError, ValueError):
|
|
143
|
+
pass
|
|
144
|
+
return None
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
ACLED_DGP_CHECKS: tuple[
|
|
148
|
+
Callable[[dict], str | None], ...
|
|
149
|
+
] = (
|
|
150
|
+
_check_fatality_non_negative,
|
|
151
|
+
_check_known_event_type,
|
|
152
|
+
_check_coordinate_bounds,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
# ---- Config ----
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass(frozen=True)
|
|
160
|
+
class AcledConfig:
|
|
161
|
+
"""Configuration for fetching ACLED event data."""
|
|
162
|
+
|
|
163
|
+
start_year: int = 1997
|
|
164
|
+
end_year: int = 0
|
|
165
|
+
|
|
166
|
+
event_types: tuple[str, ...] = ALL_EVENT_TYPES
|
|
167
|
+
|
|
168
|
+
# API transport
|
|
169
|
+
api_url: str = ACLED_API_BASE
|
|
170
|
+
token_url: str = ACLED_TOKEN_URL
|
|
171
|
+
page_size: int = 5000
|
|
172
|
+
timeout: int = 60
|
|
173
|
+
max_retries: int = 3
|
|
174
|
+
page_delay: float = 2.0
|
|
175
|
+
|
|
176
|
+
# Storage
|
|
177
|
+
data_dir: Path = Path("data/raw/acled")
|
|
178
|
+
ledger_path: Path = Path("provenance/acled/ingestion_ledger.jsonl")
|
|
179
|
+
|
|
180
|
+
def __post_init__(self) -> None:
|
|
181
|
+
if self.end_year == 0:
|
|
182
|
+
object.__setattr__(
|
|
183
|
+
self, "end_year",
|
|
184
|
+
datetime.datetime.now(tz=datetime.UTC).year,
|
|
185
|
+
)
|
|
186
|
+
validate_year_range(self.start_year, self.end_year)
|
|
187
|
+
validate_positive_int(self.page_size, "page_size")
|
|
188
|
+
validate_positive_int(self.max_retries, "max_retries")
|
|
189
|
+
validate_positive_float(self.page_delay, "page_delay")
|
|
190
|
+
validate_positive_int(self.timeout, "timeout")
|
|
191
|
+
for et in self.event_types:
|
|
192
|
+
if et not in ALL_EVENT_TYPES:
|
|
193
|
+
msg = (
|
|
194
|
+
f"Unknown event type '{et}'. "
|
|
195
|
+
f"Valid: {ALL_EVENT_TYPES}"
|
|
196
|
+
)
|
|
197
|
+
raise ValueError(msg)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# ---- Credential resolution (ADR-026) ----
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def get_acled_credentials(
|
|
204
|
+
username: str | None = None,
|
|
205
|
+
password: str | None = None,
|
|
206
|
+
) -> tuple[str, str]:
|
|
207
|
+
"""Resolve ACLED credentials from arguments or environment.
|
|
208
|
+
|
|
209
|
+
Resolution order (per ADR-026):
|
|
210
|
+
1. Function arguments (highest priority)
|
|
211
|
+
2. Environment variables ACLED_USERNAME / ACLED_PASSWORD
|
|
212
|
+
3. Fail-loud with actionable error message
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
(username, password) tuple.
|
|
216
|
+
|
|
217
|
+
Raises:
|
|
218
|
+
ValueError: If credentials cannot be resolved.
|
|
219
|
+
"""
|
|
220
|
+
resolved_user = username or os.environ.get("ACLED_USERNAME")
|
|
221
|
+
resolved_pass = password or os.environ.get("ACLED_PASSWORD")
|
|
222
|
+
|
|
223
|
+
missing = []
|
|
224
|
+
if not resolved_user:
|
|
225
|
+
missing.append("ACLED_USERNAME")
|
|
226
|
+
if not resolved_pass:
|
|
227
|
+
missing.append("ACLED_PASSWORD")
|
|
228
|
+
|
|
229
|
+
if missing:
|
|
230
|
+
err_msg = (
|
|
231
|
+
f"ACLED credentials required. Set {' and '.join(missing)} "
|
|
232
|
+
"environment variable(s) or pass username=/password= to "
|
|
233
|
+
"fetch_acled()."
|
|
234
|
+
)
|
|
235
|
+
logger.error(err_msg)
|
|
236
|
+
raise ValueError(err_msg)
|
|
237
|
+
|
|
238
|
+
return resolved_user, resolved_pass # type: ignore[return-value]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# ---- OAuth2 token management ----
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@dataclass
|
|
245
|
+
class _TokenState:
|
|
246
|
+
"""Mutable token state — NOT in frozen config (ADR-026)."""
|
|
247
|
+
|
|
248
|
+
access_token: str = ""
|
|
249
|
+
expires_at: float = 0.0
|
|
250
|
+
|
|
251
|
+
@property
|
|
252
|
+
def is_valid(self) -> bool:
|
|
253
|
+
return (
|
|
254
|
+
bool(self.access_token)
|
|
255
|
+
and time.monotonic() < self.expires_at - _TOKEN_REFRESH_MARGIN_S
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _acquire_token(
|
|
260
|
+
username: str,
|
|
261
|
+
password: str,
|
|
262
|
+
token_url: str = ACLED_TOKEN_URL,
|
|
263
|
+
timeout: int = 30,
|
|
264
|
+
max_retries: int = 3,
|
|
265
|
+
) -> _TokenState:
|
|
266
|
+
"""Acquire a new OAuth2 bearer token from ACLED."""
|
|
267
|
+
response = request_with_retry(
|
|
268
|
+
token_url,
|
|
269
|
+
method="POST",
|
|
270
|
+
data={
|
|
271
|
+
"client_id": "acled",
|
|
272
|
+
"username": username,
|
|
273
|
+
"password": password,
|
|
274
|
+
"grant_type": "password",
|
|
275
|
+
},
|
|
276
|
+
max_retries=max_retries,
|
|
277
|
+
timeout=timeout,
|
|
278
|
+
)
|
|
279
|
+
token_data = response.json()
|
|
280
|
+
|
|
281
|
+
access_token = token_data.get("access_token")
|
|
282
|
+
if not access_token:
|
|
283
|
+
err_msg = (
|
|
284
|
+
"ACLED token response missing 'access_token'. "
|
|
285
|
+
f"Response keys: {sorted(token_data.keys())}"
|
|
286
|
+
)
|
|
287
|
+
logger.error(err_msg)
|
|
288
|
+
raise ValueError(err_msg)
|
|
289
|
+
|
|
290
|
+
expires_in = int(token_data.get("expires_in", 86400))
|
|
291
|
+
expires_at = time.monotonic() + expires_in
|
|
292
|
+
|
|
293
|
+
logger.info(
|
|
294
|
+
"ACLED token acquired (expires in %ds)", expires_in
|
|
295
|
+
)
|
|
296
|
+
return _TokenState(
|
|
297
|
+
access_token=access_token, expires_at=expires_at
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _ensure_token(
|
|
302
|
+
state: _TokenState,
|
|
303
|
+
username: str,
|
|
304
|
+
password: str,
|
|
305
|
+
token_url: str = ACLED_TOKEN_URL,
|
|
306
|
+
timeout: int = 30,
|
|
307
|
+
max_retries: int = 3,
|
|
308
|
+
) -> _TokenState:
|
|
309
|
+
"""Return a valid token, refreshing if near expiry."""
|
|
310
|
+
if state.is_valid:
|
|
311
|
+
return state
|
|
312
|
+
logger.info("ACLED token expired or near expiry, refreshing")
|
|
313
|
+
return _acquire_token(
|
|
314
|
+
username, password, token_url, timeout, max_retries
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
# ---- API client ----
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _authenticated_request(
|
|
322
|
+
url: str,
|
|
323
|
+
params: dict,
|
|
324
|
+
state: _TokenState,
|
|
325
|
+
username: str,
|
|
326
|
+
password: str,
|
|
327
|
+
token_url: str,
|
|
328
|
+
timeout: int,
|
|
329
|
+
max_retries: int,
|
|
330
|
+
) -> tuple[requests.Response, _TokenState]:
|
|
331
|
+
"""Make an authenticated request, recovering from 401.
|
|
332
|
+
|
|
333
|
+
Handles the full OAuth2 token lifecycle:
|
|
334
|
+
1. Proactive refresh if local clock says token is near expiry
|
|
335
|
+
2. Reactive recovery if the server returns 401
|
|
336
|
+
|
|
337
|
+
Returns the response and the (possibly refreshed) token state.
|
|
338
|
+
Credentials are passed as arguments, never stored (ADR-026).
|
|
339
|
+
"""
|
|
340
|
+
state = _ensure_token(
|
|
341
|
+
state, username, password,
|
|
342
|
+
token_url, timeout, max_retries,
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
def _do_request(s: _TokenState) -> requests.Response:
|
|
346
|
+
return request_with_retry(
|
|
347
|
+
url,
|
|
348
|
+
headers={
|
|
349
|
+
"Authorization": f"Bearer {s.access_token}",
|
|
350
|
+
"User-Agent": (
|
|
351
|
+
"VIEWS-DataFactory/1.0 (monthly-cron)"
|
|
352
|
+
),
|
|
353
|
+
},
|
|
354
|
+
params=params,
|
|
355
|
+
max_retries=max_retries,
|
|
356
|
+
timeout=timeout,
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
try:
|
|
360
|
+
return _do_request(state), state
|
|
361
|
+
except requests.HTTPError as exc:
|
|
362
|
+
if (
|
|
363
|
+
exc.response is not None
|
|
364
|
+
and exc.response.status_code == 401
|
|
365
|
+
):
|
|
366
|
+
logger.warning(
|
|
367
|
+
"401 from %s — forcing token refresh", url,
|
|
368
|
+
)
|
|
369
|
+
state = _acquire_token(
|
|
370
|
+
username, password,
|
|
371
|
+
token_url, timeout, max_retries,
|
|
372
|
+
)
|
|
373
|
+
return _do_request(state), state
|
|
374
|
+
raise
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def fetch_paginated(
|
|
378
|
+
config: AcledConfig,
|
|
379
|
+
username: str,
|
|
380
|
+
password: str,
|
|
381
|
+
*,
|
|
382
|
+
max_pages: int | None = None,
|
|
383
|
+
_token_state: _TokenState | None = None,
|
|
384
|
+
) -> list[dict]:
|
|
385
|
+
"""Fetch all ACLED events with page-based pagination.
|
|
386
|
+
|
|
387
|
+
Args:
|
|
388
|
+
config: Harvest configuration.
|
|
389
|
+
username: ACLED username.
|
|
390
|
+
password: ACLED password.
|
|
391
|
+
max_pages: Stop after this many pages (None = fetch all).
|
|
392
|
+
_token_state: Pre-acquired token (avoids re-auth per year).
|
|
393
|
+
|
|
394
|
+
Returns:
|
|
395
|
+
List of raw event dicts.
|
|
396
|
+
"""
|
|
397
|
+
token_state = _token_state or _acquire_token(
|
|
398
|
+
username,
|
|
399
|
+
password,
|
|
400
|
+
config.token_url,
|
|
401
|
+
config.timeout,
|
|
402
|
+
config.max_retries,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
all_events: list[dict] = []
|
|
406
|
+
page = 1
|
|
407
|
+
|
|
408
|
+
while True:
|
|
409
|
+
params: dict = {
|
|
410
|
+
"_format": "json",
|
|
411
|
+
"event_date": (
|
|
412
|
+
f"{config.start_year}-01-01"
|
|
413
|
+
f"|{config.end_year}-12-31"
|
|
414
|
+
),
|
|
415
|
+
"event_date_where": "BETWEEN",
|
|
416
|
+
"limit": config.page_size,
|
|
417
|
+
"page": page,
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
if config.event_types != ALL_EVENT_TYPES:
|
|
421
|
+
params["event_type"] = "|".join(config.event_types)
|
|
422
|
+
|
|
423
|
+
response, token_state = _authenticated_request(
|
|
424
|
+
config.api_url,
|
|
425
|
+
params,
|
|
426
|
+
token_state,
|
|
427
|
+
username,
|
|
428
|
+
password,
|
|
429
|
+
config.token_url,
|
|
430
|
+
config.timeout,
|
|
431
|
+
config.max_retries,
|
|
432
|
+
)
|
|
433
|
+
data = response.json()
|
|
434
|
+
|
|
435
|
+
results = data.get("data", [])
|
|
436
|
+
if not results:
|
|
437
|
+
break
|
|
438
|
+
|
|
439
|
+
all_events.extend(results)
|
|
440
|
+
|
|
441
|
+
if page % _LOG_EVERY_N_PAGES == 0 or page == 1:
|
|
442
|
+
logger.info(
|
|
443
|
+
"Page %d: %d events fetched so far",
|
|
444
|
+
page,
|
|
445
|
+
len(all_events),
|
|
446
|
+
)
|
|
447
|
+
|
|
448
|
+
if len(results) < config.page_size:
|
|
449
|
+
break
|
|
450
|
+
if max_pages is not None and page >= max_pages:
|
|
451
|
+
logger.info(
|
|
452
|
+
"Stopped after %d pages (max_pages limit)",
|
|
453
|
+
max_pages,
|
|
454
|
+
)
|
|
455
|
+
break
|
|
456
|
+
|
|
457
|
+
page += 1
|
|
458
|
+
time.sleep(config.page_delay)
|
|
459
|
+
|
|
460
|
+
logger.info(
|
|
461
|
+
"Fetched %d total ACLED events across %d pages",
|
|
462
|
+
len(all_events),
|
|
463
|
+
page,
|
|
464
|
+
)
|
|
465
|
+
return all_events
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
# ---- Orchestrator ----
|
|
469
|
+
|
|
470
|
+
DIGEST_FIELDS: tuple[str, ...] = ("event_id_cnty", "fatalities")
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _snapshot_path(config: AcledConfig) -> Path:
|
|
474
|
+
"""Deterministic path for the raw event snapshot."""
|
|
475
|
+
return (
|
|
476
|
+
config.data_dir
|
|
477
|
+
/ f"acled_{config.start_year}_{config.end_year}.parquet"
|
|
478
|
+
)
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def _recompute_content_digest(snap_path: Path) -> str | None:
|
|
482
|
+
"""Recompute content_digest from a Parquet snapshot on disk.
|
|
483
|
+
|
|
484
|
+
Uses the same algorithm as event_validation.py: sorted tuples of
|
|
485
|
+
digest fields → JSON → SHA-256. Returns None if the file cannot
|
|
486
|
+
be read (corrupted, missing columns).
|
|
487
|
+
"""
|
|
488
|
+
try:
|
|
489
|
+
table = pq.read_table(
|
|
490
|
+
snap_path, columns=list(DIGEST_FIELDS),
|
|
491
|
+
)
|
|
492
|
+
except (pa.lib.ArrowInvalid, OSError):
|
|
493
|
+
logger.warning(
|
|
494
|
+
"Cannot read %s for digest — treating as cache miss",
|
|
495
|
+
snap_path,
|
|
496
|
+
)
|
|
497
|
+
return None
|
|
498
|
+
digest_data = sorted(
|
|
499
|
+
tuple(row) for row in zip(
|
|
500
|
+
*(table.column(f).to_pylist() for f in DIGEST_FIELDS),
|
|
501
|
+
strict=True,
|
|
502
|
+
)
|
|
503
|
+
)
|
|
504
|
+
return compute_content_digest(
|
|
505
|
+
json.dumps(digest_data, sort_keys=True).encode()
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _year_is_cached(year: int, config: AcledConfig) -> bool:
|
|
510
|
+
"""Check if a year's snapshot exists with a matching ledger digest.
|
|
511
|
+
|
|
512
|
+
The current year is never considered cached because ACLED publishes
|
|
513
|
+
new events biweekly — the local snapshot is always stale.
|
|
514
|
+
"""
|
|
515
|
+
if year >= datetime.datetime.now(tz=datetime.UTC).year:
|
|
516
|
+
return False
|
|
517
|
+
version = f"{year}_{year}"
|
|
518
|
+
snap_path = config.data_dir / f"acled_{year}_{year}.parquet"
|
|
519
|
+
if not snap_path.exists():
|
|
520
|
+
return False
|
|
521
|
+
previous = last_digest_for_version(
|
|
522
|
+
config.ledger_path, version
|
|
523
|
+
)
|
|
524
|
+
if previous is None:
|
|
525
|
+
return False
|
|
526
|
+
actual = _recompute_content_digest(snap_path)
|
|
527
|
+
if actual is None:
|
|
528
|
+
return False
|
|
529
|
+
if actual != previous:
|
|
530
|
+
logger.warning(
|
|
531
|
+
"Year %d cached content digest mismatch "
|
|
532
|
+
"(expected %s, got %s) — re-fetching",
|
|
533
|
+
year, previous, actual,
|
|
534
|
+
)
|
|
535
|
+
return False
|
|
536
|
+
return True
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _fetch_single_year(
|
|
540
|
+
year: int,
|
|
541
|
+
config: AcledConfig,
|
|
542
|
+
resolved_user: str,
|
|
543
|
+
resolved_pass: str,
|
|
544
|
+
token_state: _TokenState,
|
|
545
|
+
) -> dict:
|
|
546
|
+
"""Fetch one year of ACLED data: fetch, validate, store.
|
|
547
|
+
|
|
548
|
+
Returns a result dict with version, outcome, and path info.
|
|
549
|
+
"""
|
|
550
|
+
version = f"{year}_{year}"
|
|
551
|
+
year_config = AcledConfig(
|
|
552
|
+
start_year=year,
|
|
553
|
+
end_year=year,
|
|
554
|
+
event_types=config.event_types,
|
|
555
|
+
api_url=config.api_url,
|
|
556
|
+
token_url=config.token_url,
|
|
557
|
+
page_size=config.page_size,
|
|
558
|
+
timeout=config.timeout,
|
|
559
|
+
max_retries=config.max_retries,
|
|
560
|
+
page_delay=config.page_delay,
|
|
561
|
+
data_dir=config.data_dir,
|
|
562
|
+
ledger_path=config.ledger_path,
|
|
563
|
+
)
|
|
564
|
+
snap_path = _snapshot_path(year_config)
|
|
565
|
+
|
|
566
|
+
t0 = time.monotonic()
|
|
567
|
+
events = fetch_paginated(
|
|
568
|
+
year_config,
|
|
569
|
+
resolved_user,
|
|
570
|
+
resolved_pass,
|
|
571
|
+
_token_state=token_state,
|
|
572
|
+
)
|
|
573
|
+
fetch_duration = time.monotonic() - t0
|
|
574
|
+
|
|
575
|
+
validation = validate_events(
|
|
576
|
+
events,
|
|
577
|
+
REQUIRED_FIELDS,
|
|
578
|
+
FIELD_TYPES,
|
|
579
|
+
digest_fields=DIGEST_FIELDS,
|
|
580
|
+
)
|
|
581
|
+
|
|
582
|
+
min_date, max_date = date_range(
|
|
583
|
+
events, field_name="event_date"
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
base_entry = {
|
|
587
|
+
"dataset": DATASET_ID,
|
|
588
|
+
"version": version,
|
|
589
|
+
"start_year": year,
|
|
590
|
+
"end_year": year,
|
|
591
|
+
"n_events": validation.n_events,
|
|
592
|
+
"min_date": min_date,
|
|
593
|
+
"max_date": max_date,
|
|
594
|
+
"fetch_duration_s": round(
|
|
595
|
+
fetch_duration, _FETCH_DURATION_PRECISION
|
|
596
|
+
),
|
|
597
|
+
"content_digest": validation.content_digest,
|
|
598
|
+
"ledger_version": LEDGER_VERSION,
|
|
599
|
+
"digest_algorithm": DIGEST_SCHEME,
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
if not validation.valid:
|
|
603
|
+
err_msg = (
|
|
604
|
+
f"Validation failed for year {year}: "
|
|
605
|
+
f"{validation.errors}"
|
|
606
|
+
)
|
|
607
|
+
logger.error(err_msg)
|
|
608
|
+
append_ledger_entry(config.ledger_path, {
|
|
609
|
+
**base_entry,
|
|
610
|
+
"outcome": "failed",
|
|
611
|
+
"errors": validation.errors,
|
|
612
|
+
"warnings": validation.warnings,
|
|
613
|
+
})
|
|
614
|
+
raise ValueError(err_msg)
|
|
615
|
+
|
|
616
|
+
validate_dgp_assumptions(
|
|
617
|
+
events, ACLED_DGP_CHECKS, source_name="ACLED",
|
|
618
|
+
)
|
|
619
|
+
|
|
620
|
+
comparison: ComparisonResult | None = None
|
|
621
|
+
if snap_path.exists():
|
|
622
|
+
comparison = compare_snapshots(
|
|
623
|
+
snap_path,
|
|
624
|
+
events,
|
|
625
|
+
id_field="event_id_cnty",
|
|
626
|
+
key_fields=("fatalities", "country", "event_date"),
|
|
627
|
+
)
|
|
628
|
+
if comparison.has_previous and comparison.n_revised == 0:
|
|
629
|
+
logger.info(
|
|
630
|
+
"Year %d: no revisions since previous snapshot",
|
|
631
|
+
year,
|
|
632
|
+
)
|
|
633
|
+
|
|
634
|
+
if snap_path.exists():
|
|
635
|
+
archive_snapshot(snap_path)
|
|
636
|
+
|
|
637
|
+
save_event_snapshot(events, snap_path)
|
|
638
|
+
|
|
639
|
+
revision_warnings = comparison.warnings if comparison else []
|
|
640
|
+
append_ledger_entry(config.ledger_path, {
|
|
641
|
+
**base_entry,
|
|
642
|
+
"outcome": "success",
|
|
643
|
+
"schema_fields": sorted(validation.schema_snapshot.keys()),
|
|
644
|
+
"schema_types": validation.schema_snapshot,
|
|
645
|
+
"warnings": validation.warnings + revision_warnings,
|
|
646
|
+
"errors": validation.errors,
|
|
647
|
+
})
|
|
648
|
+
|
|
649
|
+
return {
|
|
650
|
+
"version": version,
|
|
651
|
+
"outcome": "success",
|
|
652
|
+
"digest": validation.content_digest,
|
|
653
|
+
"path": str(snap_path),
|
|
654
|
+
"n_events": validation.n_events,
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def fetch_acled(
|
|
659
|
+
config: AcledConfig | None = None,
|
|
660
|
+
*,
|
|
661
|
+
username: str | None = None,
|
|
662
|
+
password: str | None = None,
|
|
663
|
+
force_refresh: bool = False,
|
|
664
|
+
) -> Path:
|
|
665
|
+
"""Fetch ACLED data year-by-year: auth, then per-year fetch/skip.
|
|
666
|
+
|
|
667
|
+
Each year gets its own snapshot and version-aware ledger entry.
|
|
668
|
+
Cached years (snapshot + ledger digest) are skipped, so monthly
|
|
669
|
+
cron runs only fetch the current year.
|
|
670
|
+
|
|
671
|
+
Args:
|
|
672
|
+
config: Harvest configuration (defaults to full range).
|
|
673
|
+
username: ACLED username (falls back to ACLED_USERNAME env var).
|
|
674
|
+
password: ACLED password (falls back to ACLED_PASSWORD env var).
|
|
675
|
+
force_refresh: If True, re-fetch even if snapshot exists.
|
|
676
|
+
|
|
677
|
+
Returns:
|
|
678
|
+
Path to the data directory containing per-year snapshots.
|
|
679
|
+
"""
|
|
680
|
+
if config is None:
|
|
681
|
+
config = AcledConfig()
|
|
682
|
+
|
|
683
|
+
resolved_user, resolved_pass = get_acled_credentials(
|
|
684
|
+
username, password
|
|
685
|
+
)
|
|
686
|
+
|
|
687
|
+
token_state: _TokenState | None = None
|
|
688
|
+
|
|
689
|
+
results = []
|
|
690
|
+
for year in range(config.start_year, config.end_year + 1):
|
|
691
|
+
if not force_refresh and _year_is_cached(
|
|
692
|
+
year, config
|
|
693
|
+
):
|
|
694
|
+
version = f"{year}_{year}"
|
|
695
|
+
logger.info("Year %d cached, skipping", year)
|
|
696
|
+
results.append({
|
|
697
|
+
"version": version,
|
|
698
|
+
"outcome": "cached",
|
|
699
|
+
})
|
|
700
|
+
continue
|
|
701
|
+
|
|
702
|
+
if token_state is None:
|
|
703
|
+
token_state = _acquire_token(
|
|
704
|
+
resolved_user,
|
|
705
|
+
resolved_pass,
|
|
706
|
+
config.token_url,
|
|
707
|
+
config.timeout,
|
|
708
|
+
config.max_retries,
|
|
709
|
+
)
|
|
710
|
+
else:
|
|
711
|
+
token_state = _ensure_token(
|
|
712
|
+
token_state,
|
|
713
|
+
resolved_user,
|
|
714
|
+
resolved_pass,
|
|
715
|
+
config.token_url,
|
|
716
|
+
config.timeout,
|
|
717
|
+
config.max_retries,
|
|
718
|
+
)
|
|
719
|
+
|
|
720
|
+
result = _fetch_single_year(
|
|
721
|
+
year,
|
|
722
|
+
config,
|
|
723
|
+
resolved_user,
|
|
724
|
+
resolved_pass,
|
|
725
|
+
token_state,
|
|
726
|
+
)
|
|
727
|
+
results.append(result)
|
|
728
|
+
|
|
729
|
+
cached = sum(1 for r in results if r["outcome"] == "cached")
|
|
730
|
+
fetched = sum(
|
|
731
|
+
1 for r in results if r["outcome"] == "success"
|
|
732
|
+
)
|
|
733
|
+
logger.info(
|
|
734
|
+
"ACLED harvest: %d years total, %d cached, %d fetched",
|
|
735
|
+
len(results),
|
|
736
|
+
cached,
|
|
737
|
+
fetched,
|
|
738
|
+
)
|
|
739
|
+
|
|
740
|
+
return config.data_dir
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
register_source("acled", fetch_acled)
|