mloda-plugin-govdata 0.2.4__tar.gz → 0.3.0__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 (80) hide show
  1. mloda_plugin_govdata-0.3.0/NOTICE.md +7 -0
  2. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/PKG-INFO +45 -8
  3. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/README.md +38 -5
  4. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/conftest.py +10 -0
  5. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/__init__.py +50 -0
  6. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/core/api.py +293 -0
  7. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/core/auth.py +156 -0
  8. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/core/cache.py +261 -0
  9. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/core/envelope.py +336 -0
  10. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/core/errors.py +62 -0
  11. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/core/hosts.py +62 -0
  12. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/core/parse.py +198 -0
  13. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/core/period.py +106 -0
  14. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/core/redact.py +69 -0
  15. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/locator.py +173 -0
  16. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/reader.py +68 -0
  17. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/govdata/__init__.py +8 -1
  18. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/govdata/bundeswahlleiterin.py +3 -6
  19. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/govdata/core/cache.py +155 -0
  20. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/govdata/core/client.py +46 -7
  21. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/govdata/core/locator.py +18 -0
  22. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/govdata/core/provenance.py +41 -0
  23. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/govdata/population.py +1 -1
  24. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/govdata/reader.py +58 -36
  25. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/govdata/uba.py +3 -6
  26. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/__init__.py +8 -0
  27. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/base.py +111 -0
  28. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/__init__.py +1 -0
  29. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/crosswalk.py +61 -0
  30. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/keys.py +78 -0
  31. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/land_codes.py +79 -0
  32. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/nuts.py +195 -0
  33. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/rebase.py +463 -0
  34. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/reference/__init__.py +1 -0
  35. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/reference/bbsr.py +153 -0
  36. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/reference/download.py +42 -0
  37. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/reference/eurostat.py +115 -0
  38. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/reference/gv_isys.py +110 -0
  39. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/core/reference/sources.py +72 -0
  40. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/nuts.py +111 -0
  41. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/period.py +65 -0
  42. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/harmonization/rebase.py +241 -0
  43. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/land_population_per_voter.py +75 -0
  44. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/recipes/__init__.py +24 -0
  45. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/recipes/credential_scan.py +133 -0
  46. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/recipes/frames.py +46 -0
  47. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/recipes/load.py +75 -0
  48. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/recipes/model.py +172 -0
  49. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/recipes/write.py +185 -0
  50. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata.egg-info/PKG-INFO +45 -8
  51. mloda_plugin_govdata-0.3.0/mloda_plugin_govdata.egg-info/SOURCES.txt +67 -0
  52. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata.egg-info/requires.txt +6 -1
  53. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/pyproject.toml +23 -7
  54. mloda_plugin_govdata-0.3.0/tests/test_capture_genesis_fixtures.py +149 -0
  55. mloda_plugin_govdata-0.3.0/tests/test_demo_definition.py +90 -0
  56. mloda_plugin_govdata-0.3.0/tests/test_land_join.py +101 -0
  57. mloda_plugin_govdata-0.3.0/tests/test_packaging.py +46 -0
  58. mloda_plugin_govdata-0.2.4/mloda_plugin_govdata/feature_groups/govdata/core/cache.py +0 -114
  59. mloda_plugin_govdata-0.2.4/mloda_plugin_govdata/feature_groups/govdata/tests/conftest.py +0 -8
  60. mloda_plugin_govdata-0.2.4/mloda_plugin_govdata/feature_groups/govdata/tests/test_cache.py +0 -62
  61. mloda_plugin_govdata-0.2.4/mloda_plugin_govdata/feature_groups/govdata/tests/test_client.py +0 -49
  62. mloda_plugin_govdata-0.2.4/mloda_plugin_govdata/feature_groups/govdata/tests/test_discovery.py +0 -157
  63. mloda_plugin_govdata-0.2.4/mloda_plugin_govdata/feature_groups/govdata/tests/test_parse.py +0 -183
  64. mloda_plugin_govdata-0.2.4/mloda_plugin_govdata/feature_groups/govdata/tests/test_parse_hypothesis.py +0 -38
  65. mloda_plugin_govdata-0.2.4/mloda_plugin_govdata/feature_groups/govdata/tests/test_reader.py +0 -362
  66. mloda_plugin_govdata-0.2.4/mloda_plugin_govdata/feature_groups/govdata/tests/test_uba.py +0 -301
  67. mloda_plugin_govdata-0.2.4/mloda_plugin_govdata.egg-info/SOURCES.txt +0 -33
  68. mloda_plugin_govdata-0.2.4/tests/test_demo_definition.py +0 -19
  69. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/LICENSE +0 -0
  70. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/__init__.py +0 -0
  71. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/__init__.py +0 -0
  72. {mloda_plugin_govdata-0.2.4/mloda_plugin_govdata/feature_groups/govdata/tests → mloda_plugin_govdata-0.3.0/mloda_plugin_govdata/feature_groups/destatis/core}/__init__.py +0 -0
  73. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/govdata/core/__init__.py +0 -0
  74. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/govdata/core/discovery.py +0 -0
  75. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/govdata/core/parse.py +0 -0
  76. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata/feature_groups/govdata/feature.py +0 -0
  77. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata.egg-info/dependency_links.txt +0 -0
  78. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/mloda_plugin_govdata.egg-info/top_level.txt +0 -0
  79. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/setup.cfg +0 -0
  80. {mloda_plugin_govdata-0.2.4 → mloda_plugin_govdata-0.3.0}/tests/test_mloda_imports.py +0 -0
@@ -0,0 +1,7 @@
1
+ Copyright 2026- Tom Kaltofen <tomkaltofen@mloda.ai>
2
+
3
+ This project, "mloda-plugin-govdata," is licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License. You may obtain a copy
5
+ of the License at:
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mloda-plugin-govdata
3
- Version: 0.2.4
4
- Summary: mloda plugin providing connectors and harmonization for German government data (GovData.de CKAN API, Destatis GENESIS API v3).
3
+ Version: 0.3.0
4
+ Summary: mloda plugin providing connectors, harmonization and recipes for German government data (GovData.de CKAN API, Destatis GENESIS webservice).
5
5
  Author-email: Tom Kaltofen <tomkaltofen@mloda.ai>
6
6
  License-Expression: Apache-2.0
7
7
  Project-URL: Homepage, https://github.com/mloda-ai/mloda-plugin-govdata
@@ -12,9 +12,12 @@ Project-URL: Prototype Fund, https://www.prototypefund.de/projects/mloda-plugin-
12
12
  Requires-Python: >=3.10
13
13
  Description-Content-Type: text/markdown
14
14
  License-File: LICENSE
15
- Requires-Dist: mloda<0.12.0,>=0.11.0
15
+ License-File: NOTICE.md
16
+ Requires-Dist: mloda<0.14.0,>=0.13.0
16
17
  Requires-Dist: mloda-testing>=0.3.1
18
+ Requires-Dist: filelock>=3.12
17
19
  Requires-Dist: httpx>=0.27
20
+ Requires-Dist: openpyxl>=3.1
18
21
  Requires-Dist: pandas>=2.0
19
22
  Requires-Dist: pyarrow>=17.0
20
23
  Requires-Dist: pydantic>=2.0
@@ -32,6 +35,7 @@ Requires-Dist: bandit; extra == "dev"
32
35
  Requires-Dist: hypothesis; extra == "dev"
33
36
  Requires-Dist: respx; extra == "dev"
34
37
  Requires-Dist: pandas-stubs; extra == "dev"
38
+ Requires-Dist: tomli; python_version < "3.11" and extra == "dev"
35
39
  Dynamic: license-file
36
40
 
37
41
  [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/mloda-ai/mloda-plugin-govdata/blob/main/LICENSE)
@@ -44,14 +48,16 @@ Dynamic: license-file
44
48
 
45
49
  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.
46
50
 
47
- Three example datasets cover the M1 themes: population (GovData CSV), elections (Bundeswahlleiterin `kerg.csv`), and environment (UBA Air Data JSON).
51
+ Three example datasets cover population (GovData CSV), elections (Bundeswahlleiterin `kerg.csv`), and environment (UBA Air Data JSON); the Destatis connector adds GENESIS tables, with harmonization features and recipe files on top.
48
52
 
49
53
  ## Status
50
54
 
51
- 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](https://github.com/mloda-ai/mloda-plugin-govdata/blob/main/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.
55
+ Young but working. The three example readers and the Destatis connector 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 the parse step (and the fetch step for a source with its own locator type); new datasets follow the same path (see [docs/adding-a-reader.md](https://github.com/mloda-ai/mloda-plugin-govdata/blob/main/docs/adding-a-reader.md)). How the packages fit together, and where to start for a change: [docs/architecture.md](https://github.com/mloda-ai/mloda-plugin-govdata/blob/main/docs/architecture.md). Development happens in a 6-month Prototype Fund stage (June to November 2026), so the API may still shift between releases.
52
56
 
53
57
  ## Usage
54
58
 
59
+ ### GovData readers
60
+
55
61
  Read the Stuttgart population dataset (via GovData) as a typed PyArrow table:
56
62
 
57
63
  ```python
@@ -70,7 +76,7 @@ table = result[0] # pyarrow.Table with the requested columns
70
76
  result.plan # resolved execution steps: which FeatureGroup ran on which framework
71
77
  ```
72
78
 
73
- 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.
79
+ 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 (harmonized features below use a separate `HarmonizationFeature.cache_dir`). 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.
74
80
 
75
81
  Don't know the slug yet? Search GovData with the paginated CKAN `package_search` API:
76
82
 
@@ -135,9 +141,40 @@ result = mloda.run_all(
135
141
 
136
142
  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.
137
143
 
144
+ ### Destatis
145
+
146
+ The Destatis connector reads a GENESIS table (Statistisches Bundesamt or a Regionalstatistik installation) by table code, needs a free registration (`GENESIS_TOKEN` or `GENESIS_USER` / `GENESIS_PASSWORD`; see [docs/credentials.md](docs/credentials.md)), and parses the ffcsv reply:
147
+
148
+ ```python
149
+ from mloda_plugin_govdata.feature_groups.destatis import DestatisReader
150
+
151
+ result = mloda.run_all(
152
+ [Feature("value", options={DestatisReader: "12411-0010"})], # population by Land
153
+ compute_frameworks=["PyArrowTable"],
154
+ )
155
+ ```
156
+
157
+ The option value is a bare table code (the server's default years), a `DestatisLocator`, or its dict form; the latter two narrow the selection by region, years, and classifying variables, and the dict form round-trips through a recipe file. See [docs/destatis-options.md](docs/destatis-options.md) for the full parameter table. `peek` lists the ffcsv columns the same way as the other readers.
158
+
159
+ ### Harmonization
160
+
161
+ Harmonized features chain an operation onto a reader column (`<column>__<operation>`): `value__rebased` re-bases a Kreis series onto a later Gebietsstand with the BBSR keys, `1_variable_attribute_code__nuts2024` adds NUTS codes to Kreis and Gemeinde keys, and `time__year_period` types the period. A feature with several output columns returns them as `<name>~<part>`, mloda's multi-output convention: `value__rebased~key`, `value__rebased~flag`, and so on. `value__rebased` and `__nuts2024` read their reference tables offline from `HarmonizationFeature.cache_dir`, so fetch them once first; see [docs/harmonization.md](docs/harmonization.md) for the example, the options, and the one-time fetch.
162
+
163
+ ### Recipes
164
+
165
+ A recipe file bundles the features, joins, and provenance of one run as JSON; `load_recipe` returns what `mloda.run_all` needs plus the compliance block (license, attribution, payload sha256, credential env names). Recipes ship under `recipes/` in the repository, not in the published package: the Land table, the re-based Kreis series, a rate with its denominator, the Land-level join, and the three example datasets above. See [docs/recipes.md](docs/recipes.md).
166
+
167
+ ```python
168
+ from mloda_plugin_govdata.recipes import load_recipe
169
+
170
+ recipe = load_recipe("recipes/land_population.json")
171
+ result = mloda.run_all(recipe.features, compute_frameworks=["PyArrowTable"], links=set(recipe.links))
172
+ recipe.compliance.sources[0].attribution # what to print next to the result
173
+ ```
174
+
138
175
  ## Demo
139
176
 
140
- 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:
177
+ An interactive [marimo](https://marimo.io) notebook walks through dataset discovery, all three example datasets, a Destatis table, a recipe joining two sources (population per eligible voter by Land), and a Kreis series re-based across a merger. The notebook lives in the repository (not in the published package), so run it from a source checkout:
141
178
 
142
179
  ```bash
143
180
  git clone https://github.com/mloda-ai/mloda-plugin-govdata.git
@@ -146,7 +183,7 @@ uv sync --all-extras
146
183
  uv run marimo edit demos/govdata_demo.py
147
184
  ```
148
185
 
149
- The notebook hits the live GovData, Bundeswahlleiterin, and UBA endpoints; downloads are cached locally after the first run.
186
+ The notebook hits the live GovData, Bundeswahlleiterin, UBA, and GENESIS-Online endpoints and fetches the BBSR key file; downloads are cached locally after the first run. The Destatis chapters need GENESIS-Online credentials in the environment (`GENESIS_TOKEN`, or `GENESIS_USER` and `GENESIS_PASSWORD`; see [docs/credentials.md](docs/credentials.md)) and skip themselves without them.
150
187
 
151
188
  ## Related Repositories
152
189
 
@@ -8,14 +8,16 @@
8
8
 
9
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
10
 
11
- Three example datasets cover the M1 themes: population (GovData CSV), elections (Bundeswahlleiterin `kerg.csv`), and environment (UBA Air Data JSON).
11
+ Three example datasets cover population (GovData CSV), elections (Bundeswahlleiterin `kerg.csv`), and environment (UBA Air Data JSON); the Destatis connector adds GENESIS tables, with harmonization features and recipe files on top.
12
12
 
13
13
  ## Status
14
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](https://github.com/mloda-ai/mloda-plugin-govdata/blob/main/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.
15
+ Young but working. The three example readers and the Destatis connector 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 the parse step (and the fetch step for a source with its own locator type); new datasets follow the same path (see [docs/adding-a-reader.md](https://github.com/mloda-ai/mloda-plugin-govdata/blob/main/docs/adding-a-reader.md)). How the packages fit together, and where to start for a change: [docs/architecture.md](https://github.com/mloda-ai/mloda-plugin-govdata/blob/main/docs/architecture.md). Development happens in a 6-month Prototype Fund stage (June to November 2026), so the API may still shift between releases.
16
16
 
17
17
  ## Usage
18
18
 
19
+ ### GovData readers
20
+
19
21
  Read the Stuttgart population dataset (via GovData) as a typed PyArrow table:
20
22
 
21
23
  ```python
@@ -34,7 +36,7 @@ table = result[0] # pyarrow.Table with the requested columns
34
36
  result.plan # resolved execution steps: which FeatureGroup ran on which framework
35
37
  ```
36
38
 
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.
39
+ 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 (harmonized features below use a separate `HarmonizationFeature.cache_dir`). 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
40
 
39
41
  Don't know the slug yet? Search GovData with the paginated CKAN `package_search` API:
40
42
 
@@ -99,9 +101,40 @@ result = mloda.run_all(
99
101
 
100
102
  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.
101
103
 
104
+ ### Destatis
105
+
106
+ The Destatis connector reads a GENESIS table (Statistisches Bundesamt or a Regionalstatistik installation) by table code, needs a free registration (`GENESIS_TOKEN` or `GENESIS_USER` / `GENESIS_PASSWORD`; see [docs/credentials.md](docs/credentials.md)), and parses the ffcsv reply:
107
+
108
+ ```python
109
+ from mloda_plugin_govdata.feature_groups.destatis import DestatisReader
110
+
111
+ result = mloda.run_all(
112
+ [Feature("value", options={DestatisReader: "12411-0010"})], # population by Land
113
+ compute_frameworks=["PyArrowTable"],
114
+ )
115
+ ```
116
+
117
+ The option value is a bare table code (the server's default years), a `DestatisLocator`, or its dict form; the latter two narrow the selection by region, years, and classifying variables, and the dict form round-trips through a recipe file. See [docs/destatis-options.md](docs/destatis-options.md) for the full parameter table. `peek` lists the ffcsv columns the same way as the other readers.
118
+
119
+ ### Harmonization
120
+
121
+ Harmonized features chain an operation onto a reader column (`<column>__<operation>`): `value__rebased` re-bases a Kreis series onto a later Gebietsstand with the BBSR keys, `1_variable_attribute_code__nuts2024` adds NUTS codes to Kreis and Gemeinde keys, and `time__year_period` types the period. A feature with several output columns returns them as `<name>~<part>`, mloda's multi-output convention: `value__rebased~key`, `value__rebased~flag`, and so on. `value__rebased` and `__nuts2024` read their reference tables offline from `HarmonizationFeature.cache_dir`, so fetch them once first; see [docs/harmonization.md](docs/harmonization.md) for the example, the options, and the one-time fetch.
122
+
123
+ ### Recipes
124
+
125
+ A recipe file bundles the features, joins, and provenance of one run as JSON; `load_recipe` returns what `mloda.run_all` needs plus the compliance block (license, attribution, payload sha256, credential env names). Recipes ship under `recipes/` in the repository, not in the published package: the Land table, the re-based Kreis series, a rate with its denominator, the Land-level join, and the three example datasets above. See [docs/recipes.md](docs/recipes.md).
126
+
127
+ ```python
128
+ from mloda_plugin_govdata.recipes import load_recipe
129
+
130
+ recipe = load_recipe("recipes/land_population.json")
131
+ result = mloda.run_all(recipe.features, compute_frameworks=["PyArrowTable"], links=set(recipe.links))
132
+ recipe.compliance.sources[0].attribution # what to print next to the result
133
+ ```
134
+
102
135
  ## Demo
103
136
 
104
- 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:
137
+ An interactive [marimo](https://marimo.io) notebook walks through dataset discovery, all three example datasets, a Destatis table, a recipe joining two sources (population per eligible voter by Land), and a Kreis series re-based across a merger. The notebook lives in the repository (not in the published package), so run it from a source checkout:
105
138
 
106
139
  ```bash
107
140
  git clone https://github.com/mloda-ai/mloda-plugin-govdata.git
@@ -110,7 +143,7 @@ uv sync --all-extras
110
143
  uv run marimo edit demos/govdata_demo.py
111
144
  ```
112
145
 
113
- The notebook hits the live GovData, Bundeswahlleiterin, and UBA endpoints; downloads are cached locally after the first run.
146
+ The notebook hits the live GovData, Bundeswahlleiterin, UBA, and GENESIS-Online endpoints and fetches the BBSR key file; downloads are cached locally after the first run. The Destatis chapters need GENESIS-Online credentials in the environment (`GENESIS_TOKEN`, or `GENESIS_USER` and `GENESIS_PASSWORD`; see [docs/credentials.md](docs/credentials.md)) and skip themselves without them.
114
147
 
115
148
  ## Related Repositories
116
149
 
@@ -0,0 +1,10 @@
1
+ """Shared pytest fixtures for every ``tests/`` package under ``mloda_plugin_govdata``."""
2
+
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+
8
+ @pytest.fixture
9
+ def fixtures_dir(request: pytest.FixtureRequest) -> Path:
10
+ return Path(request.path).parent / "fixtures"
@@ -0,0 +1,50 @@
1
+ """Destatis GENESIS connector: ``DestatisReader`` reads the table selection a ``DestatisLocator`` names.
2
+
3
+ GENESIS is the database software and its REST API. ``genesis`` (GENESIS-Online, Destatis) and ``regionalstatistik``
4
+ (Regionaldatenbank, run by IT.NRW) are two installations of it, each with its own registration. By convention
5
+ ``Destatis*`` classes face mloda and ``Genesis*`` classes speak the protocol; ``OPTION_GENESIS_CREDENTIALS`` is an
6
+ mloda option despite its name.
7
+ """
8
+
9
+ from .core.api import GenesisClient
10
+ from .core.auth import OPTION_GENESIS_CREDENTIALS, DestatisCredentials
11
+ from .core.errors import (
12
+ GenesisAuthError,
13
+ GenesisBackendError,
14
+ GenesisEmptySelection,
15
+ GenesisError,
16
+ GenesisJobAccepted,
17
+ GenesisMaintenance,
18
+ GenesisResultTooLarge,
19
+ GenesisUnknownEnvelope,
20
+ GenesisUnknownTable,
21
+ MissingCredentialsError,
22
+ WrongHostCredentialsError,
23
+ )
24
+ from .core.hosts import GENESIS_ONLINE, REGIONALSTATISTIK, GenesisHost
25
+ from .core.parse import parse_ffcsv_zip
26
+ from .locator import DestatisLocator
27
+ from .reader import DestatisReader
28
+
29
+ __all__ = [
30
+ "GENESIS_ONLINE",
31
+ "OPTION_GENESIS_CREDENTIALS",
32
+ "REGIONALSTATISTIK",
33
+ "DestatisCredentials",
34
+ "DestatisLocator",
35
+ "DestatisReader",
36
+ "GenesisAuthError",
37
+ "GenesisBackendError",
38
+ "GenesisClient",
39
+ "GenesisEmptySelection",
40
+ "GenesisError",
41
+ "GenesisHost",
42
+ "GenesisJobAccepted",
43
+ "GenesisMaintenance",
44
+ "GenesisResultTooLarge",
45
+ "GenesisUnknownEnvelope",
46
+ "GenesisUnknownTable",
47
+ "MissingCredentialsError",
48
+ "WrongHostCredentialsError",
49
+ "parse_ffcsv_zip",
50
+ ]
@@ -0,0 +1,293 @@
1
+ """GENESIS client: header credentials, form-encoded POST, pinned language, one request at a time.
2
+
3
+ Politeness: a per-host ``threading.Lock`` serializes calls inside one process, and a
4
+ ``filelock.FileLock`` in the cache directory serializes across processes that share it. mloda's
5
+ ``THREADING`` mode runs feature groups in threads of one process; ``MULTIPROCESSING`` spawns one
6
+ fresh interpreter per compute framework instance, so only the file lock reaches those.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import os
13
+ import threading
14
+ from collections.abc import Iterator, Mapping
15
+ from contextlib import contextmanager
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ import httpx
21
+ from filelock import FileLock, Timeout
22
+
23
+ from ...govdata.core.cache import DEFAULT_CACHE_DIR
24
+ from ...govdata.core.client import OwnedHttpClient, RetryableStatusError, build_client, send_with_retry
25
+ from .auth import DestatisCredentials, resolve_credentials
26
+ from .envelope import (
27
+ GenesisEnvelope,
28
+ HelloWorldReply,
29
+ InspectedReply,
30
+ LoginCheckReply,
31
+ inspect_response,
32
+ )
33
+ from .errors import GenesisBackendError, GenesisError, GenesisUnknownEnvelope, MissingCredentialsError
34
+ from .hosts import GENESIS_ONLINE, GenesisHost, resolve_host
35
+ from .redact import redact_text
36
+
37
+ __all__ = [
38
+ "OPERATIONS",
39
+ "GenesisClient",
40
+ "Operation",
41
+ "fetch_tablefile",
42
+ ]
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+ DEFAULT_LANGUAGE = "de"
47
+ LOCK_FILE_NAME = "genesis-{host}.lock"
48
+ # One attempt holds the lock for at most connect plus read timeout; anything longer is a stuck holder.
49
+ LOCK_TIMEOUT_SECONDS = 300.0
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class Operation:
54
+ """One webservice operation as the client may call it; the contract test checks it against the spec."""
55
+
56
+ path: str # relative to the host base URL, e.g. "data/tablefile"
57
+ method: str # "GET" or "POST"
58
+ credentials: bool # username / password headers declared (and required)
59
+ fields: frozenset[str] # form fields (POST) or query parameters (GET) the client may send
60
+
61
+
62
+ CLASSIFYING_VARIABLES: tuple[str, ...] = tuple(f"classifyingvariable{i}" for i in range(1, 6))
63
+ CLASSIFYING_KEYS: tuple[str, ...] = tuple(f"classifyingkey{i}" for i in range(1, 6))
64
+
65
+ TABLEFILE_FIELDS: frozenset[str] = frozenset(
66
+ {
67
+ "name",
68
+ "area",
69
+ "compress",
70
+ "transpose",
71
+ "contents",
72
+ "startyear",
73
+ "endyear",
74
+ "timeslices",
75
+ "regionalvariable",
76
+ "regionalkey",
77
+ *CLASSIFYING_VARIABLES,
78
+ *CLASSIFYING_KEYS,
79
+ "format",
80
+ "quality",
81
+ "job",
82
+ "stand",
83
+ "language",
84
+ }
85
+ )
86
+ # Sent on every data/tablefile request; not locator fields (see docs/destatis-options.md).
87
+ PINNED_TABLEFILE_FIELDS: Mapping[str, str] = {
88
+ "format": "ffcsv",
89
+ "job": "false",
90
+ "compress": "false",
91
+ "transpose": "false",
92
+ }
93
+
94
+ OPERATIONS: dict[str, Operation] = {
95
+ "helloworld/whoami": Operation("helloworld/whoami", "GET", credentials=False, fields=frozenset()),
96
+ "helloworld/logincheck": Operation(
97
+ "helloworld/logincheck", "POST", credentials=True, fields=frozenset({"language"})
98
+ ),
99
+ "catalogue/qualitysigns": Operation(
100
+ "catalogue/qualitysigns", "GET", credentials=False, fields=frozenset({"language"})
101
+ ),
102
+ "metadata/table": Operation(
103
+ "metadata/table", "POST", credentials=True, fields=frozenset({"name", "area", "language"})
104
+ ),
105
+ "data/tablefile": Operation("data/tablefile", "POST", credentials=True, fields=TABLEFILE_FIELDS),
106
+ }
107
+
108
+ _process_locks: dict[tuple[str, str], threading.Lock] = {}
109
+ _process_locks_guard = threading.Lock()
110
+
111
+
112
+ def _process_lock(host: GenesisHost) -> threading.Lock:
113
+ with _process_locks_guard:
114
+ return _process_locks.setdefault((host.name, host.base_url), threading.Lock())
115
+
116
+
117
+ class GenesisClient(OwnedHttpClient):
118
+ """Calls one GENESIS host. Credentials resolve lazily (explicit, then env) on the first call that needs them."""
119
+
120
+ def __init__(
121
+ self,
122
+ host: GenesisHost | str = GENESIS_ONLINE,
123
+ credentials: DestatisCredentials | None = None,
124
+ *,
125
+ client: httpx.Client | None = None,
126
+ language: str = DEFAULT_LANGUAGE,
127
+ lock_dir: str | os.PathLike[str] | None = None,
128
+ environ: Mapping[str, str] | None = None,
129
+ allow_guest: bool = False,
130
+ ) -> None:
131
+ self.host = resolve_host(host)
132
+ self.language = language
133
+ self._explicit = credentials
134
+ self._credentials: DestatisCredentials | None = None
135
+ self._environ = environ
136
+ # Guest calls send no credential headers; only for characterizing replies (the capture script).
137
+ self.allow_guest = allow_guest
138
+ self._owns_client = client is None
139
+ # Redirects are also disabled per request, so an injected client cannot re-enable them.
140
+ self._client = client if client is not None else build_client(follow_redirects=False)
141
+ lock_root = Path(lock_dir) if lock_dir is not None else DEFAULT_CACHE_DIR
142
+ self.lock_path = lock_root / LOCK_FILE_NAME.format(host=self.host.name)
143
+
144
+ @property
145
+ def credentials(self) -> DestatisCredentials:
146
+ """Resolved credentials for this host; raises MissingCredentialsError when none are configured."""
147
+ if self._credentials is None:
148
+ self._credentials = resolve_credentials(self.host, self._explicit, self._environ)
149
+ return self._credentials
150
+
151
+ def _auth_headers(self) -> dict[str, str]:
152
+ if self.allow_guest and self._explicit is None:
153
+ try:
154
+ configured = DestatisCredentials.from_env(self.host, self._environ)
155
+ except MissingCredentialsError:
156
+ configured = None # a half-set env pair still runs as guest here
157
+ if configured is None:
158
+ return {}
159
+ return self.credentials.headers()
160
+
161
+ @contextmanager
162
+ def _serialized(self) -> Iterator[None]:
163
+ """One attempt at a time per host: this process's threads, then every process sharing the lock file."""
164
+ self.lock_path.parent.mkdir(parents=True, exist_ok=True)
165
+ with _process_lock(self.host):
166
+ try:
167
+ with FileLock(str(self.lock_path), timeout=LOCK_TIMEOUT_SECONDS):
168
+ yield
169
+ except Timeout:
170
+ raise GenesisBackendError(
171
+ f"Another process has held the GENESIS lock {self.lock_path} for more than {LOCK_TIMEOUT_SECONDS:g} s; "
172
+ "wait for it or remove a stale lock file."
173
+ ) from None
174
+
175
+ def request(self, endpoint: str, params: Mapping[str, str] | None = None) -> httpx.Response:
176
+ """One request, each attempt under the lock; ``language`` is always sent, unknown fields are refused."""
177
+ try:
178
+ operation = OPERATIONS[endpoint]
179
+ except KeyError:
180
+ raise ValueError(
181
+ f"Unknown GENESIS operation {endpoint!r}; known: {', '.join(sorted(OPERATIONS))}"
182
+ ) from None
183
+ sent: dict[str, str] = {}
184
+ for key, value in (params or {}).items():
185
+ if not isinstance(value, str):
186
+ # The wire wants strings; str(True) would send "True" where the spec expects "true".
187
+ raise TypeError(f"{endpoint}: value for {key!r} must be a str, got {type(value).__name__}")
188
+ sent[str(key)] = value
189
+ if "language" in operation.fields:
190
+ sent.setdefault("language", self.language)
191
+ unknown = sorted(set(sent) - operation.fields)
192
+ if unknown:
193
+ raise ValueError(f"{endpoint} does not declare {unknown}; allowed: {sorted(operation.fields)}")
194
+ headers = self._auth_headers() if operation.credentials else {}
195
+ url = self.host.url(operation.path)
196
+ kwargs: dict[str, Any] = {"headers": headers, "follow_redirects": False}
197
+ if operation.method == "GET":
198
+ kwargs["params"] = sent
199
+ else:
200
+ kwargs["data"] = sent
201
+
202
+ def attempt() -> httpx.Response:
203
+ with self._serialized():
204
+ return self._client.request(operation.method, url, **kwargs)
205
+
206
+ try:
207
+ return send_with_retry(attempt)
208
+ except RetryableStatusError as exc:
209
+ raise GenesisBackendError(
210
+ f"GENESIS kept answering HTTP {exc.response.status_code} on {endpoint}; retry later.",
211
+ endpoint=endpoint,
212
+ http_status=exc.response.status_code,
213
+ ) from None
214
+
215
+ def call(self, endpoint: str, params: Mapping[str, str] | None = None) -> InspectedReply:
216
+ """Request plus envelope inspection; JSON replies come back parsed, error statuses raise (redacted)."""
217
+ response = self.request(endpoint, params)
218
+ try:
219
+ if response.is_redirect:
220
+ raise GenesisUnknownEnvelope(
221
+ f"GENESIS redirected {endpoint} to {response.headers.get('location', '?')}; the base URL is stale. "
222
+ "Credentials are not sent across redirects.",
223
+ endpoint=endpoint,
224
+ http_status=response.status_code,
225
+ )
226
+ inspected = inspect_response(response, endpoint, host=self.host)
227
+ except GenesisError as exc:
228
+ self._redact(exc)
229
+ raise
230
+ if isinstance(inspected.reply, GenesisEnvelope) and inspected.reply.status.is_warning:
231
+ logger.warning("GENESIS %s: %s", endpoint, redact_text(inspected.reply.status.content, self._secrets()))
232
+ return inspected
233
+
234
+ def _secrets(self) -> tuple[str, ...]:
235
+ known = self._credentials if self._credentials is not None else self._explicit
236
+ return known.secrets() if known is not None else ()
237
+
238
+ def _redact(self, exc: GenesisError) -> None:
239
+ """Server text quoted in an exception may echo a credential; scrub it with the known secrets."""
240
+ secrets = self._secrets()
241
+ if not secrets:
242
+ return
243
+ exc.args = tuple(redact_text(arg, secrets) if isinstance(arg, str) else arg for arg in exc.args)
244
+ if exc.status_block is not None:
245
+ exc.status_block = {
246
+ k: redact_text(v, secrets) if isinstance(v, str) else v for k, v in exc.status_block.items()
247
+ }
248
+
249
+ def whoami(self) -> HelloWorldReply:
250
+ reply = self.call("helloworld/whoami").reply
251
+ if not isinstance(reply, HelloWorldReply):
252
+ raise GenesisUnknownEnvelope("whoami did not answer with a User-Agent object", endpoint="helloworld/whoami")
253
+ return reply
254
+
255
+ def logincheck(self) -> LoginCheckReply:
256
+ """Proves the credentials: raises GenesisAuthError on guest or rejected, GenesisBackendError on the outage text."""
257
+ reply = self.call("helloworld/logincheck").reply
258
+ if not isinstance(reply, LoginCheckReply):
259
+ raise GenesisUnknownEnvelope(
260
+ "logincheck did not answer with the flat Status/Username reply", endpoint="helloworld/logincheck"
261
+ )
262
+ return reply
263
+
264
+ def qualitysigns(self) -> GenesisEnvelope:
265
+ """The value-marker legend (``List`` of ``Code``/``Content``); no credentials needed."""
266
+ return self._envelope("catalogue/qualitysigns", None)
267
+
268
+ def metadata_table(self, name: str) -> GenesisEnvelope:
269
+ """``metadata/table`` for one table code; ``area`` stays at the server default."""
270
+ return self._envelope("metadata/table", {"name": name})
271
+
272
+ def _envelope(self, endpoint: str, params: Mapping[str, str] | None) -> GenesisEnvelope:
273
+ reply = self.call(endpoint, params).reply
274
+ if not isinstance(reply, GenesisEnvelope):
275
+ raise GenesisUnknownEnvelope(f"{endpoint} did not answer with the nested envelope", endpoint=endpoint)
276
+ return reply
277
+
278
+
279
+ def fetch_tablefile(client: GenesisClient, parameters: Mapping[str, str]) -> bytes:
280
+ """POSTs ``data/tablefile`` with already-canonical ``parameters`` and returns the zip body.
281
+
282
+ Meant as the ``fetch`` callback for ``ParameterCache.get_or_fetch``. The envelope and HTTP
283
+ status are inspected by ``GenesisClient.call`` before this looks at the reply kind; raises if
284
+ GENESIS answers with anything other than a zip payload.
285
+ """
286
+ inspected = client.call("data/tablefile", parameters)
287
+ if inspected.kind != "zip":
288
+ raise GenesisUnknownEnvelope(
289
+ "data/tablefile did not answer with a zip payload",
290
+ endpoint="data/tablefile",
291
+ http_status=inspected.http_status,
292
+ )
293
+ return inspected.body