mloda-plugin-govdata 0.2.1__tar.gz

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.
Files changed (35) hide show
  1. mloda_plugin_govdata-0.2.1/LICENSE +201 -0
  2. mloda_plugin_govdata-0.2.1/PKG-INFO +29 -0
  3. mloda_plugin_govdata-0.2.1/README.md +116 -0
  4. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/__init__.py +0 -0
  5. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/__init__.py +1 -0
  6. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/__init__.py +55 -0
  7. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/bundeswahlleiterin.py +48 -0
  8. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/core/__init__.py +1 -0
  9. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/core/cache.py +114 -0
  10. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/core/client.py +72 -0
  11. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/core/discovery.py +177 -0
  12. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/core/locator.py +42 -0
  13. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/core/parse.py +275 -0
  14. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/feature.py +17 -0
  15. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/population.py +22 -0
  16. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/reader.py +123 -0
  17. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/tests/__init__.py +0 -0
  18. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/tests/conftest.py +8 -0
  19. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/tests/test_cache.py +62 -0
  20. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/tests/test_client.py +49 -0
  21. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/tests/test_discovery.py +157 -0
  22. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/tests/test_parse.py +183 -0
  23. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/tests/test_parse_hypothesis.py +38 -0
  24. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/tests/test_reader.py +327 -0
  25. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/tests/test_uba.py +193 -0
  26. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata/feature_groups/govdata/uba.py +220 -0
  27. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata.egg-info/PKG-INFO +29 -0
  28. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata.egg-info/SOURCES.txt +33 -0
  29. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata.egg-info/dependency_links.txt +1 -0
  30. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata.egg-info/requires.txt +22 -0
  31. mloda_plugin_govdata-0.2.1/mloda_plugin_govdata.egg-info/top_level.txt +1 -0
  32. mloda_plugin_govdata-0.2.1/pyproject.toml +77 -0
  33. mloda_plugin_govdata-0.2.1/setup.cfg +4 -0
  34. mloda_plugin_govdata-0.2.1/tests/test_demo_definition.py +19 -0
  35. mloda_plugin_govdata-0.2.1/tests/test_mloda_imports.py +23 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,29 @@
1
+ Metadata-Version: 2.4
2
+ Name: mloda-plugin-govdata
3
+ Version: 0.2.1
4
+ Summary: mloda plugin providing connectors and harmonization for German government data (GovData.de CKAN API, Destatis GENESIS API v3).
5
+ Author-email: Tom Kaltofen <tomkaltofen@mloda.ai>
6
+ License-Expression: Apache-2.0
7
+ Requires-Python: >=3.10
8
+ License-File: LICENSE
9
+ Requires-Dist: mloda<0.11.0,>=0.10.0
10
+ Requires-Dist: mloda-testing>=0.3.1
11
+ Requires-Dist: httpx>=0.27
12
+ Requires-Dist: pandas>=2.0
13
+ Requires-Dist: pyarrow>=17.0
14
+ Requires-Dist: pydantic>=2.0
15
+ Requires-Dist: tenacity>=8.0
16
+ Provides-Extra: demo
17
+ Requires-Dist: marimo>=0.14; extra == "demo"
18
+ Provides-Extra: dev
19
+ Requires-Dist: tox; extra == "dev"
20
+ Requires-Dist: tox-uv; extra == "dev"
21
+ Requires-Dist: uv>=0.11.15; extra == "dev"
22
+ Requires-Dist: pytest; extra == "dev"
23
+ Requires-Dist: ruff; extra == "dev"
24
+ Requires-Dist: mypy; extra == "dev"
25
+ Requires-Dist: bandit; extra == "dev"
26
+ Requires-Dist: hypothesis; extra == "dev"
27
+ Requires-Dist: respx; extra == "dev"
28
+ Requires-Dist: pandas-stubs; extra == "dev"
29
+ Dynamic: license-file
@@ -0,0 +1,116 @@
1
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/mloda-ai/mloda-plugin-govdata/blob/main/LICENSE)
2
+ [![mloda](https://img.shields.io/badge/built%20with-mloda-blue.svg)](https://github.com/mloda-ai/mloda)
3
+ [![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
4
+ [![Tests](https://github.com/mloda-ai/mloda-plugin-govdata/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/mloda-ai/mloda-plugin-govdata/actions/workflows/test.yml?query=branch%3Amain)
5
+ [![Prototype Fund](https://img.shields.io/badge/Prototype%20Fund-Jahrgang%2002-f1c40f.svg)](https://prototypefund.de)
6
+
7
+ # mloda-plugin-govdata
8
+
9
+ Connectors for German open government data, built on [mloda](https://github.com/mloda-ai/mloda). Request the columns you want as mloda features; the plugin handles CKAN discovery, download with caching and retries, and parsing (German CSV or publisher JSON) into a typed Arrow table.
10
+
11
+ Three example datasets cover the M1 themes: population (GovData CSV), elections (Bundeswahlleiterin `kerg.csv`), and environment (UBA Air Data JSON).
12
+
13
+ ## Status
14
+
15
+ Young but working. All three example readers run end to end, with paginated dataset search, cached downloads with retries, and unit plus property-based tests behind them. Every reader is a thin subclass of `BaseGovDataReader` that overrides only the parse step; new datasets follow the same path (see [docs/adding-a-reader.md](docs/adding-a-reader.md)). Development happens in a 6-month Prototype Fund stage (June to November 2026), so the API may still shift between releases.
16
+
17
+ ## Usage
18
+
19
+ Read the Stuttgart population dataset (via GovData) as a typed PyArrow table:
20
+
21
+ ```python
22
+ from mloda.user import Feature, mloda
23
+ from mloda_plugin_govdata.feature_groups.govdata import StuttgartPopulationReader
24
+
25
+ slug = "einwohner-nach-altersgruppen-und-stadtbezirken"
26
+ result = mloda.run_all(
27
+ [
28
+ Feature("Einwohner", options={StuttgartPopulationReader: slug}),
29
+ Feature("Stadtbezirk", options={StuttgartPopulationReader: slug}),
30
+ ],
31
+ compute_frameworks=["PyArrowTable"],
32
+ )
33
+ table = result[0] # pyarrow.Table with the requested columns
34
+ result.plan # resolved execution steps: which FeatureGroup ran on which framework
35
+ ```
36
+
37
+ The options key is the reader class or its class-name string; both select the same reader. The option value is a GovData dataset slug or a direct distribution URL. The license is read from the CKAN distribution metadata. Set `BaseGovDataReader.cache_dir` to control where downloads are cached. For any other GovData CSV dataset, `GovDataReader` works out of the box and reads every column as a string; subclass it and set `schema` for typed columns.
38
+
39
+ Don't know the slug yet? Search GovData with the paginated CKAN `package_search` API:
40
+
41
+ ```python
42
+ from mloda_plugin_govdata.feature_groups.govdata import build_client, search_datasets
43
+
44
+ with build_client() as client:
45
+ for dataset in search_datasets(client, "einwohner stuttgart", max_results=10):
46
+ print(dataset.name, "|", dataset.title)
47
+ ```
48
+
49
+ `search_datasets` walks the result pages lazily (`page_size` per request) and stops at `max_results` or the end of the result set.
50
+
51
+ Got a slug but not the column names? `peek` lists what you can request as features:
52
+
53
+ ```python
54
+ StuttgartPopulationReader.peek(slug) # {"Stichtag": "date32[day]", "Stadtbezirk": "string", ...}
55
+ ```
56
+
57
+ It works on every reader (`BundeswahlleiterinReader.peek(kerg)`, `UbaAirReader.peek(url)`) and downloads through the cache, so the actual feature request reuses the file. A typo in a feature name fails with the available columns and a close-match suggestion instead of a raw KeyError.
58
+
59
+ The elections reader handles a direct CSV URL whose file has a multi-row merged header (Bundeswahlleiterin `kerg.csv`):
60
+
61
+ ```python
62
+ from mloda_plugin_govdata.feature_groups.govdata import BundeswahlleiterinReader
63
+
64
+ kerg = "https://www.bundeswahlleiterin.de/bundestagswahlen/2025/ergebnisse/opendata/btw25/csv/kerg.csv"
65
+ result = mloda.run_all(
66
+ [Feature("Gebiet", options={BundeswahlleiterinReader: kerg})],
67
+ compute_frameworks=["PyArrowTable"],
68
+ )
69
+ ```
70
+
71
+ The environment reader fetches the Umweltbundesamt (UBA) Air Data v4 `measures` endpoint (REST JSON) and flattens it to one typed row per station and timestamp. `uba_measures_url` builds the query (here: hourly ozone at station 143):
72
+
73
+ ```python
74
+ from mloda_plugin_govdata.feature_groups.govdata import UbaAirReader, uba_measures_url
75
+
76
+ url = uba_measures_url(station=143, component=3, scope=2, date_from="2025-01-01", date_to="2025-01-01")
77
+ result = mloda.run_all(
78
+ [
79
+ Feature("date_start", options={UbaAirReader: url}),
80
+ Feature("value", options={UbaAirReader: url}),
81
+ ],
82
+ compute_frameworks=["PyArrowTable"],
83
+ )
84
+ ```
85
+
86
+ Columns are `station_id`, `date_start`, `component_id`, `scope_id`, `value`, `date_end`, and `index` (the air-quality index). Component and scope ids come from the UBA `components` and `scopes` endpoints.
87
+
88
+ ## Demo
89
+
90
+ An interactive [marimo](https://marimo.io) notebook walks through dataset discovery and all three example datasets. The notebook lives in the repository (not in the published package), so run it from a source checkout:
91
+
92
+ ```bash
93
+ git clone https://github.com/TomKaltofen/mloda-plugin-govdata.git
94
+ cd mloda-plugin-govdata
95
+ uv sync --all-extras
96
+ uv run marimo edit demos/govdata_demo.py
97
+ ```
98
+
99
+ The notebook hits the live GovData, Bundeswahlleiterin, and UBA endpoints; downloads are cached locally after the first run.
100
+
101
+ ## Related Repositories
102
+
103
+ - **[mloda](https://github.com/mloda-ai/mloda)**: the core library this plugin builds on. You declare which features you need; mloda resolves how to compute them.
104
+
105
+ - **[mloda-registry](https://github.com/mloda-ai/mloda-registry)**: plugin registry and development guides for the mloda ecosystem.
106
+
107
+ ## Funding
108
+
109
+ Developed as part of the [Prototype Fund](https://prototypefund.de) (Round 2 / Jahrgang 02), funded by the German Federal Ministry of Research, Technology and Space (BMFTR) and supported by the [Open Knowledge Foundation Deutschland](https://okfn.de). Funding code (Förderkennzeichen): **16IS26S11**. Stage 1 funding period: 6 months from June 2026.
110
+
111
+ <p>
112
+ <img src="logos/bmftr.png" alt="Funded by the Federal Ministry of Research, Technology and Space (BMFTR)" height="110">
113
+ &nbsp;&nbsp;&nbsp;
114
+ <img src="logos/prototypefund.png" alt="Supported by the Prototype Fund" height="110">
115
+ </p>
116
+
@@ -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