ethux commited on
Commit
6fb01b2
·
verified ·
1 Parent(s): cb98f38

2026-10 update

Browse files
LICENSE.md ADDED
@@ -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.
README.md CHANGED
@@ -2,15 +2,47 @@
2
  license: apache-2.0
3
  language:
4
  - nl
 
 
 
5
  size_categories:
6
  - 1K<n<10K
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  ---
8
 
9
  # Dutch GOV Belastingdienst
10
 
11
- This dataset is created by scraping https://www.belastingdienst.nl/, I used the titemap to get all possible allowed URLS.
12
- It possible some URLS are missing.
13
- The reason for creating this dataset is I couldn't find any other existing dataset with this data.
14
- So here is this dataset, Enjoy!
15
 
16
- ### Please note this dataset is not complety checked or cleaned, this was a personal research project.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  license: apache-2.0
3
  language:
4
  - nl
5
+ - en
6
+ - de
7
+ pretty_name: Dutch GOV Belastingdienst
8
  size_categories:
9
  - 1K<n<10K
10
+ task_categories:
11
+ - text-generation
12
+ - question-answering
13
+ tags:
14
+ - tax
15
+ - dutch
16
+ - government
17
+ configs:
18
+ - config_name: pages
19
+ default: true
20
+ data_files: data/pages/*.parquet
21
+ - config_name: raw
22
+ data_files: data/raw/*.parquet
23
+ - config_name: legacy
24
+ data_files: data/legacy/belastingdienst.csv
25
  ---
26
 
27
  # Dutch GOV Belastingdienst
28
 
29
+ Public pages of [belastingdienst.nl](https://www.belastingdienst.nl) (the Dutch Tax Administration), from both sitemaps
30
+ listed in its robots.txt. Rebuilt monthly; each run is tagged `YYYY-MM`.
 
 
31
 
32
+ | Config | One row per | Use |
33
+ |---|---|---|
34
+ | `pages` (default) | page, main content as Markdown | training, RAG (pages are short) |
35
+ | `raw` | page, original HTML | lossless source |
36
+ | `legacy` | 2024 scrape (`belastingdienst.csv`), unmaintained | old version |
37
+
38
+ ```python
39
+ from datasets import load_dataset
40
+
41
+ pages = load_dataset("ethux/belastingdienst-dataset", split="train")
42
+ ```
43
+
44
+ Columns: [documentation/schema.md](documentation/schema.md). Source and method: [documentation/source.md](documentation/source.md).
45
+ Run history: [documentation/changelog.md](documentation/changelog.md).
46
+
47
+ Built by [ethux/Dutch-GOV-Datasets](https://github.com/ethux/Dutch-GOV-Datasets). Not an official Belastingdienst
48
+ publication; check belastingdienst.nl before relying on a text.
data/pages/pages-00000-of-00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7f56983e76f3909fe71db50a6e97b1af8bd10e51dfd2b98d4c08233348047f89
3
+ size 713212
data/pages/pages-00001-of-00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a3702f63245cff1ff498ec1a5fcbf83e55414e7ec580ed833bd12505a4f671c
3
+ size 662938
data/pages/pages-00002-of-00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6f19b485f00b5ed21797dd89a86e853df4894d337b0151f5927944c89269d2ac
3
+ size 650858
data/pages/pages-00003-of-00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:634fed5347485c5fc2c1b7110e1f0b5fae726f25514e6b311b50a61c5b094e08
3
+ size 666412
data/raw/raw-00000-of-00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b3a3a43f15bb306ecfc76b609f60c140b202c4b8ece63b989d44b1e871992860
3
+ size 1580856
data/raw/raw-00001-of-00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:961a783859f7b4acb676bcb5a7a9ab4c034428e97b11f9a8cc8b5286cededd21
3
+ size 1463074
data/raw/raw-00002-of-00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:491ed720a0e7addc79d06301a25b36f0816630a9a0d00c0c5e2504642dc7b6cb
3
+ size 1454377
data/raw/raw-00003-of-00004.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0830c5f404a9ad2bfe04c373c2ddef0b09ddf12179530d44a00b605e7008305c
3
+ size 1466186
documentation/changelog.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ One row per monthly run. Rows = row count per config.
4
+
5
+ | Run date | Complete | Rows | Added | Changed | Removed | Failed | Pending |
6
+ |---|---|---|---|---|---|---|---|
7
+ | 2026-10-01 | yes | raw=8431, pages=8428 | 8431 | 0 | 0 | 0 | 0 |
documentation/schema.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Schema
2
+
3
+ ## `pages`
4
+
5
+ | Column | Example | Notes |
6
+ |---|---|---|
7
+ | `url` | `https://www.belastingdienst.nl/wps/wcm/connect/nl/schenken/content/wie-betaalt-de-schenkbelasting` | |
8
+ | `title` | `Wie betaalt de schenkbelasting?` | |
9
+ | `topic` | `schenken` | from the URL path |
10
+ | `language` | `nl` | `nl`, `en` or `de`, from the URL path |
11
+ | `audience` | `particulier` | `particulier`, `zakelijk`, `intermediair` or null |
12
+ | `lastmod` | `2026-03-11T14:30:04+01:00` | from the sitemap |
13
+ | `text` | | main content as Markdown, navigation removed |
14
+
15
+ Pages without extractable content are left out of `pages` but kept in `raw`.
16
+
17
+ ## `raw`
18
+
19
+ | Column | Notes |
20
+ |---|---|
21
+ | `url`, `lastmod` | as above |
22
+ | `fetched_at` | UTC timestamp of the download |
23
+ | `html` | original HTML |
documentation/source.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Source
2
+
3
+ - Page list: the sitemaps named in `https://www.belastingdienst.nl/robots.txt`
4
+ (`sitemap-dv.xml`: questions and answers; `sitemap-bieb.xml`: brochures, forms, publications).
5
+ - URLs disallowed by robots.txt are skipped. Requests are limited to 2 per second.
6
+ - Monthly runs only download pages that are new or whose sitemap `lastmod` changed.
7
+ - Text is extracted with [trafilatura](https://trafilatura.readthedocs.io). Linked PDFs are not included.
documentation/stats.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "run_date": "2026-10-01",
3
+ "complete": true,
4
+ "counts": {
5
+ "raw": 8431,
6
+ "pages": 8428
7
+ },
8
+ "added": 8431,
9
+ "changed": 0,
10
+ "removed": 0,
11
+ "failed": 0,
12
+ "pending": 0
13
+ }
scripts/README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # scripts
2
+
3
+ Copy of the scraper that built this dataset. Source and instructions: https://github.com/ethux/Dutch-GOV-Datasets
scripts/govdata/__init__.py ADDED
File without changes
scripts/govdata/belastingdienst/__init__.py ADDED
File without changes
scripts/govdata/belastingdienst/extract.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import trafilatura
4
+
5
+ AUDIENCE = {
6
+ "prive": "particulier",
7
+ "individuals": "particulier",
8
+ "privatpersonen": "particulier",
9
+ "zakelijk": "zakelijk",
10
+ "business": "zakelijk",
11
+ "unternehmen": "zakelijk",
12
+ "intermediairs": "intermediair",
13
+ "intermediaries": "intermediair",
14
+ }
15
+ CONTENT = re.compile(r"/wps/wcm/connect/(?:bldcontent(nl|en|de)|(nl|en|de))/(.*)")
16
+
17
+
18
+ def classify(url: str) -> tuple[str | None, str | None, str | None]:
19
+ """(topic, language, audience) from the URL path."""
20
+ m = CONTENT.search(url)
21
+ if not m:
22
+ return None, None, None
23
+ language = m.group(1) or m.group(2)
24
+ parts = [p for p in m.group(3).split("/") if p]
25
+ if m.group(1) and parts and parts[0] in ("belastingdienst", "standaard_functies", "themaoverstijgend"):
26
+ parts = parts[1:]
27
+ audience = AUDIENCE.get(parts[0]) if parts else None
28
+ if audience and m.group(1) and len(parts) > 2:
29
+ parts = parts[1:]
30
+ return (parts[0] if parts else None), language, audience
31
+
32
+
33
+ def extract_page(html: str, url: str) -> dict | None:
34
+ text = trafilatura.extract(
35
+ html, url=url, output_format="markdown", include_tables=True, include_comments=False, favor_precision=True
36
+ )
37
+ if not text or not text.strip():
38
+ return None
39
+ meta = trafilatura.extract_metadata(html, default_url=url)
40
+ title = meta.title.strip() if meta and meta.title else None
41
+ return {"title": title, "text": text.strip()}
scripts/govdata/belastingdienst/index.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Page list from the sitemaps named in belastingdienst.nl/robots.txt."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from lxml import etree
6
+
7
+ from govdata.common.http import Fetcher
8
+
9
+ BASE = "https://www.belastingdienst.nl"
10
+ SM = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Page:
15
+ url: str
16
+ lastmod: str
17
+
18
+
19
+ def sitemap_urls(robots_txt: str) -> list[str]:
20
+ return [
21
+ line.split(":", 1)[1].strip()
22
+ for line in robots_txt.splitlines()
23
+ if line.lower().startswith("sitemap:")
24
+ ]
25
+
26
+
27
+ def parse_sitemap(xml: bytes) -> tuple[list[tuple[str, str]], list[str]]:
28
+ """(page url, lastmod) pairs, and nested sitemap urls when this is a sitemap index."""
29
+ root = etree.fromstring(xml)
30
+ urls = [
31
+ (u.findtext(f"{SM}loc").strip(), (u.findtext(f"{SM}lastmod") or "").strip())
32
+ for u in root.iter(f"{SM}url")
33
+ if u.findtext(f"{SM}loc")
34
+ ]
35
+ subs = [s.findtext(f"{SM}loc").strip() for s in root.iter(f"{SM}sitemap") if s.findtext(f"{SM}loc")]
36
+ return urls, subs
37
+
38
+
39
+ def fetch_index(fetcher: Fetcher, limit: int | None = None) -> dict[str, Page]:
40
+ todo = sitemap_urls(fetcher.get(f"{BASE}/robots.txt").text)
41
+ if not todo:
42
+ raise RuntimeError("no sitemaps listed in robots.txt")
43
+ seen: set[str] = set()
44
+ out: dict[str, Page] = {}
45
+ while todo:
46
+ sm = todo.pop(0)
47
+ if sm in seen:
48
+ continue
49
+ seen.add(sm)
50
+ urls, subs = parse_sitemap(fetcher.get(sm).content)
51
+ todo += subs
52
+ for url, lastmod in urls:
53
+ if url not in out and fetcher.allowed(url):
54
+ out[url] = Page(url, lastmod)
55
+ return dict(list(out.items())[:limit]) if limit else out
scripts/govdata/belastingdienst/source.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timezone
2
+
3
+ import pyarrow as pa
4
+
5
+ from govdata.belastingdienst import extract
6
+ from govdata.belastingdienst.index import Page, fetch_index
7
+ from govdata.common.http import Fetcher
8
+
9
+ S = pa.string()
10
+ PAGES = pa.schema(
11
+ [("url", S), ("title", S), ("topic", S), ("language", S), ("audience", S), ("lastmod", S), ("text", S)]
12
+ )
13
+
14
+
15
+ class Belastingdienst:
16
+ name = "belastingdienst"
17
+ repo_id = "ethux/belastingdienst-dataset"
18
+ n_shards = 4
19
+ key_col = "url"
20
+ mod_col = "lastmod"
21
+ shard_col = "url"
22
+ raw_schema = pa.schema([("url", S), ("lastmod", S), ("fetched_at", S), ("html", S)])
23
+ configs = {"pages": PAGES}
24
+ rate = 2.0
25
+ robots_exempt = frozenset()
26
+ legacy = ("belastingdienst.csv", "data/legacy/belastingdienst.csv")
27
+
28
+ def index(self, fetcher: Fetcher, limit: int | None) -> dict[str, Page]:
29
+ return fetch_index(fetcher, limit)
30
+
31
+ def modified(self, rec: Page) -> str:
32
+ return rec.lastmod
33
+
34
+ def fetch(self, fetcher: Fetcher, key: str, rec: Page) -> dict:
35
+ r = fetcher.get(key)
36
+ return {
37
+ "url": key,
38
+ "lastmod": rec.lastmod,
39
+ "fetched_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
40
+ "html": r.text,
41
+ }
42
+
43
+ def build(self, raw: pa.Table, index: dict[str, Page], run_date: str) -> dict[str, list[dict]]:
44
+ pages = []
45
+ for row in raw.to_pylist():
46
+ page = extract.extract_page(row["html"], row["url"])
47
+ if page is None:
48
+ continue
49
+ topic, language, audience = extract.classify(row["url"])
50
+ pages.append(
51
+ {
52
+ "url": row["url"],
53
+ "title": page["title"],
54
+ "topic": topic,
55
+ "language": language,
56
+ "audience": audience,
57
+ "lastmod": row["lastmod"],
58
+ "text": page["text"],
59
+ }
60
+ )
61
+ return {"pages": pages}
62
+
63
+
64
+ SOURCE = Belastingdienst()
scripts/govdata/cli.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import importlib
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from govdata.common.pipeline import Options, run
7
+
8
+ DATASETS = ["wetten", "belastingdienst"]
9
+
10
+
11
+ def main(argv: list[str] | None = None) -> None:
12
+ p = argparse.ArgumentParser(prog="govdata", description="Rebuild a dataset and publish it to Hugging Face.")
13
+ p.add_argument("dataset", choices=DATASETS)
14
+ p.add_argument("--limit", type=int, help="only index/fetch the first N records (for smoke runs)")
15
+ p.add_argument("--no-upload", action="store_true", help="build locally, skip HF download and upload")
16
+ p.add_argument("--out", type=Path, default=Path("out"))
17
+ p.add_argument("--budget-hours", type=float, default=5.0, help="stop fetching after this long")
18
+ args = p.parse_args(argv)
19
+
20
+ src = importlib.import_module(f"govdata.{args.dataset}.source").SOURCE
21
+ opt = Options(limit=args.limit, upload=not args.no_upload, out=args.out, budget_s=args.budget_hours * 3600)
22
+ stats = run(src, opt, repo_root=Path(__file__).resolve().parents[2])
23
+ print(json.dumps(stats, indent=2))
24
+
25
+
26
+ if __name__ == "__main__":
27
+ main()
scripts/govdata/common/__init__.py ADDED
File without changes
scripts/govdata/common/guard.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ def check_counts(previous: dict[str, int] | None, current: dict[str, int], max_drop: float = 0.10) -> list[str]:
2
+ """Configs whose row count dropped more than max_drop. Configs absent on either side are skipped."""
3
+ if not previous:
4
+ return []
5
+ return [
6
+ f"{cfg}: {prev} -> {current[cfg]}"
7
+ for cfg, prev in previous.items()
8
+ if cfg in current and prev and current[cfg] < prev * (1 - max_drop)
9
+ ]
scripts/govdata/common/http.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import threading
2
+ import time
3
+ import urllib.robotparser
4
+ from urllib.parse import urlsplit
5
+
6
+ import httpx
7
+
8
+ USER_AGENT = "Dutch-GOV-Datasets (+https://github.com/ethux/Dutch-GOV-Datasets)"
9
+ RETRY_STATUS = {429, 500, 502, 503, 504}
10
+
11
+
12
+ class FetchError(Exception):
13
+ pass
14
+
15
+
16
+ class RateLimiter:
17
+ """Spaces calls at least 1/per_second apart, across threads."""
18
+
19
+ def __init__(self, per_second: float):
20
+ self.interval = 1.0 / per_second
21
+ self.lock = threading.Lock()
22
+ self.next_at = 0.0
23
+
24
+ def wait(self) -> None:
25
+ with self.lock:
26
+ now = time.monotonic()
27
+ at = max(now, self.next_at)
28
+ self.next_at = at + self.interval
29
+ time.sleep(max(0.0, at - now))
30
+
31
+
32
+ class Fetcher:
33
+ def __init__(
34
+ self,
35
+ per_second: float,
36
+ *,
37
+ max_retries: int = 5,
38
+ backoff: float = 2.0,
39
+ robots_exempt: set[str] = frozenset(),
40
+ transport: httpx.BaseTransport | None = None,
41
+ ):
42
+ self.client = httpx.Client(
43
+ headers={"User-Agent": USER_AGENT, "Accept": "application/xml, text/html;q=0.9, */*;q=0.8"},
44
+ timeout=120,
45
+ follow_redirects=True,
46
+ transport=transport,
47
+ )
48
+ self.limiter = RateLimiter(per_second)
49
+ self.max_retries = max_retries
50
+ self.backoff = backoff
51
+ self.robots_exempt = set(robots_exempt)
52
+ self._robots: dict[str, urllib.robotparser.RobotFileParser] = {}
53
+ self._robots_lock = threading.Lock()
54
+
55
+ def allowed(self, url: str) -> bool:
56
+ parts = urlsplit(url)
57
+ if parts.hostname in self.robots_exempt:
58
+ return True
59
+ origin = f"{parts.scheme}://{parts.netloc}"
60
+ with self._robots_lock:
61
+ rp = self._robots.get(origin)
62
+ if rp is None:
63
+ rp = urllib.robotparser.RobotFileParser()
64
+ try:
65
+ r = self.client.get(origin + "/robots.txt")
66
+ rp.parse(r.text.splitlines() if r.status_code == 200 else [])
67
+ except httpx.HTTPError:
68
+ rp.parse([])
69
+ self._robots[origin] = rp
70
+ return rp.can_fetch(USER_AGENT, url)
71
+
72
+ def get(self, url: str) -> httpx.Response:
73
+ if not self.allowed(url):
74
+ raise FetchError(f"disallowed by robots.txt: {url}")
75
+ last = ""
76
+ for attempt in range(self.max_retries + 1):
77
+ self.limiter.wait()
78
+ try:
79
+ r = self.client.get(url)
80
+ except httpx.TransportError as e:
81
+ last = repr(e)
82
+ except httpx.HTTPError as e:
83
+ raise FetchError(f"{e!r}: {url}") from e
84
+ else:
85
+ if r.status_code == 200:
86
+ return r
87
+ if r.status_code not in RETRY_STATUS:
88
+ raise FetchError(f"HTTP {r.status_code}: {url}")
89
+ last = f"HTTP {r.status_code}"
90
+ if attempt < self.max_retries:
91
+ time.sleep(self.backoff**attempt if self.backoff else 0)
92
+ raise FetchError(f"gave up after {self.max_retries} retries ({last}): {url}")
scripts/govdata/common/pipeline.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Index -> diff against previous raw -> fetch changes -> merge + build per shard -> publish."""
2
+
3
+ import json
4
+ import shutil
5
+ import time
6
+ from collections.abc import Callable, Iterable
7
+ from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
8
+ from dataclasses import dataclass, field
9
+ from datetime import date
10
+ from pathlib import Path
11
+ from typing import Any, Protocol
12
+
13
+ import pyarrow as pa
14
+
15
+ from govdata.common import publish, store
16
+ from govdata.common.guard import check_counts
17
+ from govdata.common.http import Fetcher, FetchError
18
+
19
+ MAX_FAIL_RATE = 0.02
20
+
21
+
22
+ def log(msg: str) -> None:
23
+ print(msg, flush=True)
24
+
25
+
26
+ class Source(Protocol):
27
+ name: str
28
+ repo_id: str
29
+ n_shards: int
30
+ key_col: str
31
+ mod_col: str
32
+ shard_col: str
33
+ raw_schema: pa.Schema
34
+ configs: dict[str, pa.Schema]
35
+ rate: float
36
+ robots_exempt: frozenset[str]
37
+ legacy: tuple[str, str] | None
38
+
39
+ def index(self, fetcher: Fetcher, limit: int | None) -> dict[str, Any]: ...
40
+ def modified(self, rec: Any) -> str: ...
41
+ def fetch(self, fetcher: Fetcher, key: str, rec: Any) -> dict: ...
42
+ def build(self, raw: pa.Table, index: dict[str, Any], run_date: str) -> dict[str, list[dict]]: ...
43
+
44
+
45
+ @dataclass
46
+ class FetchResult:
47
+ fetched: int = 0
48
+ failed: list[str] = field(default_factory=list)
49
+ pending: int = 0
50
+
51
+
52
+ def fetch_all(
53
+ keys: Iterable[str],
54
+ fetch_one: Callable[[str], dict],
55
+ sink: Callable[[dict], None],
56
+ deadline: float | None,
57
+ workers: int = 8,
58
+ ) -> FetchResult:
59
+ """Fetch in a thread pool; sink runs on the calling thread. Stops submitting once deadline passes."""
60
+ res = FetchResult()
61
+ it = iter(keys)
62
+ pending: dict = {}
63
+
64
+ def top_up(pool) -> bool:
65
+ while len(pending) < workers * 4:
66
+ if deadline is not None and time.monotonic() >= deadline:
67
+ return False
68
+ k = next(it, None)
69
+ if k is None:
70
+ return False
71
+ pending[pool.submit(fetch_one, k)] = k
72
+ return True
73
+
74
+ with ThreadPoolExecutor(workers) as pool:
75
+ more = top_up(pool)
76
+ while pending:
77
+ done, _ = wait(pending, return_when=FIRST_COMPLETED)
78
+ for f in done:
79
+ k = pending.pop(f)
80
+ try:
81
+ sink(f.result())
82
+ res.fetched += 1
83
+ except FetchError as e:
84
+ res.failed.append(k)
85
+ log(f"fetch failed: {e}")
86
+ done_n = res.fetched + len(res.failed)
87
+ if done_n % 1000 == 0:
88
+ log(f"fetched {done_n}")
89
+ if more:
90
+ more = top_up(pool)
91
+ res.pending = sum(1 for _ in it)
92
+ return res
93
+
94
+
95
+ @dataclass
96
+ class Options:
97
+ limit: int | None = None
98
+ upload: bool = True
99
+ out: Path = Path("out")
100
+ budget_s: float | None = 5 * 3600
101
+ run_date: str = field(default_factory=lambda: date.today().isoformat())
102
+
103
+
104
+ def run(src: Source, opt: Options, repo_root: Path) -> dict:
105
+ work = opt.out / src.name
106
+ if work.exists():
107
+ shutil.rmtree(work)
108
+ prev, staged, repo = work / "previous", work / "staging", work / "repo"
109
+ deadline = time.monotonic() + opt.budget_s if opt.budget_s is not None else None
110
+
111
+ if opt.upload:
112
+ if src.legacy and publish.move_legacy(src.repo_id, *src.legacy):
113
+ log(f"moved legacy file {src.legacy[0]} -> {src.legacy[1]}")
114
+ publish.download_previous(
115
+ src.repo_id, prev, ["data/raw/*", "documentation/stats.json", "documentation/changelog.md"]
116
+ )
117
+
118
+ fetcher = Fetcher(src.rate, robots_exempt=src.robots_exempt)
119
+ index = src.index(fetcher, opt.limit)
120
+ previous = store.read_index(prev / "data" / "raw", src.key_col, src.mod_col)
121
+ d = store.diff({k: src.modified(r) for k, r in index.items()}, previous)
122
+ log(f"index {len(index)}: {d.added} new, {d.changed} changed, {len(d.removed)} removed, {d.unchanged} unchanged")
123
+
124
+ staging = store.Staging(staged, src.raw_schema, src.shard_col, src.n_shards)
125
+ res = fetch_all(d.fetch, lambda k: src.fetch(fetcher, k, index[k]), staging.add, deadline)
126
+ staging.flush()
127
+ attempted = res.fetched + len(res.failed)
128
+ if attempted and len(res.failed) / attempted > MAX_FAIL_RATE:
129
+ raise RuntimeError(f"too many fetch failures: {len(res.failed)}/{attempted}")
130
+ complete = res.pending == 0
131
+ log(f"fetched {res.fetched}, failed {len(res.failed)}, pending {res.pending}")
132
+
133
+ counts = {"raw": 0} | ({c: 0 for c in src.configs} if complete else {})
134
+ for s in range(src.n_shards):
135
+ raw = store.merge_shard(
136
+ store.read_shard(prev / "data" / "raw", "raw", s, src.n_shards),
137
+ staging.read_shard(s),
138
+ d.removed,
139
+ src.key_col,
140
+ src.raw_schema,
141
+ )
142
+ store.write_shard(raw, repo / "data" / "raw", "raw", s, src.n_shards)
143
+ counts["raw"] += raw.num_rows
144
+ if complete:
145
+ for cfg, rows in src.build(raw, index, opt.run_date).items():
146
+ t = pa.Table.from_pylist(rows, schema=src.configs[cfg])
147
+ if t.num_rows:
148
+ store.write_shard(t, repo / "data" / cfg, cfg, s, src.n_shards)
149
+ counts[cfg] += t.num_rows
150
+
151
+ stats_file = prev / "documentation" / "stats.json"
152
+ prev_counts = json.loads(stats_file.read_text())["counts"] if stats_file.exists() else None
153
+ if problems := check_counts(prev_counts, counts):
154
+ raise RuntimeError(f"row count dropped more than 10%, not uploading: {problems}")
155
+
156
+ stats = {
157
+ "run_date": opt.run_date,
158
+ "complete": complete,
159
+ "counts": counts,
160
+ "added": d.added,
161
+ "changed": d.changed,
162
+ "removed": len(d.removed),
163
+ "failed": len(res.failed),
164
+ "pending": res.pending,
165
+ }
166
+ publish.stage_repo(repo_root, src.name, repo, stats, prev / "documentation" / "changelog.md")
167
+ if not complete:
168
+ (repo / "README.md").unlink() # its configs point at files a backfill hasn't built yet
169
+
170
+ if opt.upload:
171
+ month = opt.run_date[:7]
172
+ deletes = ["data/raw/*"] + ([f"data/{c}/*" for c in src.configs] if complete else [])
173
+ message = f"{month} update" if complete else f"{month} backfill progress ({res.pending} pending)"
174
+ publish.push(src.repo_id, repo, message, month if complete else None, deletes)
175
+ log(f"published {src.repo_id}: {message}")
176
+ return stats
scripts/govdata/common/publish.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import shutil
3
+ from pathlib import Path
4
+
5
+ from huggingface_hub import CommitOperationCopy, CommitOperationDelete, HfApi, snapshot_download
6
+
7
+ LEGACY_TAG = "v1-2024"
8
+ CHANGELOG_HEADER = (
9
+ "# Changelog\n\n"
10
+ "One row per monthly run. Rows = row count per config.\n\n"
11
+ "| Run date | Complete | Rows | Added | Changed | Removed | Failed | Pending |\n"
12
+ "|---|---|---|---|---|---|---|---|\n"
13
+ )
14
+ SCRIPTS_README = (
15
+ "# scripts\n\n"
16
+ "Copy of the scraper that built this dataset. Source and instructions: "
17
+ "https://github.com/ethux/Dutch-GOV-Datasets\n"
18
+ )
19
+ IGNORE = shutil.ignore_patterns("__pycache__", "*.pyc")
20
+
21
+
22
+ def download_previous(repo_id: str, dest: Path, patterns: list[str]) -> None:
23
+ snapshot_download(repo_id=repo_id, repo_type="dataset", local_dir=dest, allow_patterns=patterns)
24
+
25
+
26
+ def stage_repo(repo_root: Path, name: str, dest: Path, stats: dict, previous_changelog: Path) -> None:
27
+ """Lay out everything except data/ as it should appear in the HF repo."""
28
+ ds = repo_root / "datasets" / name
29
+ pkg = repo_root / "src" / "govdata"
30
+ dest.mkdir(parents=True, exist_ok=True)
31
+ shutil.copy(ds / "README.md", dest / "README.md")
32
+ shutil.copy(repo_root / "LICENSE", dest / "LICENSE.md")
33
+ docs = dest / "documentation"
34
+ shutil.copytree(ds / "documentation", docs, dirs_exist_ok=True)
35
+
36
+ scripts = dest / "scripts"
37
+ for part in ("common", name):
38
+ shutil.copytree(pkg / part, scripts / "govdata" / part, ignore=IGNORE, dirs_exist_ok=True)
39
+ for f in ("__init__.py", "cli.py"):
40
+ shutil.copy(pkg / f, scripts / "govdata" / f)
41
+ (scripts / "README.md").write_text(SCRIPTS_README)
42
+
43
+ (docs / "stats.json").write_text(json.dumps(stats, indent=2) + "\n")
44
+ log = previous_changelog.read_text() if previous_changelog.exists() else CHANGELOG_HEADER
45
+ rows = ", ".join(f"{k}={v}" for k, v in stats["counts"].items())
46
+ log = log.rstrip("\n") + "\n" + (
47
+ f"| {stats['run_date']} | {'yes' if stats['complete'] else 'no'} | {rows} | {stats['added']} "
48
+ f"| {stats['changed']} | {stats['removed']} | {stats['failed']} | {stats['pending']} |\n"
49
+ )
50
+ (docs / "changelog.md").write_text(log)
51
+
52
+
53
+ def push(
54
+ repo_id: str, folder: Path, message: str, tag: str | None, delete_patterns: list[str], api: HfApi | None = None
55
+ ) -> str:
56
+ api = api or HfApi()
57
+ info = api.upload_folder(
58
+ repo_id=repo_id,
59
+ repo_type="dataset",
60
+ folder_path=folder,
61
+ commit_message=message,
62
+ delete_patterns=delete_patterns,
63
+ )
64
+ if tag:
65
+ refs = api.list_repo_refs(repo_id, repo_type="dataset")
66
+ if any(t.name == tag for t in refs.tags):
67
+ api.delete_tag(repo_id, tag=tag, repo_type="dataset")
68
+ api.create_tag(repo_id, tag=tag, repo_type="dataset", revision=info.oid)
69
+ return info.oid
70
+
71
+
72
+ def move_legacy(repo_id: str, src_path: str, dst_path: str, api: HfApi | None = None) -> bool:
73
+ """One-time: tag the pre-monorepo state, then move the old CSV into data/legacy/."""
74
+ api = api or HfApi()
75
+ if src_path not in api.list_repo_files(repo_id, repo_type="dataset"):
76
+ return False
77
+ api.create_tag(repo_id, tag=LEGACY_TAG, repo_type="dataset", exist_ok=True)
78
+ api.create_commit(
79
+ repo_id=repo_id,
80
+ repo_type="dataset",
81
+ operations=[
82
+ CommitOperationCopy(src_path_in_repo=src_path, path_in_repo=dst_path),
83
+ CommitOperationDelete(path_in_repo=src_path),
84
+ ],
85
+ commit_message=f"Move {src_path} to {dst_path}",
86
+ )
87
+ return True
scripts/govdata/common/store.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import zlib
2
+ from collections import defaultdict
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+
6
+ import pyarrow as pa
7
+ import pyarrow.compute as pc
8
+ import pyarrow.parquet as pq
9
+
10
+
11
+ def shard_of(value: str, n: int) -> int:
12
+ return zlib.crc32(value.encode()) % n
13
+
14
+
15
+ def shard_name(config: str, s: int, n: int) -> str:
16
+ return f"{config}-{s:05d}-of-{n:05d}.parquet"
17
+
18
+
19
+ def read_shard(directory: Path, config: str, s: int, n: int) -> pa.Table | None:
20
+ path = Path(directory) / shard_name(config, s, n)
21
+ return pq.read_table(path) if path.exists() else None
22
+
23
+
24
+ def write_shard(table: pa.Table, directory: Path, config: str, s: int, n: int) -> Path:
25
+ directory = Path(directory)
26
+ directory.mkdir(parents=True, exist_ok=True)
27
+ path = directory / shard_name(config, s, n)
28
+ pq.write_table(table, path, compression="zstd")
29
+ return path
30
+
31
+
32
+ def read_index(raw_dir: Path, key_col: str, mod_col: str) -> dict[str, str]:
33
+ out: dict[str, str] = {}
34
+ for f in sorted(Path(raw_dir).glob("*.parquet")):
35
+ t = pq.read_table(f, columns=[key_col, mod_col])
36
+ out.update(zip(t.column(key_col).to_pylist(), t.column(mod_col).to_pylist()))
37
+ return out
38
+
39
+
40
+ @dataclass
41
+ class Diff:
42
+ fetch: list[str]
43
+ removed: set[str]
44
+ added: int
45
+ changed: int
46
+ unchanged: int
47
+
48
+
49
+ def diff(current: dict[str, str], previous: dict[str, str]) -> Diff:
50
+ added = [k for k in current if k not in previous]
51
+ changed = [k for k in current if k in previous and previous[k] != current[k]]
52
+ return Diff(
53
+ fetch=added + changed,
54
+ removed=set(previous) - set(current),
55
+ added=len(added),
56
+ changed=len(changed),
57
+ unchanged=len(current) - len(added) - len(changed),
58
+ )
59
+
60
+
61
+ class Staging:
62
+ """Buffers fetched rows to per-shard Parquet files so a shard is read back without scanning the rest."""
63
+
64
+ def __init__(self, directory: Path, schema: pa.Schema, shard_col: str, n_shards: int, flush_rows: int = 100):
65
+ self.dir = Path(directory)
66
+ self.dir.mkdir(parents=True, exist_ok=True)
67
+ self.schema = schema
68
+ self.shard_col = shard_col
69
+ self.n = n_shards
70
+ self.flush_rows = flush_rows
71
+ self.buffers: dict[int, list[dict]] = defaultdict(list)
72
+ self.seq = 0
73
+
74
+ def add(self, row: dict) -> None:
75
+ s = shard_of(row[self.shard_col], self.n)
76
+ self.buffers[s].append(row)
77
+ if len(self.buffers[s]) >= self.flush_rows:
78
+ self._flush_shard(s)
79
+
80
+ def flush(self) -> None:
81
+ for s in list(self.buffers):
82
+ self._flush_shard(s)
83
+
84
+ def _flush_shard(self, s: int) -> None:
85
+ rows = self.buffers.pop(s, [])
86
+ if not rows:
87
+ return
88
+ self.seq += 1
89
+ pq.write_table(pa.Table.from_pylist(rows, schema=self.schema), self.dir / f"{s:05d}-{self.seq:07d}.parquet")
90
+
91
+ def read_shard(self, s: int) -> pa.Table:
92
+ files = sorted(self.dir.glob(f"{s:05d}-*.parquet"))
93
+ if not files:
94
+ return self.schema.empty_table()
95
+ return pa.concat_tables(pq.read_table(f).cast(self.schema) for f in files)
96
+
97
+
98
+ def merge_shard(
99
+ previous: pa.Table | None, fetched: pa.Table, removed: set[str], key_col: str, schema: pa.Schema
100
+ ) -> pa.Table:
101
+ parts = []
102
+ if previous is not None and previous.num_rows:
103
+ drop = pa.array(sorted(set(removed) | set(fetched.column(key_col).to_pylist())), pa.string())
104
+ keep = pc.invert(pc.is_in(previous.column(key_col), value_set=drop))
105
+ parts.append(previous.filter(keep).select(schema.names).cast(schema))
106
+ parts.append(fetched.select(schema.names).cast(schema))
107
+ return pa.concat_tables(parts).sort_by(key_col)