mloda-plugin-govdata 0.2.1__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.
- mloda_plugin_govdata/__init__.py +0 -0
- mloda_plugin_govdata/feature_groups/__init__.py +1 -0
- mloda_plugin_govdata/feature_groups/govdata/__init__.py +55 -0
- mloda_plugin_govdata/feature_groups/govdata/bundeswahlleiterin.py +48 -0
- mloda_plugin_govdata/feature_groups/govdata/core/__init__.py +1 -0
- mloda_plugin_govdata/feature_groups/govdata/core/cache.py +114 -0
- mloda_plugin_govdata/feature_groups/govdata/core/client.py +72 -0
- mloda_plugin_govdata/feature_groups/govdata/core/discovery.py +177 -0
- mloda_plugin_govdata/feature_groups/govdata/core/locator.py +42 -0
- mloda_plugin_govdata/feature_groups/govdata/core/parse.py +275 -0
- mloda_plugin_govdata/feature_groups/govdata/feature.py +17 -0
- mloda_plugin_govdata/feature_groups/govdata/population.py +22 -0
- mloda_plugin_govdata/feature_groups/govdata/reader.py +123 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/__init__.py +0 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/conftest.py +8 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_cache.py +62 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_client.py +49 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_discovery.py +157 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_parse.py +183 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_parse_hypothesis.py +38 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_reader.py +327 -0
- mloda_plugin_govdata/feature_groups/govdata/tests/test_uba.py +193 -0
- mloda_plugin_govdata/feature_groups/govdata/uba.py +220 -0
- mloda_plugin_govdata-0.2.1.dist-info/METADATA +29 -0
- mloda_plugin_govdata-0.2.1.dist-info/RECORD +28 -0
- mloda_plugin_govdata-0.2.1.dist-info/WHEEL +5 -0
- mloda_plugin_govdata-0.2.1.dist-info/licenses/LICENSE +201 -0
- mloda_plugin_govdata-0.2.1.dist-info/top_level.txt +1 -0
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Feature groups namespace package."""
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""GovData connector: read German open-government data into mloda."""
|
|
2
|
+
|
|
3
|
+
from .bundeswahlleiterin import (
|
|
4
|
+
OPTION_WAHL_HEADER_ROWS,
|
|
5
|
+
OPTION_WAHL_LABEL_COLUMNS,
|
|
6
|
+
OPTION_WAHL_SKIPROWS,
|
|
7
|
+
OPTION_WAHL_VALUE_TYPE,
|
|
8
|
+
BundeswahlleiterinReader,
|
|
9
|
+
)
|
|
10
|
+
from .core.client import build_client
|
|
11
|
+
from .core.discovery import (
|
|
12
|
+
Dataset,
|
|
13
|
+
ResolvedDistribution,
|
|
14
|
+
Resource,
|
|
15
|
+
normalize_license,
|
|
16
|
+
resolve_distribution,
|
|
17
|
+
search_datasets,
|
|
18
|
+
)
|
|
19
|
+
from .core.locator import GovDataLocator
|
|
20
|
+
from .core.parse import ColumnType, parse_german_csv, parse_german_csv_bytes, parse_multi_header_csv
|
|
21
|
+
from .feature import GovDataFeature
|
|
22
|
+
from .population import POPULATION_SCHEMA, POPULATION_SLUG, StuttgartPopulationReader
|
|
23
|
+
from .reader import BaseGovDataReader, GovDataReader
|
|
24
|
+
from .uba import UBA_AIR_BASE, UbaAirReader, parse_uba_measures, parse_uba_measures_bytes, uba_measures_url
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"OPTION_WAHL_HEADER_ROWS",
|
|
28
|
+
"OPTION_WAHL_LABEL_COLUMNS",
|
|
29
|
+
"OPTION_WAHL_SKIPROWS",
|
|
30
|
+
"OPTION_WAHL_VALUE_TYPE",
|
|
31
|
+
"POPULATION_SCHEMA",
|
|
32
|
+
"POPULATION_SLUG",
|
|
33
|
+
"UBA_AIR_BASE",
|
|
34
|
+
"BaseGovDataReader",
|
|
35
|
+
"BundeswahlleiterinReader",
|
|
36
|
+
"ColumnType",
|
|
37
|
+
"Dataset",
|
|
38
|
+
"GovDataFeature",
|
|
39
|
+
"GovDataLocator",
|
|
40
|
+
"GovDataReader",
|
|
41
|
+
"ResolvedDistribution",
|
|
42
|
+
"Resource",
|
|
43
|
+
"StuttgartPopulationReader",
|
|
44
|
+
"UbaAirReader",
|
|
45
|
+
"build_client",
|
|
46
|
+
"normalize_license",
|
|
47
|
+
"parse_german_csv",
|
|
48
|
+
"parse_german_csv_bytes",
|
|
49
|
+
"parse_multi_header_csv",
|
|
50
|
+
"parse_uba_measures",
|
|
51
|
+
"parse_uba_measures_bytes",
|
|
52
|
+
"resolve_distribution",
|
|
53
|
+
"search_datasets",
|
|
54
|
+
"uba_measures_url",
|
|
55
|
+
]
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Bundeswahlleiterin federal election results (M1 elections theme, kerg.csv)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import pyarrow as pa
|
|
8
|
+
from mloda.user import Options
|
|
9
|
+
|
|
10
|
+
from .core.discovery import ResolvedDistribution
|
|
11
|
+
from .core.locator import GovDataLocator
|
|
12
|
+
from .core.parse import ColumnType, parse_multi_header_csv
|
|
13
|
+
from .reader import BaseGovDataReader
|
|
14
|
+
|
|
15
|
+
# Feature-option keys steering the multi-header election parse; defaults are the btw25 kerg.csv
|
|
16
|
+
# geometry, so a new election file is a per-feature configuration change, not a code change.
|
|
17
|
+
OPTION_WAHL_SKIPROWS = "govdata_wahl_skiprows"
|
|
18
|
+
OPTION_WAHL_HEADER_ROWS = "govdata_wahl_header_rows"
|
|
19
|
+
OPTION_WAHL_LABEL_COLUMNS = "govdata_wahl_label_columns"
|
|
20
|
+
OPTION_WAHL_VALUE_TYPE = "govdata_wahl_value_type"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class BundeswahlleiterinReader(BaseGovDataReader):
|
|
24
|
+
"""Reads German election-result CSVs with the Bundeswahlleiterin kerg.csv as the default geometry.
|
|
25
|
+
|
|
26
|
+
The header geometry defaults to the btw25 kerg.csv layout (5-line preamble, 3-row merged
|
|
27
|
+
header, 4 label columns, integer values) and is overridable per feature via the
|
|
28
|
+
``OPTION_WAHL_*`` option keys. A degenerate geometry (``header_rows=1``, ``skiprows=0``)
|
|
29
|
+
covers single-header publisher exports, so connecting the next election is a
|
|
30
|
+
configuration step instead of a code change.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def _parse(
|
|
35
|
+
cls, path: Path, locator: GovDataLocator, distribution: ResolvedDistribution, options: Options | None = None
|
|
36
|
+
) -> pa.Table:
|
|
37
|
+
def int_option(key: str, default: int) -> int:
|
|
38
|
+
value = options.get(key) if options is not None else None
|
|
39
|
+
return default if value is None else int(value) # non-numeric values raise loudly
|
|
40
|
+
|
|
41
|
+
raw_value_type = options.get(OPTION_WAHL_VALUE_TYPE) if options is not None else None
|
|
42
|
+
return parse_multi_header_csv(
|
|
43
|
+
path,
|
|
44
|
+
skiprows=int_option(OPTION_WAHL_SKIPROWS, 5),
|
|
45
|
+
header_rows=int_option(OPTION_WAHL_HEADER_ROWS, 3),
|
|
46
|
+
label_columns=int_option(OPTION_WAHL_LABEL_COLUMNS, 4),
|
|
47
|
+
value_type=ColumnType(raw_value_type) if raw_value_type is not None else ColumnType.INTEGER,
|
|
48
|
+
)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Source-agnostic plumbing: HTTP client, download cache, CKAN discovery, locator, CSV parsing."""
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Content-addressed download cache with conditional-GET revalidation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from types import TracebackType
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from .client import build_client, request_with_retry
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class CachedFile:
|
|
20
|
+
path: Path
|
|
21
|
+
url: str
|
|
22
|
+
sha256: str
|
|
23
|
+
etag: str | None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DownloadCache:
|
|
27
|
+
"""Stores downloaded bodies addressed by content hash.
|
|
28
|
+
|
|
29
|
+
Revalidates with ``If-None-Match`` / ``If-Modified-Since``; a ``304`` reuses
|
|
30
|
+
the stored body (sha256-verified). Safe to share across runs: entries are
|
|
31
|
+
keyed by URL and content hash.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, cache_dir: str | os.PathLike[str], client: httpx.Client | None = None) -> None:
|
|
35
|
+
self.cache_dir = Path(cache_dir)
|
|
36
|
+
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
self._owns_client = client is None
|
|
38
|
+
self._client = client if client is not None else build_client()
|
|
39
|
+
|
|
40
|
+
# PYI034/PYI019 want `Self`, which is 3.11+; the package floor is 3.10 and the class
|
|
41
|
+
# is never subclassed, so the concrete return type is accurate here.
|
|
42
|
+
def __enter__(self) -> DownloadCache: # noqa: PYI034
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
def __exit__(
|
|
46
|
+
self,
|
|
47
|
+
exc_type: type[BaseException] | None,
|
|
48
|
+
exc: BaseException | None,
|
|
49
|
+
tb: TracebackType | None,
|
|
50
|
+
) -> None:
|
|
51
|
+
self.close()
|
|
52
|
+
|
|
53
|
+
def close(self) -> None:
|
|
54
|
+
if self._owns_client:
|
|
55
|
+
self._client.close()
|
|
56
|
+
|
|
57
|
+
def _meta_path(self, url: str) -> Path:
|
|
58
|
+
key = hashlib.sha256(url.encode("utf-8")).hexdigest()
|
|
59
|
+
return self.cache_dir / f"{key}.meta.json"
|
|
60
|
+
|
|
61
|
+
def _read_meta(self, url: str) -> dict[str, Any] | None:
|
|
62
|
+
meta_path = self._meta_path(url)
|
|
63
|
+
if not meta_path.exists():
|
|
64
|
+
return None
|
|
65
|
+
try:
|
|
66
|
+
loaded = json.loads(meta_path.read_text(encoding="utf-8"))
|
|
67
|
+
except (json.JSONDecodeError, OSError):
|
|
68
|
+
return None # unreadable metadata: treat as a cache miss and re-download
|
|
69
|
+
return loaded if isinstance(loaded, dict) else None
|
|
70
|
+
|
|
71
|
+
def get_or_download(self, url: str) -> CachedFile:
|
|
72
|
+
meta = self._read_meta(url)
|
|
73
|
+
cached = self._cached_from_meta(url, meta) if meta is not None else None
|
|
74
|
+
|
|
75
|
+
# Only revalidate conditionally when there is a valid body to fall back on;
|
|
76
|
+
# otherwise request unconditionally so the server sends a full 200.
|
|
77
|
+
headers: dict[str, str] = {}
|
|
78
|
+
if cached is not None and meta is not None:
|
|
79
|
+
if meta.get("etag"):
|
|
80
|
+
headers["If-None-Match"] = meta["etag"]
|
|
81
|
+
if meta.get("last_modified"):
|
|
82
|
+
headers["If-Modified-Since"] = meta["last_modified"]
|
|
83
|
+
|
|
84
|
+
response = request_with_retry(self._client, "GET", url, headers=headers)
|
|
85
|
+
if response.status_code == 304:
|
|
86
|
+
if cached is not None:
|
|
87
|
+
return cached
|
|
88
|
+
raise RuntimeError(f"server returned 304 for {url} but no cached body is available")
|
|
89
|
+
response.raise_for_status()
|
|
90
|
+
return self._store(url, response)
|
|
91
|
+
|
|
92
|
+
def _cached_from_meta(self, url: str, meta: dict[str, Any]) -> CachedFile | None:
|
|
93
|
+
data_path = self.cache_dir / str(meta.get("data_file", ""))
|
|
94
|
+
if not data_path.exists():
|
|
95
|
+
return None
|
|
96
|
+
digest = hashlib.sha256(data_path.read_bytes()).hexdigest()
|
|
97
|
+
if digest != meta.get("sha256"):
|
|
98
|
+
return None # corrupted cache; force re-download
|
|
99
|
+
return CachedFile(path=data_path, url=url, sha256=digest, etag=meta.get("etag"))
|
|
100
|
+
|
|
101
|
+
def _store(self, url: str, response: httpx.Response) -> CachedFile:
|
|
102
|
+
body = response.content
|
|
103
|
+
digest = hashlib.sha256(body).hexdigest()
|
|
104
|
+
data_path = self.cache_dir / f"{digest}.bin"
|
|
105
|
+
data_path.write_bytes(body)
|
|
106
|
+
meta: dict[str, Any] = {
|
|
107
|
+
"url": url,
|
|
108
|
+
"etag": response.headers.get("ETag"),
|
|
109
|
+
"last_modified": response.headers.get("Last-Modified"),
|
|
110
|
+
"sha256": digest,
|
|
111
|
+
"data_file": data_path.name,
|
|
112
|
+
}
|
|
113
|
+
self._meta_path(url).write_text(json.dumps(meta), encoding="utf-8")
|
|
114
|
+
return CachedFile(path=data_path, url=url, sha256=digest, etag=meta["etag"])
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""HTTP client and retry policy for GovData / publisher requests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.metadata
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
from tenacity import RetryCallState, retry, retry_if_exception, stop_after_attempt, wait_exponential_jitter
|
|
10
|
+
|
|
11
|
+
# Four-part timeout: distinct connect / read / write / pool budgets.
|
|
12
|
+
DEFAULT_TIMEOUT = httpx.Timeout(connect=10.0, read=60.0, write=30.0, pool=10.0)
|
|
13
|
+
RETRYABLE_STATUS: frozenset[int] = frozenset({429, 500, 502, 503, 504})
|
|
14
|
+
MAX_ATTEMPTS = 5
|
|
15
|
+
MAX_RETRY_AFTER = 60.0 # cap a server's Retry-After so it cannot stall the client for hours
|
|
16
|
+
|
|
17
|
+
_BASE_WAIT = wait_exponential_jitter(initial=0.5, max=10.0)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _user_agent() -> str:
|
|
21
|
+
try:
|
|
22
|
+
version = importlib.metadata.version("mloda-plugin-govdata")
|
|
23
|
+
except importlib.metadata.PackageNotFoundError:
|
|
24
|
+
version = "0.0.0"
|
|
25
|
+
return f"mloda-plugin-govdata/{version} (+https://github.com/mloda-ai/mloda-plugin-govdata)"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def build_client(*, timeout: httpx.Timeout = DEFAULT_TIMEOUT) -> httpx.Client:
|
|
29
|
+
"""A pooled httpx client with the polite User-Agent and timeout budget."""
|
|
30
|
+
return httpx.Client(timeout=timeout, headers={"User-Agent": _user_agent()}, follow_redirects=True)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class RetryableStatusError(Exception):
|
|
34
|
+
"""Raised internally so a retryable status code triggers a tenacity retry."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, response: httpx.Response) -> None:
|
|
37
|
+
self.response = response
|
|
38
|
+
self.retry_after = _parse_retry_after(response)
|
|
39
|
+
super().__init__(f"retryable status {response.status_code} for {response.request.url}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _parse_retry_after(response: httpx.Response) -> float | None:
|
|
43
|
+
raw = response.headers.get("Retry-After")
|
|
44
|
+
if raw is None:
|
|
45
|
+
return None
|
|
46
|
+
try:
|
|
47
|
+
return float(raw) # seconds form; HTTP-date form is not honored
|
|
48
|
+
except ValueError:
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _is_retryable(exc: BaseException) -> bool:
|
|
53
|
+
return isinstance(exc, (httpx.TransportError, RetryableStatusError))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _wait(state: RetryCallState) -> float:
|
|
57
|
+
base = _BASE_WAIT(state)
|
|
58
|
+
outcome = state.outcome
|
|
59
|
+
if outcome is not None:
|
|
60
|
+
exc = outcome.exception()
|
|
61
|
+
if isinstance(exc, RetryableStatusError) and exc.retry_after is not None:
|
|
62
|
+
return max(base, min(exc.retry_after, MAX_RETRY_AFTER))
|
|
63
|
+
return base
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@retry(retry=retry_if_exception(_is_retryable), wait=_wait, stop=stop_after_attempt(MAX_ATTEMPTS), reraise=True)
|
|
67
|
+
def request_with_retry(client: httpx.Client, method: str, url: str, **kwargs: Any) -> httpx.Response:
|
|
68
|
+
"""Issue a request, retrying transport errors and retryable status codes."""
|
|
69
|
+
response = client.request(method, url, **kwargs)
|
|
70
|
+
if response.status_code in RETRYABLE_STATUS:
|
|
71
|
+
raise RetryableStatusError(response)
|
|
72
|
+
return response
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""CKAN discovery: find GovData datasets and resolve them to a distribution URL and license."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterator
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
from pydantic import BaseModel, ConfigDict
|
|
11
|
+
|
|
12
|
+
from .client import request_with_retry
|
|
13
|
+
from .locator import DEFAULT_CKAN_BASE, GovDataLocator
|
|
14
|
+
|
|
15
|
+
# dcat-ap.de license URIs observed across GovData distributions -> short labels.
|
|
16
|
+
LICENSE_LABELS: dict[str, str] = {
|
|
17
|
+
"http://dcat-ap.de/def/licenses/cc-by/4.0": "CC-BY-4.0",
|
|
18
|
+
"http://dcat-ap.de/def/licenses/dl-by-de/2.0": "DL-DE-BY-2.0",
|
|
19
|
+
"http://dcat-ap.de/def/licenses/dl-zero-de/2.0": "DL-DE-Zero-2.0",
|
|
20
|
+
"http://dcat-ap.de/def/licenses/cc-zero": "CC0-1.0",
|
|
21
|
+
"http://dcat-ap.de/def/licenses/geonutz/20130319": "GeoNutzV",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def normalize_license(uri: str | None) -> str | None:
|
|
26
|
+
"""Map a dcat-ap.de license URI to a short label, tolerating spelling drift.
|
|
27
|
+
|
|
28
|
+
Returns the raw value for unknown / free-text licenses (warn, never refuse),
|
|
29
|
+
and None when no license is present.
|
|
30
|
+
"""
|
|
31
|
+
if not uri:
|
|
32
|
+
return None
|
|
33
|
+
candidate = uri.strip()
|
|
34
|
+
# dataset-level uses dl-by-de/2_0, resource-level dl-by-de/2.0; normalize the underscore.
|
|
35
|
+
normalized = candidate.replace("/2_0", "/2.0")
|
|
36
|
+
return LICENSE_LABELS.get(candidate) or LICENSE_LABELS.get(normalized) or candidate
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Resource(BaseModel):
|
|
40
|
+
model_config = ConfigDict(extra="ignore")
|
|
41
|
+
|
|
42
|
+
url: str
|
|
43
|
+
format: str | None = None
|
|
44
|
+
license: str | None = None
|
|
45
|
+
mimetype: str | None = None
|
|
46
|
+
name: str | None = None
|
|
47
|
+
size: int | None = None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Dataset(BaseModel):
|
|
51
|
+
model_config = ConfigDict(extra="ignore")
|
|
52
|
+
|
|
53
|
+
name: str | None = None
|
|
54
|
+
title: str | None = None
|
|
55
|
+
notes: str | None = None
|
|
56
|
+
resources: list[Resource] = []
|
|
57
|
+
extras: dict[str, str] = {}
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def from_ckan(cls, result: dict[str, Any]) -> Dataset:
|
|
61
|
+
extras = {e["key"]: str(e.get("value", "")) for e in result.get("extras", []) if "key" in e}
|
|
62
|
+
resources = [Resource.model_validate(r) for r in result.get("resources", [])]
|
|
63
|
+
return cls(
|
|
64
|
+
name=result.get("name"),
|
|
65
|
+
title=result.get("title"),
|
|
66
|
+
notes=result.get("notes"),
|
|
67
|
+
resources=resources,
|
|
68
|
+
extras=extras,
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class ResolvedDistribution:
|
|
74
|
+
url: str
|
|
75
|
+
license: str | None
|
|
76
|
+
dataset: Dataset | None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def fetch_dataset(client: httpx.Client, locator: GovDataLocator) -> Dataset:
|
|
80
|
+
"""Call CKAN ``package_show`` for the locator's dataset id."""
|
|
81
|
+
response = request_with_retry(
|
|
82
|
+
client,
|
|
83
|
+
"GET",
|
|
84
|
+
f"{locator.ckan_base}/package_show",
|
|
85
|
+
params={"id": locator.dataset_id},
|
|
86
|
+
)
|
|
87
|
+
response.raise_for_status()
|
|
88
|
+
payload: dict[str, Any] = response.json()
|
|
89
|
+
if not payload.get("success"):
|
|
90
|
+
raise ValueError(f"CKAN package_show was not successful for {locator.dataset_id!r}")
|
|
91
|
+
return Dataset.from_ckan(payload["result"])
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def search_datasets(
|
|
95
|
+
client: httpx.Client,
|
|
96
|
+
query: str = "",
|
|
97
|
+
*,
|
|
98
|
+
ckan_base: str = DEFAULT_CKAN_BASE,
|
|
99
|
+
page_size: int = 100,
|
|
100
|
+
max_results: int | None = None,
|
|
101
|
+
) -> Iterator[Dataset]:
|
|
102
|
+
"""Search GovData via CKAN ``package_search``, paginating with ``rows``/``start``.
|
|
103
|
+
|
|
104
|
+
Yields datasets lazily page by page; ``max_results`` caps the total yield.
|
|
105
|
+
Stops early when the server returns an empty page, so a stale ``count``
|
|
106
|
+
cannot loop forever.
|
|
107
|
+
"""
|
|
108
|
+
if page_size < 1:
|
|
109
|
+
raise ValueError(f"page_size must be >= 1, got {page_size}")
|
|
110
|
+
if max_results is not None and max_results < 1:
|
|
111
|
+
return
|
|
112
|
+
|
|
113
|
+
yielded = 0
|
|
114
|
+
start = 0
|
|
115
|
+
while True:
|
|
116
|
+
rows = page_size if max_results is None else min(page_size, max_results - yielded)
|
|
117
|
+
response = request_with_retry(
|
|
118
|
+
client,
|
|
119
|
+
"GET",
|
|
120
|
+
f"{ckan_base}/package_search",
|
|
121
|
+
params={"q": query, "rows": rows, "start": start},
|
|
122
|
+
)
|
|
123
|
+
response.raise_for_status()
|
|
124
|
+
payload: dict[str, Any] = response.json()
|
|
125
|
+
if not payload.get("success"):
|
|
126
|
+
raise ValueError(f"CKAN package_search was not successful for query {query!r}")
|
|
127
|
+
result = payload["result"]
|
|
128
|
+
results: list[dict[str, Any]] = result.get("results", [])
|
|
129
|
+
if not results:
|
|
130
|
+
return
|
|
131
|
+
for entry in results:
|
|
132
|
+
yield Dataset.from_ckan(entry)
|
|
133
|
+
yielded += 1
|
|
134
|
+
if max_results is not None and yielded >= max_results:
|
|
135
|
+
return
|
|
136
|
+
start += len(results)
|
|
137
|
+
count = result.get("count")
|
|
138
|
+
# Without a usable count, the empty-page guard above ends the walk.
|
|
139
|
+
if count is not None and start >= int(count):
|
|
140
|
+
return
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _looks_like_csv(resource: Resource) -> bool:
|
|
144
|
+
"""True when the resource advertises CSV via format, mimetype, or URL suffix."""
|
|
145
|
+
fmt = (resource.format or "").strip().lower()
|
|
146
|
+
mimetype = (resource.mimetype or "").strip().lower()
|
|
147
|
+
return fmt == "csv" or mimetype == "text/csv" or resource.url.lower().endswith(".csv")
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _select_resource(resources: list[Resource], resource_index: int) -> Resource:
|
|
151
|
+
"""Pick the distribution to read, preferring CSV since that is all the reader parses."""
|
|
152
|
+
if not 0 <= resource_index < len(resources):
|
|
153
|
+
raise IndexError(f"resource_index {resource_index} is out of range ({len(resources)} resources)")
|
|
154
|
+
chosen = resources[resource_index]
|
|
155
|
+
if _looks_like_csv(chosen):
|
|
156
|
+
return chosen
|
|
157
|
+
for resource in resources:
|
|
158
|
+
if _looks_like_csv(resource):
|
|
159
|
+
return resource
|
|
160
|
+
return chosen
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def resolve_distribution(locator: GovDataLocator, client: httpx.Client) -> ResolvedDistribution:
|
|
164
|
+
"""Resolve a locator to a concrete distribution URL plus its license.
|
|
165
|
+
|
|
166
|
+
A direct ``distribution_url`` is used as-is; a ``dataset_id`` is resolved via
|
|
167
|
+
``package_show``, reading the license from the chosen distribution (the
|
|
168
|
+
distribution ``license`` is reliably populated; dataset ``license_id`` is not).
|
|
169
|
+
"""
|
|
170
|
+
if locator.distribution_url is not None:
|
|
171
|
+
return ResolvedDistribution(url=locator.distribution_url, license=None, dataset=None)
|
|
172
|
+
|
|
173
|
+
dataset = fetch_dataset(client, locator)
|
|
174
|
+
if not dataset.resources:
|
|
175
|
+
raise ValueError(f"dataset {locator.dataset_id!r} exposes no resources")
|
|
176
|
+
resource = _select_resource(dataset.resources, locator.resource_index)
|
|
177
|
+
return ResolvedDistribution(url=resource.url, license=normalize_license(resource.license), dataset=dataset)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""GovData locator: identifies a dataset distribution to read."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
DEFAULT_CKAN_BASE = "https://ckan.govdata.de/api/3/action"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class GovDataLocator:
|
|
12
|
+
"""Points at one GovData distribution.
|
|
13
|
+
|
|
14
|
+
Either a CKAN ``dataset_id`` (resolved to a distribution via ``package_show``)
|
|
15
|
+
or a direct ``distribution_url``. ``resource_index`` selects the distribution
|
|
16
|
+
when a dataset exposes several.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
dataset_id: str | None = None
|
|
20
|
+
distribution_url: str | None = None
|
|
21
|
+
ckan_base: str = DEFAULT_CKAN_BASE
|
|
22
|
+
resource_index: int = 0
|
|
23
|
+
|
|
24
|
+
def __post_init__(self) -> None:
|
|
25
|
+
if not self.dataset_id and not self.distribution_url:
|
|
26
|
+
raise ValueError("GovDataLocator needs a dataset_id or a distribution_url.")
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def from_string(cls, value: str) -> GovDataLocator:
|
|
30
|
+
"""A URL becomes a direct distribution; anything else is a dataset id."""
|
|
31
|
+
if value.startswith(("http://", "https://")):
|
|
32
|
+
return cls(distribution_url=value)
|
|
33
|
+
return cls(dataset_id=value)
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def coerce(cls, value: object) -> GovDataLocator | None:
|
|
37
|
+
"""Normalize a reader option value into a locator, or None if unusable."""
|
|
38
|
+
if isinstance(value, GovDataLocator):
|
|
39
|
+
return value
|
|
40
|
+
if isinstance(value, str) and value:
|
|
41
|
+
return cls.from_string(value)
|
|
42
|
+
return None
|