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
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""Deterministic parser for German public-authority CSVs into a typed Arrow table.
|
|
2
|
+
|
|
3
|
+
Handles the traits that break a naive ``pyarrow.csv`` read: cp1252/latin
|
|
4
|
+
encodings, semicolon delimiters, German number formatting (``.`` thousands,
|
|
5
|
+
``,`` decimal), German dates, and statistical value markers where ``-`` means
|
|
6
|
+
zero (not missing). Parsing into the wrong type fails loudly rather than
|
|
7
|
+
silently leaving a column as strings.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import csv
|
|
13
|
+
import io
|
|
14
|
+
import os
|
|
15
|
+
from datetime import date, datetime
|
|
16
|
+
from enum import Enum
|
|
17
|
+
|
|
18
|
+
import pandas as pd
|
|
19
|
+
import pyarrow as pa
|
|
20
|
+
|
|
21
|
+
# Strict-decode first, latin-1 last because it never raises (guaranteed fallback).
|
|
22
|
+
ENCODING_LADDER: tuple[str, ...] = ("utf-8-sig", "cp1252", "iso-8859-15", "latin-1")
|
|
23
|
+
|
|
24
|
+
GERMAN_DATE_FORMAT = "%d.%m.%Y"
|
|
25
|
+
|
|
26
|
+
# German statistical value markers (Destatis / Genesis convention).
|
|
27
|
+
ZERO_MARKERS: frozenset[str] = frozenset({"-"}) # exactly zero, never null
|
|
28
|
+
NULL_MARKERS: frozenset[str] = frozenset({".", "...", "/", "x", "()", ""}) # unknown / blocked
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ColumnType(str, Enum):
|
|
32
|
+
STRING = "string"
|
|
33
|
+
INTEGER = "integer"
|
|
34
|
+
FLOAT = "float"
|
|
35
|
+
DATE = "date"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
_ARROW_TYPE: dict[ColumnType, pa.DataType] = {
|
|
39
|
+
ColumnType.STRING: pa.string(),
|
|
40
|
+
ColumnType.INTEGER: pa.int64(),
|
|
41
|
+
ColumnType.FLOAT: pa.float64(),
|
|
42
|
+
ColumnType.DATE: pa.date32(),
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def detect_encoding(data: bytes, ladder: tuple[str, ...] = ENCODING_LADDER) -> str:
|
|
47
|
+
"""First encoding in the ladder that decodes the bytes without error."""
|
|
48
|
+
for enc in ladder:
|
|
49
|
+
try:
|
|
50
|
+
data.decode(enc)
|
|
51
|
+
return enc
|
|
52
|
+
except UnicodeDecodeError:
|
|
53
|
+
continue
|
|
54
|
+
return ladder[-1]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _clean_number(raw: str) -> str | None:
|
|
58
|
+
"""Apply value markers, then de-Germanize the number, or None for null markers."""
|
|
59
|
+
value = raw.strip()
|
|
60
|
+
if value in ZERO_MARKERS:
|
|
61
|
+
return "0"
|
|
62
|
+
if value in NULL_MARKERS:
|
|
63
|
+
return None
|
|
64
|
+
# German formatting: '.' is the thousands separator, ',' the decimal mark.
|
|
65
|
+
return value.replace(".", "").replace(",", ".")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _to_int(raw: str) -> int | None:
|
|
69
|
+
cleaned = _clean_number(raw)
|
|
70
|
+
if cleaned is None:
|
|
71
|
+
return None
|
|
72
|
+
try:
|
|
73
|
+
# int() directly, never through float, so large values are not rounded.
|
|
74
|
+
return int(cleaned)
|
|
75
|
+
except ValueError:
|
|
76
|
+
raise ValueError(f"expected an integer, got {raw!r}") from None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _to_float(raw: str) -> float | None:
|
|
80
|
+
cleaned = _clean_number(raw)
|
|
81
|
+
if cleaned is None:
|
|
82
|
+
return None
|
|
83
|
+
return float(cleaned)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _to_date(raw: str) -> date | None:
|
|
87
|
+
value = raw.strip()
|
|
88
|
+
if value in NULL_MARKERS:
|
|
89
|
+
return None
|
|
90
|
+
# Publisher columns are calendar dates (Stichtag), not instants; .date() drops the time,
|
|
91
|
+
# so attaching a timezone would invent precision the source does not have.
|
|
92
|
+
return datetime.strptime(value, GERMAN_DATE_FORMAT).date() # noqa: DTZ007
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _to_string(raw: str) -> str | None:
|
|
96
|
+
value = raw.strip()
|
|
97
|
+
return None if value == "" else value
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _typed_table(cells: dict[str, list[str]], spec: dict[str, ColumnType]) -> pa.Table:
|
|
101
|
+
"""Build a typed Arrow table from raw string columns and a name to type spec."""
|
|
102
|
+
arrays: dict[str, pa.Array] = {}
|
|
103
|
+
fields: list[pa.Field] = []
|
|
104
|
+
for name, ctype in spec.items():
|
|
105
|
+
if name not in cells:
|
|
106
|
+
raise KeyError(f"column {name!r} not found; available: {list(cells)}")
|
|
107
|
+
raw = cells[name]
|
|
108
|
+
if ctype is ColumnType.STRING:
|
|
109
|
+
values: list[object] = [_to_string(v) for v in raw]
|
|
110
|
+
elif ctype is ColumnType.INTEGER:
|
|
111
|
+
values = [_to_int(v) for v in raw]
|
|
112
|
+
elif ctype is ColumnType.FLOAT:
|
|
113
|
+
values = [_to_float(v) for v in raw]
|
|
114
|
+
else:
|
|
115
|
+
values = [_to_date(v) for v in raw]
|
|
116
|
+
arrays[name] = pa.array(values, type=_ARROW_TYPE[ctype])
|
|
117
|
+
fields.append(pa.field(name, _ARROW_TYPE[ctype]))
|
|
118
|
+
return pa.table(arrays, schema=pa.schema(fields))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def parse_german_csv_bytes(
|
|
122
|
+
data: bytes,
|
|
123
|
+
columns: dict[str, ColumnType] | None = None,
|
|
124
|
+
*,
|
|
125
|
+
sep: str = ";",
|
|
126
|
+
skiprows: int = 0,
|
|
127
|
+
encoding: str | None = None,
|
|
128
|
+
) -> pa.Table:
|
|
129
|
+
"""Parse single-header German-CSV ``data`` into a typed Arrow table.
|
|
130
|
+
|
|
131
|
+
``columns`` maps column name to type; when omitted every column is read as a
|
|
132
|
+
string. Unknown column names in ``columns`` raise ``KeyError``.
|
|
133
|
+
"""
|
|
134
|
+
enc = encoding or detect_encoding(data)
|
|
135
|
+
frame = pd.read_csv(
|
|
136
|
+
io.BytesIO(data),
|
|
137
|
+
sep=sep,
|
|
138
|
+
dtype=str,
|
|
139
|
+
keep_default_na=False,
|
|
140
|
+
na_values=[],
|
|
141
|
+
skiprows=skiprows,
|
|
142
|
+
encoding=enc,
|
|
143
|
+
)
|
|
144
|
+
frame.columns = pd.Index([str(name).strip() for name in frame.columns])
|
|
145
|
+
cells: dict[str, list[str]] = {
|
|
146
|
+
col: ["" if v is None else str(v) for v in frame[col].tolist()] for col in frame.columns
|
|
147
|
+
}
|
|
148
|
+
row_count = len(frame.index)
|
|
149
|
+
|
|
150
|
+
# Drop fully-empty trailing rows (a trailing newline can yield one).
|
|
151
|
+
keep = [i for i in range(row_count) if any(cells[col][i].strip() != "" for col in cells)]
|
|
152
|
+
filtered = {name: [col[i] for i in keep] for name, col in cells.items()}
|
|
153
|
+
|
|
154
|
+
spec = columns if columns is not None else {name: ColumnType.STRING for name in filtered}
|
|
155
|
+
return _typed_table(filtered, spec)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def parse_german_csv(
|
|
159
|
+
path: str | os.PathLike[str],
|
|
160
|
+
columns: dict[str, ColumnType] | None = None,
|
|
161
|
+
*,
|
|
162
|
+
sep: str = ";",
|
|
163
|
+
skiprows: int = 0,
|
|
164
|
+
encoding: str | None = None,
|
|
165
|
+
) -> pa.Table:
|
|
166
|
+
"""Read ``path`` and parse it with :func:`parse_german_csv_bytes`."""
|
|
167
|
+
with open(path, "rb") as handle:
|
|
168
|
+
data = handle.read()
|
|
169
|
+
return parse_german_csv_bytes(data, columns, sep=sep, skiprows=skiprows, encoding=encoding)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _ffill_header_row(row: list[str]) -> list[str]:
|
|
173
|
+
"""Forward-fill a header row so merged (empty) cells inherit the value to their left."""
|
|
174
|
+
out: list[str] = []
|
|
175
|
+
last = ""
|
|
176
|
+
for cell in row:
|
|
177
|
+
text = cell.strip()
|
|
178
|
+
if text:
|
|
179
|
+
last = text
|
|
180
|
+
out.append(last)
|
|
181
|
+
return out
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _flatten_header(header_rows: list[list[str]]) -> list[str]:
|
|
185
|
+
"""Combine multi-row merged headers into one unique name per column.
|
|
186
|
+
|
|
187
|
+
Trailing columns with no header cell in any row are dropped, so a universal
|
|
188
|
+
trailing delimiter does not add a phantom all-null column.
|
|
189
|
+
"""
|
|
190
|
+
ncols = 0
|
|
191
|
+
for row in header_rows:
|
|
192
|
+
for j, cell in enumerate(row):
|
|
193
|
+
if cell.strip():
|
|
194
|
+
ncols = max(ncols, j + 1)
|
|
195
|
+
# Forward-fill merged cells within each row, then pad/truncate to ncols so a
|
|
196
|
+
# writer's omitted trailing cells do not inherit a label.
|
|
197
|
+
filled = [(_ffill_header_row(row) + [""] * ncols)[:ncols] for row in header_rows]
|
|
198
|
+
names: list[str] = []
|
|
199
|
+
used: set[str] = set()
|
|
200
|
+
for j in range(ncols):
|
|
201
|
+
parts: list[str] = []
|
|
202
|
+
for row in filled:
|
|
203
|
+
part = row[j]
|
|
204
|
+
if part and (not parts or parts[-1] != part):
|
|
205
|
+
parts.append(part)
|
|
206
|
+
base = " ".join(parts) if parts else f"column_{j}"
|
|
207
|
+
name = base
|
|
208
|
+
suffix = 1
|
|
209
|
+
while name in used: # guarantee uniqueness even against pre-suffixed names
|
|
210
|
+
suffix += 1
|
|
211
|
+
name = f"{base} ({suffix})"
|
|
212
|
+
used.add(name)
|
|
213
|
+
names.append(name)
|
|
214
|
+
return names
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def parse_multi_header_csv_bytes(
|
|
218
|
+
data: bytes,
|
|
219
|
+
*,
|
|
220
|
+
sep: str = ";",
|
|
221
|
+
skiprows: int = 0,
|
|
222
|
+
header_rows: int = 1,
|
|
223
|
+
label_columns: int = 0,
|
|
224
|
+
value_type: ColumnType = ColumnType.INTEGER,
|
|
225
|
+
encoding: str | None = None,
|
|
226
|
+
) -> pa.Table:
|
|
227
|
+
"""Parse a publisher CSV with a multi-row merged header into a typed Arrow table.
|
|
228
|
+
|
|
229
|
+
Skips ``skiprows`` preamble lines, flattens the next ``header_rows`` rows into
|
|
230
|
+
unique column names, drops blank/separator rows, and types the first
|
|
231
|
+
``label_columns`` columns as strings with the rest as ``value_type``. Parsing
|
|
232
|
+
goes through the csv module, so quoted fields and line endings are handled.
|
|
233
|
+
"""
|
|
234
|
+
enc = encoding or detect_encoding(data)
|
|
235
|
+
rows = list(csv.reader(io.StringIO(data.decode(enc)), delimiter=sep))
|
|
236
|
+
header_block = rows[skiprows : skiprows + header_rows]
|
|
237
|
+
if header_rows < 1 or len(header_block) < header_rows:
|
|
238
|
+
raise ValueError("not enough header rows for the requested header_rows")
|
|
239
|
+
names = _flatten_header(header_block)
|
|
240
|
+
ncols = len(names)
|
|
241
|
+
|
|
242
|
+
cells: dict[str, list[str]] = {name: [] for name in names}
|
|
243
|
+
for row in rows[skiprows + header_rows :]:
|
|
244
|
+
if not any(cell.strip() for cell in row):
|
|
245
|
+
continue # blank or separator row (e.g. a lone ';')
|
|
246
|
+
fields = (row + [""] * ncols)[:ncols]
|
|
247
|
+
for name, value in zip(names, fields):
|
|
248
|
+
cells[name].append(value)
|
|
249
|
+
|
|
250
|
+
spec = {name: (ColumnType.STRING if i < label_columns else value_type) for i, name in enumerate(names)}
|
|
251
|
+
return _typed_table(cells, spec)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def parse_multi_header_csv(
|
|
255
|
+
path: str | os.PathLike[str],
|
|
256
|
+
*,
|
|
257
|
+
sep: str = ";",
|
|
258
|
+
skiprows: int = 0,
|
|
259
|
+
header_rows: int = 1,
|
|
260
|
+
label_columns: int = 0,
|
|
261
|
+
value_type: ColumnType = ColumnType.INTEGER,
|
|
262
|
+
encoding: str | None = None,
|
|
263
|
+
) -> pa.Table:
|
|
264
|
+
"""Read ``path`` and parse it with :func:`parse_multi_header_csv_bytes`."""
|
|
265
|
+
with open(path, "rb") as handle:
|
|
266
|
+
data = handle.read()
|
|
267
|
+
return parse_multi_header_csv_bytes(
|
|
268
|
+
data,
|
|
269
|
+
sep=sep,
|
|
270
|
+
skiprows=skiprows,
|
|
271
|
+
header_rows=header_rows,
|
|
272
|
+
label_columns=label_columns,
|
|
273
|
+
value_type=value_type,
|
|
274
|
+
encoding=encoding,
|
|
275
|
+
)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Root FeatureGroup exposing the GovData readers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from mloda.provider import BaseInputData
|
|
6
|
+
from mloda_plugins.feature_group.input_data.read_file_feature import ReadFileFeature
|
|
7
|
+
|
|
8
|
+
from .reader import BaseGovDataReader
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class GovDataFeature(ReadFileFeature):
|
|
12
|
+
"""Root FeatureGroup for GovData columns; inherits the any-framework rule to avoid resolver collisions."""
|
|
13
|
+
|
|
14
|
+
@classmethod
|
|
15
|
+
def input_data(cls) -> BaseInputData | None:
|
|
16
|
+
# The base reader, so every sibling reader subclass stays matchable via its class-name options key.
|
|
17
|
+
return BaseGovDataReader()
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Stuttgart population dataset (M1 population theme, via GovData)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import ClassVar
|
|
6
|
+
|
|
7
|
+
from .core.parse import ColumnType
|
|
8
|
+
from .reader import GovDataReader
|
|
9
|
+
|
|
10
|
+
POPULATION_SLUG = "einwohner-nach-altersgruppen-und-stadtbezirken"
|
|
11
|
+
POPULATION_SCHEMA: dict[str, ColumnType] = {
|
|
12
|
+
"Stichtag": ColumnType.DATE,
|
|
13
|
+
"Stadtbezirk": ColumnType.STRING,
|
|
14
|
+
"Alter in 10 Gruppen": ColumnType.STRING,
|
|
15
|
+
"Einwohner": ColumnType.INTEGER,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class StuttgartPopulationReader(GovDataReader):
|
|
20
|
+
"""Residents by age group and city district, with typed columns."""
|
|
21
|
+
|
|
22
|
+
schema: ClassVar[dict[str, ColumnType] | None] = POPULATION_SCHEMA
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""Base mloda reader for GovData distributions.
|
|
2
|
+
|
|
3
|
+
``BaseGovDataReader`` follows the ``CsvReader`` pattern (a ``ReadFile`` subclass):
|
|
4
|
+
it resolves a locator to a distribution, downloads it through the cache, and lets
|
|
5
|
+
the subclass parse the payload into a typed Arrow table. One module per data
|
|
6
|
+
source implements ``_parse``; ``GovDataReader`` is the generic single-header
|
|
7
|
+
German-CSV reader.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import difflib
|
|
13
|
+
import tempfile
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, ClassVar
|
|
16
|
+
|
|
17
|
+
import pyarrow as pa
|
|
18
|
+
from mloda.provider import FeatureSet
|
|
19
|
+
|
|
20
|
+
# PyArrowTable is imported for its registration side effect so "PyArrowTable" resolves; the reader
|
|
21
|
+
# returns a pyarrow Table. Public path since mloda 0.10.0 (lazy export); resolving it imports and
|
|
22
|
+
# registers the framework class.
|
|
23
|
+
from mloda.user import Options, PyArrowTable # noqa: F401
|
|
24
|
+
from mloda_plugins.feature_group.input_data.read_file import ReadFile
|
|
25
|
+
|
|
26
|
+
from .core.cache import DownloadCache
|
|
27
|
+
from .core.client import build_client
|
|
28
|
+
from .core.discovery import ResolvedDistribution, resolve_distribution
|
|
29
|
+
from .core.locator import GovDataLocator
|
|
30
|
+
from .core.parse import ColumnType, parse_german_csv
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _unknown_features_message(missing: list[str], available: list[str], locator: GovDataLocator) -> str:
|
|
34
|
+
"""Name the missing features, list what the distribution offers, and suggest close matches."""
|
|
35
|
+
target = locator.dataset_id or locator.distribution_url
|
|
36
|
+
parts = [
|
|
37
|
+
f"Unknown feature(s) {', '.join(repr(name) for name in missing)} for {target!r}.",
|
|
38
|
+
f"Available: {', '.join(sorted(available))}.",
|
|
39
|
+
]
|
|
40
|
+
for name in missing:
|
|
41
|
+
close = difflib.get_close_matches(name, available, n=1)
|
|
42
|
+
if close:
|
|
43
|
+
parts.append(f"Did you mean {close[0]!r} instead of {name!r}?")
|
|
44
|
+
return " ".join(parts)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class BaseGovDataReader(ReadFile):
|
|
48
|
+
"""Plumbing shared by every GovData reader.
|
|
49
|
+
|
|
50
|
+
Handles locator coercion, CKAN discovery, cached download with retries, and
|
|
51
|
+
column selection. Subclasses implement ``_parse`` (and override ``suffix``
|
|
52
|
+
when the payload is not CSV).
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
# Persistent, content-addressed cache location (override per environment).
|
|
56
|
+
cache_dir: ClassVar[str] = str(Path(tempfile.gettempdir()) / "mloda-govdata-cache")
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def suffix(cls) -> tuple[str, ...]:
|
|
60
|
+
return (".csv",)
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def match_subclass_data_access(cls, data_access: Any, feature_names: list[str], options: Any) -> Any:
|
|
64
|
+
return GovDataLocator.coerce(data_access)
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def load_data(cls, data_access: Any, features: FeatureSet) -> Any:
|
|
68
|
+
# Overriding load_data wholesale classifies this as a final reader (mloda >=0.10.0
|
|
69
|
+
# is_final_reader, structural, no runtime probe).
|
|
70
|
+
requested = list(features.get_all_names()) # sorted tuple since mloda 0.10.0; deterministic column order
|
|
71
|
+
locator = cls._coerce_locator(data_access)
|
|
72
|
+
table = cls._read_table(locator, features.options)
|
|
73
|
+
available = set(table.column_names)
|
|
74
|
+
missing = [name for name in requested if name not in available]
|
|
75
|
+
if missing:
|
|
76
|
+
raise ValueError(_unknown_features_message(missing, table.column_names, locator))
|
|
77
|
+
return table.select(requested)
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def peek(cls, data_access: Any) -> dict[str, str]:
|
|
81
|
+
"""Columns selectable as features for this locator, as name to Arrow type.
|
|
82
|
+
|
|
83
|
+
Downloads through the cache, so a following feature request reuses the file.
|
|
84
|
+
"""
|
|
85
|
+
table = cls._read_table(cls._coerce_locator(data_access))
|
|
86
|
+
return {field.name: str(field.type) for field in table.schema}
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def _coerce_locator(cls, data_access: Any) -> GovDataLocator:
|
|
90
|
+
locator = GovDataLocator.coerce(data_access)
|
|
91
|
+
if locator is None:
|
|
92
|
+
raise ValueError(f"{cls.__name__} cannot handle data access {data_access!r}")
|
|
93
|
+
return locator
|
|
94
|
+
|
|
95
|
+
@classmethod
|
|
96
|
+
def _read_table(cls, locator: GovDataLocator, options: Options | None = None) -> pa.Table:
|
|
97
|
+
with build_client() as client:
|
|
98
|
+
distribution = resolve_distribution(locator, client)
|
|
99
|
+
cache = DownloadCache(cls.cache_dir, client=client)
|
|
100
|
+
cached = cache.get_or_download(distribution.url)
|
|
101
|
+
return cls._parse(cached.path, locator, distribution, options)
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def _parse(
|
|
105
|
+
cls, path: Path, locator: GovDataLocator, distribution: ResolvedDistribution, options: Options | None = None
|
|
106
|
+
) -> pa.Table:
|
|
107
|
+
raise NotImplementedError(f"{cls.__name__} must implement _parse")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class GovDataReader(BaseGovDataReader):
|
|
111
|
+
"""Reads a single-header German-CSV distribution into a typed Arrow table.
|
|
112
|
+
|
|
113
|
+
``schema`` maps column name to type; ``None`` reads every column as a string.
|
|
114
|
+
Subclass and set ``schema`` for a dataset with known typed columns.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
schema: ClassVar[dict[str, ColumnType] | None] = None
|
|
118
|
+
|
|
119
|
+
@classmethod
|
|
120
|
+
def _parse(
|
|
121
|
+
cls, path: Path, locator: GovDataLocator, distribution: ResolvedDistribution, options: Options | None = None
|
|
122
|
+
) -> pa.Table:
|
|
123
|
+
return parse_german_csv(path, cls.schema)
|
|
File without changes
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Level 1: content-addressed download cache and conditional GET."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
import respx
|
|
8
|
+
|
|
9
|
+
from mloda_plugin_govdata.feature_groups.govdata.core.cache import DownloadCache
|
|
10
|
+
|
|
11
|
+
URL = "https://example.org/data.csv"
|
|
12
|
+
BODY = b"Stichtag;Wert\r\n30.06.2020;1\r\n"
|
|
13
|
+
ETAG = '"v1"'
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@respx.mock
|
|
17
|
+
def test_download_and_store(tmp_path: Path) -> None:
|
|
18
|
+
respx.get(URL).mock(return_value=httpx.Response(200, content=BODY, headers={"ETag": ETAG}))
|
|
19
|
+
with DownloadCache(tmp_path) as cache:
|
|
20
|
+
cached = cache.get_or_download(URL)
|
|
21
|
+
assert cached.path.read_bytes() == BODY
|
|
22
|
+
assert cached.sha256 == hashlib.sha256(BODY).hexdigest()
|
|
23
|
+
assert cached.etag == ETAG
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@respx.mock
|
|
27
|
+
def test_conditional_get_reuses_on_304(tmp_path: Path) -> None:
|
|
28
|
+
calls: dict[str, int] = {"n": 0}
|
|
29
|
+
|
|
30
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
31
|
+
calls["n"] += 1
|
|
32
|
+
if request.headers.get("If-None-Match") == ETAG:
|
|
33
|
+
return httpx.Response(304)
|
|
34
|
+
return httpx.Response(200, content=BODY, headers={"ETag": ETAG})
|
|
35
|
+
|
|
36
|
+
respx.get(URL).mock(side_effect=handler)
|
|
37
|
+
with DownloadCache(tmp_path) as cache:
|
|
38
|
+
first = cache.get_or_download(URL)
|
|
39
|
+
second = cache.get_or_download(URL)
|
|
40
|
+
assert calls["n"] == 2 # second call revalidated and got a 304
|
|
41
|
+
assert first.sha256 == second.sha256
|
|
42
|
+
assert second.path.read_bytes() == BODY
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@respx.mock
|
|
46
|
+
def test_corrupted_cache_redownloads(tmp_path: Path) -> None:
|
|
47
|
+
respx.get(URL).mock(return_value=httpx.Response(200, content=BODY, headers={"ETag": ETAG}))
|
|
48
|
+
with DownloadCache(tmp_path) as cache:
|
|
49
|
+
first = cache.get_or_download(URL)
|
|
50
|
+
first.path.write_bytes(b"corrupted") # tamper the stored body
|
|
51
|
+
second = cache.get_or_download(URL)
|
|
52
|
+
assert second.path.read_bytes() == BODY
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@respx.mock
|
|
56
|
+
def test_unreadable_metadata_redownloads(tmp_path: Path) -> None:
|
|
57
|
+
respx.get(URL).mock(return_value=httpx.Response(200, content=BODY, headers={"ETag": ETAG}))
|
|
58
|
+
with DownloadCache(tmp_path) as cache:
|
|
59
|
+
cache.get_or_download(URL)
|
|
60
|
+
cache._meta_path(URL).write_text("{ not valid json", encoding="utf-8") # truncated write
|
|
61
|
+
second = cache.get_or_download(URL)
|
|
62
|
+
assert second.path.read_bytes() == BODY
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Level 1: retry policy for transient transport / status failures."""
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import pytest
|
|
5
|
+
import respx
|
|
6
|
+
|
|
7
|
+
from mloda_plugin_govdata.feature_groups.govdata.core.client import (
|
|
8
|
+
RetryableStatusError,
|
|
9
|
+
build_client,
|
|
10
|
+
request_with_retry,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
URL = "https://example.org/x"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.fixture(autouse=True)
|
|
17
|
+
def _instant_backoff(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
18
|
+
# Collapse tenacity's backoff to zero so retry tests run instantly.
|
|
19
|
+
monkeypatch.setattr(
|
|
20
|
+
"mloda_plugin_govdata.feature_groups.govdata.core.client._BASE_WAIT",
|
|
21
|
+
lambda _state: 0.0,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@respx.mock
|
|
26
|
+
def test_retries_on_503_then_succeeds() -> None:
|
|
27
|
+
responses = [httpx.Response(503), httpx.Response(503), httpx.Response(200, content=b"ok")]
|
|
28
|
+
route = respx.get(URL).mock(side_effect=responses)
|
|
29
|
+
with build_client() as client:
|
|
30
|
+
response = request_with_retry(client, "GET", URL)
|
|
31
|
+
assert response.status_code == 200
|
|
32
|
+
assert route.call_count == 3
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@respx.mock
|
|
36
|
+
def test_no_retry_on_404() -> None:
|
|
37
|
+
route = respx.get(URL).mock(return_value=httpx.Response(404))
|
|
38
|
+
with build_client() as client:
|
|
39
|
+
response = request_with_retry(client, "GET", URL)
|
|
40
|
+
assert response.status_code == 404
|
|
41
|
+
assert route.call_count == 1
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@respx.mock
|
|
45
|
+
def test_gives_up_after_max_attempts() -> None:
|
|
46
|
+
route = respx.get(URL).mock(return_value=httpx.Response(503))
|
|
47
|
+
with build_client() as client, pytest.raises(RetryableStatusError):
|
|
48
|
+
request_with_retry(client, "GET", URL)
|
|
49
|
+
assert route.call_count == 5
|