endomorphosis commited on
Commit
ab9708b
·
verified ·
1 Parent(s): 13f6734

Add parquet corpus and collector

Browse files
Files changed (4) hide show
  1. README.md +67 -0
  2. data/articles.parquet +3 -0
  3. data/laws.parquet +3 -0
  4. scrapers/collect_gii.py +1175 -0
README.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: German Federal Law Corpus (Gesetze im Internet)
3
+ license: other
4
+ license_name: urhg-5-amtliche-werke
5
+ language:
6
+ - de
7
+ task_categories:
8
+ - text-retrieval
9
+ tags:
10
+ - legal
11
+ - law
12
+ - germany
13
+ - bundesrecht
14
+ - gesetze-im-internet
15
+ - official-texts
16
+ size_categories:
17
+ - 100K<n<1M
18
+ configs:
19
+ - config_name: laws
20
+ data_files: data/laws.parquet
21
+ default: true
22
+ - config_name: articles
23
+ data_files: data/articles.parquet
24
+ ---
25
+
26
+ # German Federal Law Corpus (Gesetze im Internet)
27
+
28
+ Research snapshot of **current German federal law (Bundesrecht)** collected from
29
+ [Gesetze im Internet](https://www.gesetze-im-internet.de/) (GII), the public
30
+ portal of the Federal Ministry of Justice.
31
+
32
+ **Not legal advice.** The official gazette (*Bundesgesetzblatt*) and the
33
+ authentic source prevail over this corpus.
34
+
35
+ ## Snapshot
36
+
37
+ | Field | Value |
38
+ | --- | --- |
39
+ | Snapshot date | 2026-09-02 |
40
+ | Source | Gesetze im Internet (GII) |
41
+ | Collector | `scrapers/collect_gii.py` |
42
+ | Laws | 6,124 |
43
+ | Articles | 129,926 |
44
+ | Language | German (`de`) |
45
+ | Jurisdiction | Germany (federal) |
46
+
47
+ ## Contents
48
+
49
+ - `data/laws.parquet` — one row per instrument (id, title, full text, ELI,
50
+ dates, status, identifiers, article count, source URL).
51
+ - `data/articles.parquet` — one row per article/section (`law_id`, article
52
+ number, title, text, source URL).
53
+ - `scrapers/collect_gii.py` — research collector used to build this snapshot.
54
+
55
+ ## License / reuse
56
+
57
+ Official legislative texts are **amtliche Werke** under **UrhG § 5**
58
+ (German Copyright Act). Reuse of the official wording is generally permitted;
59
+ this packaging, metadata, and collector script are provided for research.
60
+
61
+ This dataset is **not** an official consolidation and is **not legal advice**.
62
+ The official gazette prevails.
63
+
64
+ ## Source
65
+
66
+ - Portal: https://www.gesetze-im-internet.de/
67
+ - Publisher: Federal Ministry of Justice (BMJ) / juris
data/articles.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e4ed43ee4b26485830984c79911167526b3cfc9c4e536ca14f3eb4013d5fe4da
3
+ size 38009784
data/laws.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57c04536ba4246fdcc016d93ed98a7bf593989f7b2ffe4d29f0a0a8efa8d902b
3
+ size 32867474
scrapers/collect_gii.py ADDED
@@ -0,0 +1,1175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Collect current German federal law (Bundesrecht) from gesetze-im-internet.de.
3
+
4
+ Writes:
5
+ instruments/{safe_id}.json
6
+ index.jsonl
7
+ SUMMARY.md
8
+ logs/collector.log
9
+ logs/failures.jsonl
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import logging
15
+ import os
16
+ import re
17
+ import sys
18
+ import threading
19
+ import time
20
+ import zipfile
21
+ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
22
+ from datetime import datetime, timezone, timedelta
23
+ from io import BytesIO
24
+ from pathlib import Path
25
+ from typing import Any, Optional
26
+ from urllib.parse import urlparse
27
+ from xml.etree import ElementTree as ET
28
+
29
+ import requests
30
+ from requests.adapters import HTTPAdapter
31
+ from urllib3.util.retry import Retry
32
+
33
+ ROOT = Path("/workspace/legal-corpora/de")
34
+ INSTRUMENTS = ROOT / "instruments"
35
+ LOGS = ROOT / "logs"
36
+ INDEX_PATH = ROOT / "index.jsonl"
37
+ SUMMARY_PATH = ROOT / "SUMMARY.md"
38
+ FAILURES_PATH = LOGS / "failures.jsonl"
39
+ TOC_CACHE = LOGS / "gii-toc.xml"
40
+ TOC_URL = "https://www.gesetze-im-internet.de/gii-toc.xml"
41
+ CACHE = ROOT / "cache"
42
+
43
+ LICENSE = (
44
+ "Public domain (gemeinfrei): amtliche Werke i.S.d. § 5 Abs. 1 UrhG; "
45
+ "Bundesministerium der Justiz / gesetze-im-internet.de"
46
+ )
47
+ PUBLISHER = "Bundesministerium der Justiz"
48
+ SOURCE_NAME = "gesetze-im-internet.de"
49
+ UA = "legal-corpora-collector/1.0 (research corpus; German Bundesrecht; polite; +https://www.gesetze-im-internet.de/)"
50
+ WORKERS = 6
51
+ PARSE_WORKERS = max(1, (os.cpu_count() or 8))
52
+ CONNECT_TIMEOUT = 15
53
+ READ_TIMEOUT = 60
54
+ MAX_ZIP_BYTES = 80 * 1024 * 1024 # skip pathological zips
55
+ MAX_XML_BYTES = 60 * 1024 * 1024
56
+ BINARY_TAGS = {
57
+ "img", "graphic", "object", "binary", "Image", "IMG", "Bild",
58
+ "symbol", "Symbol",
59
+ }
60
+ BREAK_AFTER = {
61
+ "P", "BR", "LA", "DT", "DD", "Title", "Ident", "pre", "TOC", "Content",
62
+ "Footnote", "fussnoten",
63
+ }
64
+ SAFE_RE = re.compile(r"[^A-Za-z0-9._-]+")
65
+ PT = timezone(timedelta(hours=-7))
66
+
67
+ log = logging.getLogger("collector")
68
+ _index_lock = threading.Lock()
69
+ _fail_lock = threading.Lock()
70
+ _tls = threading.local()
71
+
72
+
73
+ def now_utc() -> datetime:
74
+ return datetime.now(timezone.utc)
75
+
76
+
77
+ def iso_z(dt: datetime) -> str:
78
+ return dt.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
79
+
80
+
81
+ def iso_pt(dt: datetime) -> str:
82
+ return dt.astimezone(PT).strftime("%Y-%m-%d %H:%M:%S PT")
83
+
84
+
85
+ def local_tag(tag: Optional[str]) -> str:
86
+ if not tag:
87
+ return ""
88
+ if "}" in tag:
89
+ return tag.rsplit("}", 1)[-1]
90
+ return tag
91
+
92
+
93
+ def looks_binary(text: str) -> bool:
94
+ if len(text) < 4000:
95
+ return False
96
+ sample = text[:8000].replace("\n", "").replace("\r", "").replace(" ", "")
97
+ if len(sample) < 2000:
98
+ return False
99
+ # base64-ish
100
+ b64 = sum(1 for c in sample if c.isalnum() or c in "+/=") / max(len(sample), 1)
101
+ if b64 > 0.95 and len(sample) > 4000:
102
+ return True
103
+ nul = sample.count("\x00")
104
+ if nul > 10:
105
+ return True
106
+ return False
107
+
108
+
109
+ def extract_text(elem: Optional[ET.Element]) -> str:
110
+ if elem is None:
111
+ return ""
112
+ parts: list[str] = []
113
+
114
+ def rec(e: ET.Element) -> None:
115
+ tag = local_tag(e.tag)
116
+ if tag in BINARY_TAGS:
117
+ return
118
+ # skip attributes that are typically binary payloads
119
+ if e.text:
120
+ if looks_binary(e.text):
121
+ parts.append("[binary attachment omitted]")
122
+ else:
123
+ parts.append(e.text)
124
+ for child in e:
125
+ rec(child)
126
+ if child.tail:
127
+ if looks_binary(child.tail):
128
+ continue
129
+ parts.append(child.tail)
130
+ if tag in BREAK_AFTER:
131
+ parts.append("\n")
132
+
133
+ rec(elem)
134
+ text = "".join(parts)
135
+ lines = [re.sub(r"[ \t]+", " ", ln).strip() for ln in text.splitlines()]
136
+ out: list[str] = []
137
+ blank = False
138
+ for ln in lines:
139
+ if not ln:
140
+ if not blank:
141
+ out.append("")
142
+ blank = True
143
+ else:
144
+ out.append(ln)
145
+ blank = False
146
+ return "\n".join(out).strip()
147
+
148
+
149
+ def child_text(parent: Optional[ET.Element], name: str) -> Optional[str]:
150
+ if parent is None:
151
+ return None
152
+ el = parent.find(name)
153
+ if el is None:
154
+ return None
155
+ t = "".join(el.itertext()).strip()
156
+ return t or None
157
+
158
+
159
+ def safe_id(slug: str) -> str:
160
+ """Filesystem-safe id. Keep leading underscores (GII slugs like _ag)."""
161
+ s = (slug or "").strip()
162
+ s = SAFE_RE.sub("_", s)
163
+ if not s or s in {".", ".."}:
164
+ s = "unnamed"
165
+ return s[:180]
166
+
167
+
168
+ def slug_from_link(link: str) -> str:
169
+ p = urlparse(link)
170
+ parts = [x for x in p.path.split("/") if x]
171
+ if parts and parts[-1].lower() in {"xml.zip", "xml"}:
172
+ parts = parts[:-1]
173
+ if not parts:
174
+ raise ValueError(f"cannot parse slug from {link}")
175
+ return parts[-1]
176
+
177
+
178
+ def https_url(url: str) -> str:
179
+ if url.startswith("http://"):
180
+ return "https://" + url[len("http://") :]
181
+ return url
182
+
183
+
184
+ def get_session() -> requests.Session:
185
+ sess = getattr(_tls, "session", None)
186
+ if sess is None:
187
+ sess = requests.Session()
188
+ sess.headers.update({"User-Agent": UA, "Accept": "*/*"})
189
+ retry = Retry(
190
+ total=0, # we handle retries ourselves for logging
191
+ connect=0,
192
+ read=0,
193
+ redirect=3,
194
+ backoff_factor=0,
195
+ raise_on_status=False,
196
+ )
197
+ adapter = HTTPAdapter(max_retries=retry, pool_connections=8, pool_maxsize=8)
198
+ sess.mount("https://", adapter)
199
+ sess.mount("http://", adapter)
200
+ _tls.session = sess
201
+ return sess
202
+
203
+
204
+ def http_get(url: str, retries: int = 6) -> requests.Response:
205
+ sess = get_session()
206
+ last_err: Optional[Exception] = None
207
+ delay = 1.0
208
+ for attempt in range(1, retries + 1):
209
+ try:
210
+ resp = sess.get(url, timeout=(CONNECT_TIMEOUT, READ_TIMEOUT), stream=True)
211
+ if resp.status_code in (429, 500, 502, 503, 504) or resp.status_code >= 500:
212
+ body_len = 0
213
+ try:
214
+ resp.close()
215
+ except Exception:
216
+ pass
217
+ log.warning("HTTP %s for %s attempt %s/%s; sleep %.1fs",
218
+ resp.status_code, url, attempt, retries, delay)
219
+ time.sleep(delay)
220
+ delay = min(delay * 2, 32)
221
+ continue
222
+ if resp.status_code == 404:
223
+ return resp
224
+ resp.raise_for_status()
225
+ return resp
226
+ except (requests.Timeout, requests.ConnectionError) as e:
227
+ last_err = e
228
+ log.warning("net error %s for %s attempt %s/%s; sleep %.1fs",
229
+ type(e).__name__, url, attempt, retries, delay)
230
+ time.sleep(delay)
231
+ delay = min(delay * 2, 32)
232
+ except requests.HTTPError as e:
233
+ last_err = e
234
+ code = getattr(e.response, "status_code", None)
235
+ if code and code < 500 and code != 429:
236
+ raise
237
+ log.warning("HTTPError %s for %s attempt %s/%s", e, url, attempt, retries)
238
+ time.sleep(delay)
239
+ delay = min(delay * 2, 32)
240
+ if last_err:
241
+ raise last_err
242
+ raise RuntimeError(f"failed to GET {url}")
243
+
244
+
245
+ def download_bytes(url: str) -> tuple[bytes, int]:
246
+ resp = http_get(url)
247
+ if resp.status_code == 404:
248
+ raise FileNotFoundError(f"404 {url}")
249
+ chunks: list[bytes] = []
250
+ total = 0
251
+ for chunk in resp.iter_content(64 * 1024):
252
+ if not chunk:
253
+ continue
254
+ total += len(chunk)
255
+ if total > MAX_ZIP_BYTES:
256
+ resp.close()
257
+ raise ValueError(f"download too large ({total} bytes): {url}")
258
+ chunks.append(chunk)
259
+ return b"".join(chunks), resp.status_code
260
+
261
+
262
+ def xml_from_payload(payload: bytes, url: str) -> ET.Element:
263
+ # zip?
264
+ if payload[:2] == b"PK":
265
+ with zipfile.ZipFile(BytesIO(payload)) as zf:
266
+ xml_names = [
267
+ n for n in zf.namelist()
268
+ if n.lower().endswith(".xml") and not n.endswith("/")
269
+ ]
270
+ if not xml_names:
271
+ raise ValueError(f"no XML in zip {url}: {zf.namelist()[:20]}")
272
+ # prefer the largest xml (main document)
273
+ xml_names.sort(key=lambda n: zf.getinfo(n).file_size, reverse=True)
274
+ info = zf.getinfo(xml_names[0])
275
+ if info.file_size > MAX_XML_BYTES:
276
+ raise ValueError(f"XML too large {info.file_size} in {url}")
277
+ raw = zf.read(xml_names[0])
278
+ else:
279
+ raw = payload
280
+ if len(raw) > MAX_XML_BYTES:
281
+ raise ValueError(f"XML too large {len(raw)} from {url}")
282
+ # strip BOM
283
+ if raw.startswith(b"\xef\xbb\xbf"):
284
+ raw = raw[3:]
285
+ try:
286
+ return ET.fromstring(raw)
287
+ except ET.ParseError:
288
+ # some files may be latin-1 mislabeled
289
+ text = raw.decode("utf-8", errors="replace")
290
+ return ET.fromstring(text.encode("utf-8"))
291
+
292
+
293
+ def parse_toc(path: Path) -> list[dict[str, str]]:
294
+ tree = ET.parse(path)
295
+ items = []
296
+ seen = set()
297
+ for it in tree.getroot().findall("item"):
298
+ title = (it.findtext("title") or "").strip()
299
+ link = (it.findtext("link") or "").strip()
300
+ if not link:
301
+ continue
302
+ link = https_url(link)
303
+ slug = slug_from_link(link)
304
+ if slug in seen:
305
+ continue
306
+ seen.add(slug)
307
+ items.append({"slug": slug, "title": title, "xml_url": link})
308
+ return items
309
+
310
+
311
+ def load_done_ids() -> set[str]:
312
+ done: set[str] = set()
313
+ if not INDEX_PATH.exists():
314
+ return done
315
+ with INDEX_PATH.open("r", encoding="utf-8") as f:
316
+ for line in f:
317
+ line = line.strip()
318
+ if not line:
319
+ continue
320
+ try:
321
+ rec = json.loads(line)
322
+ except json.JSONDecodeError:
323
+ continue
324
+ iid = rec.get("id")
325
+ if iid:
326
+ done.add(iid)
327
+ return done
328
+
329
+
330
+ def append_index(row: dict[str, Any]) -> None:
331
+ line = json.dumps(row, ensure_ascii=False, separators=(",", ":"))
332
+ with _index_lock:
333
+ with INDEX_PATH.open("a", encoding="utf-8") as f:
334
+ f.write(line + "\n")
335
+ f.flush()
336
+ os.fsync(f.fileno())
337
+
338
+
339
+ def append_failure(row: dict[str, Any]) -> None:
340
+ line = json.dumps(row, ensure_ascii=False, separators=(",", ":"))
341
+ with _fail_lock:
342
+ with FAILURES_PATH.open("a", encoding="utf-8") as f:
343
+ f.write(line + "\n")
344
+ f.flush()
345
+
346
+
347
+ def build_record(slug: str, toc_title: str, xml_url: str, root: ET.Element, retrieved_at: str) -> dict[str, Any]:
348
+ page_url = f"https://www.gesetze-im-internet.de/{slug}/"
349
+ eli = f"https://www.gesetze-im-internet.de/eli/{slug}"
350
+ official_id = root.get("doknr")
351
+ builddate = root.get("builddate")
352
+
353
+ norms = list(root.findall("norm"))
354
+ header_md = norms[0].find("metadaten") if norms else None
355
+ jurabk = child_text(header_md, "jurabk")
356
+ amtabk = child_text(header_md, "amtabk")
357
+ langue = child_text(header_md, "langue")
358
+ date_issued = child_text(header_md, "ausfertigung-datum")
359
+ title = langue or toc_title or jurabk or slug
360
+ title = re.sub(r"\s+", " ", title).strip()
361
+
362
+ fundstelle = None
363
+ if header_md is not None:
364
+ fs = header_md.find("fundstelle")
365
+ if fs is not None:
366
+ fundstelle = {
367
+ "typ": fs.get("typ"),
368
+ "periodikum": child_text(fs, "periodikum"),
369
+ "zitstelle": child_text(fs, "zitstelle"),
370
+ }
371
+
372
+ stand = []
373
+ if header_md is not None:
374
+ for sa in header_md.findall("standangabe"):
375
+ stand.append({
376
+ "typ": child_text(sa, "standtyp"),
377
+ "kommentar": child_text(sa, "standkommentar"),
378
+ })
379
+
380
+ documents: list[dict[str, Any]] = []
381
+ text_parts: list[str] = []
382
+
383
+ for i, norm in enumerate(norms):
384
+ md = norm.find("metadaten")
385
+ td = norm.find("textdaten")
386
+ enbez = child_text(md, "enbez")
387
+ titel = child_text(md, "titel")
388
+ gl = md.find("gliederungseinheit") if md is not None else None
389
+ gl_bez = child_text(gl, "gliederungsbez") if gl is not None else None
390
+ gl_titel = child_text(gl, "gliederungstitel") if gl is not None else None
391
+ doknr = norm.get("doknr")
392
+
393
+ if i == 0 and not enbez and gl is None:
394
+ doc_title = title
395
+ doc_id = f"{slug}:header"
396
+ elif gl is not None:
397
+ doc_title = " ".join(x for x in (gl_bez, gl_titel) if x) or f"gliederung-{i}"
398
+ doc_id = f"{slug}:gl:{gl_bez or i}"
399
+ else:
400
+ doc_title = " ".join(x for x in (enbez, titel) if x) or f"norm-{i}"
401
+ doc_id = f"{slug}:{enbez or i}"
402
+
403
+ body = ""
404
+ if td is not None:
405
+ text_el = td.find("text")
406
+ body = extract_text(text_el if text_el is not None else td)
407
+ fn = td.find("fussnoten")
408
+ fn_text = extract_text(fn) if fn is not None else ""
409
+ if fn_text:
410
+ body = (body + "\n\n" + fn_text).strip() if body else fn_text
411
+
412
+ documents.append({
413
+ "id": doc_id,
414
+ "title": doc_title,
415
+ "text": body,
416
+ "source_url": page_url,
417
+ "metadata": {
418
+ "doknr": doknr,
419
+ "enbez": enbez,
420
+ "titel": titel,
421
+ "gliederungsbez": gl_bez,
422
+ "gliederungstitel": gl_titel,
423
+ },
424
+ })
425
+ header_line = doc_title.strip()
426
+ if header_line and body:
427
+ text_parts.append(header_line + "\n" + body)
428
+ elif header_line:
429
+ text_parts.append(header_line)
430
+ elif body:
431
+ text_parts.append(body)
432
+
433
+ full_text = "\n\n".join(p for p in text_parts if p).strip()
434
+
435
+ rec_id = slug # unique, stable, matches URL; abbreviation kept in metadata
436
+ date = date_issued if date_issued and re.match(r"^\d{4}-\d{2}-\d{2}$", date_issued) else None
437
+ stand_blob = " ".join((x.get("kommentar") or "") for x in stand).lower()
438
+ if "außer kraft" in stand_blob or "ausser kraft" in stand_blob:
439
+ law_status = "repealed"
440
+ is_current = False
441
+ else:
442
+ law_status = "current"
443
+ is_current = True
444
+ record = {
445
+ "schema_version": "collection_record.v1",
446
+ "record_type": "law",
447
+ "id": rec_id,
448
+ "title": title,
449
+ "jurisdiction": "DE",
450
+ "country": "Germany",
451
+ "language": "de",
452
+ "source_type": "gesetze_im_internet",
453
+ "source_url": page_url,
454
+ "eli": None,
455
+ "date": date,
456
+ "date_issued": date_issued,
457
+ "license": LICENSE,
458
+ "retrieved_at": retrieved_at,
459
+ "identifier": official_id or jurabk or slug,
460
+ "official_identifier": jurabk or official_id or slug,
461
+ "law_identifier": jurabk or slug,
462
+ "document_type": "statute",
463
+ "law_status": law_status,
464
+ "is_current": is_current,
465
+ "article_count": len(documents),
466
+ "article_extraction_status": "ok" if documents else "missing",
467
+ "canonical_law_url": page_url,
468
+ "text": full_text,
469
+ "documents": documents,
470
+ "metadata": {
471
+ "license": LICENSE,
472
+ "retrieved_at": retrieved_at,
473
+ "official_id": official_id,
474
+ "publisher": PUBLISHER,
475
+ "source_name": SOURCE_NAME,
476
+ "abbreviation": jurabk,
477
+ "amtliche_abkuerzung": amtabk,
478
+ "slug": slug,
479
+ "xml_url": xml_url,
480
+ "builddate": builddate,
481
+ "fundstelle": fundstelle,
482
+ "standangabe": stand,
483
+ "toc_title": toc_title,
484
+ "n_norms": len(norms),
485
+ "schema": "collection_record.v1",
486
+ "collector": "collect_gii",
487
+ "parser": "gii-xml-norm",
488
+ "rights": {
489
+ "not_legal_advice": True,
490
+ "official_reuse_url": "https://www.gesetze-im-internet.de/",
491
+ "license": LICENSE,
492
+ },
493
+ },
494
+ }
495
+ return record
496
+
497
+
498
+ def write_record(record: dict[str, Any], sid: str) -> tuple[int, dict[str, Any]]:
499
+ out_path = INSTRUMENTS / f"{sid}.json"
500
+ tmp_path = INSTRUMENTS / f".{sid}.json.tmp"
501
+ data = json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n"
502
+ encoded = data.encode("utf-8")
503
+ with tmp_path.open("wb") as f:
504
+ f.write(encoded)
505
+ f.flush()
506
+ os.fsync(f.fileno())
507
+ os.replace(tmp_path, out_path)
508
+ row = {
509
+ "id": record["id"],
510
+ "path": f"instruments/{sid}.json",
511
+ "title": record["title"],
512
+ "identifier": record.get("identifier"),
513
+ "eli": record.get("eli"),
514
+ "source_url": record["source_url"],
515
+ "source_type": record["source_type"],
516
+ "jurisdiction": record["jurisdiction"],
517
+ "language": record["language"],
518
+ "law_status": record.get("law_status"),
519
+ "date": record.get("date"),
520
+ "retrieved_at": record.get("retrieved_at"),
521
+ "article_count": record.get("article_count") or len(record.get("documents") or []),
522
+ "bytes": len(encoded),
523
+ "byte_size": len(encoded),
524
+ }
525
+ return len(encoded), row
526
+
527
+
528
+ def process_item(item: dict[str, str]) -> dict[str, Any]:
529
+ slug = item["slug"]
530
+ sid = safe_id(slug)
531
+ xml_url = item["xml_url"]
532
+ cache_zip = CACHE / f"{slug}.zip"
533
+ part = CACHE / f"{slug}.zip.part"
534
+ if part.exists():
535
+ raise RuntimeError(f"in-progress download {part.name}")
536
+ if cache_zip.exists() and cache_zip.stat().st_size > 32:
537
+ payload = cache_zip.read_bytes()
538
+ status = 200
539
+ retrieved_at = iso_z(datetime.fromtimestamp(cache_zip.stat().st_mtime, timezone.utc))
540
+ else:
541
+ payload, status = download_bytes(xml_url)
542
+ retrieved_at = iso_z(now_utc())
543
+ try:
544
+ CACHE.mkdir(parents=True, exist_ok=True)
545
+ tmp = cache_zip.with_suffix(".zip.tmp")
546
+ tmp.write_bytes(payload)
547
+ tmp.replace(cache_zip)
548
+ except Exception:
549
+ pass
550
+ root = xml_from_payload(payload, xml_url)
551
+ record = build_record(slug, item.get("title") or "", xml_url, root, retrieved_at)
552
+ nbytes, row = write_record(record, sid)
553
+ append_index(row)
554
+ return {
555
+ "ok": True,
556
+ "id": slug,
557
+ "bytes": nbytes,
558
+ "status": status,
559
+ "n_docs": len(record["documents"]),
560
+ "row": row,
561
+ }
562
+
563
+
564
+ def process_cache_item(item: dict[str, str]) -> dict[str, Any]:
565
+ """Parse a finished cache zip. No network. Safe for ProcessPoolExecutor."""
566
+ slug = item["slug"]
567
+ sid = safe_id(slug)
568
+ xml_url = item.get("xml_url") or f"https://www.gesetze-im-internet.de/{slug}/xml.zip"
569
+ cache_zip = CACHE / f"{slug}.zip"
570
+ part = Path(str(cache_zip) + ".part")
571
+ try:
572
+ if part.exists():
573
+ return {"ok": False, "id": slug, "error": "in_progress", "transient": True}
574
+ if not cache_zip.exists() or cache_zip.stat().st_size <= 32:
575
+ return {"ok": False, "id": slug, "error": "missing_zip", "transient": True}
576
+ payload = cache_zip.read_bytes()
577
+ if not payload.startswith(b"PK"):
578
+ return {"ok": False, "id": slug, "error": "not_a_zip"}
579
+ retrieved_at = iso_z(datetime.fromtimestamp(cache_zip.stat().st_mtime, timezone.utc))
580
+ root = xml_from_payload(payload, xml_url)
581
+ record = build_record(slug, item.get("title") or "", xml_url, root, retrieved_at)
582
+ nbytes, row = write_record(record, sid)
583
+ return {
584
+ "ok": True,
585
+ "id": slug,
586
+ "bytes": nbytes,
587
+ "n_docs": len(record["documents"]),
588
+ "row": row,
589
+ "law_status": record.get("law_status"),
590
+ }
591
+ except Exception as e:
592
+ return {"ok": False, "id": slug, "error": f"{type(e).__name__}: {e}"}
593
+
594
+
595
+ def process_safe(item: dict[str, str]) -> dict[str, Any]:
596
+ slug = item["slug"]
597
+ try:
598
+ return process_item(item)
599
+ except Exception as e:
600
+ err = f"{type(e).__name__}: {e}"
601
+ log.error("FAIL %s %s", slug, err)
602
+ append_failure({
603
+ "id": slug,
604
+ "title": item.get("title"),
605
+ "xml_url": item.get("xml_url"),
606
+ "error": err,
607
+ "ts": iso_z(now_utc()),
608
+ })
609
+ return {"ok": False, "id": slug, "error": err}
610
+
611
+
612
+ def write_summary(
613
+ toc_count: int,
614
+ ok_count: int,
615
+ fail_count: int,
616
+ skip_count: int,
617
+ total_bytes: int,
618
+ start: datetime,
619
+ end: datetime,
620
+ failed_ids: list[str],
621
+ notes: str = "",
622
+ ) -> None:
623
+ elapsed = (end - start).total_seconds()
624
+ lines = [
625
+ "# German federal law corpus (Bundesrecht)",
626
+ "",
627
+ "## Source",
628
+ "",
629
+ f"- Site: https://www.gesetze-im-internet.de/",
630
+ f"- TOC: {TOC_URL}",
631
+ f"- Per-instrument XML zip: https://www.gesetze-im-internet.de/{{slug}}/xml.zip",
632
+ f"- Publisher: {PUBLISHER}",
633
+ f"- Source name: {SOURCE_NAME}",
634
+ "",
635
+ "## License",
636
+ "",
637
+ LICENSE,
638
+ "",
639
+ "Official federal statutes and regulations published on Gesetze im Internet are",
640
+ "amtliche Werke under § 5 Abs. 1 UrhG and are not protected by copyright.",
641
+ "",
642
+ "## Timing",
643
+ "",
644
+ f"- Start (UTC): {iso_z(start)}",
645
+ f"- Start (PT): {iso_pt(start)}",
646
+ f"- End (UTC): {iso_z(end)}",
647
+ f"- End (PT): {iso_pt(end)}",
648
+ f"- Elapsed: {elapsed:.1f} s ({elapsed/60:.1f} min)",
649
+ "",
650
+ "## Counts",
651
+ "",
652
+ f"- TOC items: {toc_count}",
653
+ f"- Instruments written: {ok_count}",
654
+ f"- Skipped (already in index): {skip_count}",
655
+ f"- Failures: {fail_count}",
656
+ f"- index.jsonl lines: {ok_count}",
657
+ f"- Total JSON bytes: {total_bytes} ({total_bytes/1_000_000:.2f} MB)",
658
+ "",
659
+ "## Layout",
660
+ "",
661
+ "- `instruments/{safe_id}.json` — one file per statute/regulation/treaty",
662
+ "- `index.jsonl` — one line per instrument",
663
+ "- `logs/collector.log`",
664
+ "- `logs/failures.jsonl`",
665
+ "- `logs/gii-toc.xml` — TOC snapshot used for this run",
666
+ "",
667
+ "## Failures",
668
+ "",
669
+ ]
670
+ if not failed_ids:
671
+ lines.append("None.")
672
+ else:
673
+ lines.append(f"{len(failed_ids)} failed ids:")
674
+ lines.append("")
675
+ for fid in failed_ids:
676
+ lines.append(f"- `{fid}`")
677
+ if notes:
678
+ lines.extend(["", "## Notes", "", notes])
679
+ lines.append("")
680
+ SUMMARY_PATH.write_text("\n".join(lines), encoding="utf-8")
681
+
682
+
683
+ def setup_logging() -> None:
684
+ LOGS.mkdir(parents=True, exist_ok=True)
685
+ INSTRUMENTS.mkdir(parents=True, exist_ok=True)
686
+ log.setLevel(logging.INFO)
687
+ fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
688
+ fh = logging.FileHandler(LOGS / "collector.log", encoding="utf-8")
689
+ fh.setFormatter(fmt)
690
+ sh = logging.StreamHandler(sys.stdout)
691
+ sh.setFormatter(fmt)
692
+ log.handlers.clear()
693
+ log.addHandler(fh)
694
+ log.addHandler(sh)
695
+
696
+
697
+ def fetch_toc() -> list[dict[str, str]]:
698
+ log.info("Downloading TOC %s", TOC_URL)
699
+ payload, status = download_bytes(TOC_URL)
700
+ log.info("TOC HTTP %s bytes=%s", status, len(payload))
701
+ TOC_CACHE.write_bytes(payload)
702
+ items = parse_toc(TOC_CACHE)
703
+ log.info("TOC parsed: %s unique items", len(items))
704
+ return items
705
+
706
+
707
+ def load_toc_items() -> list[dict[str, str]]:
708
+ """Use on-disk catalog; do not re-download the zip corpus."""
709
+ urls_tsv = LOGS / "urls.tsv"
710
+ if TOC_CACHE.exists() and TOC_CACHE.stat().st_size > 100:
711
+ try:
712
+ items = parse_toc(TOC_CACHE)
713
+ if items:
714
+ log.info("TOC from cache file: %s items", len(items))
715
+ return items
716
+ except Exception as e:
717
+ log.warning("TOC cache parse failed: %s", e)
718
+ if urls_tsv.exists():
719
+ items = []
720
+ seen = set()
721
+ with urls_tsv.open("r", encoding="utf-8") as f:
722
+ for line in f:
723
+ line = line.rstrip("\n")
724
+ if not line:
725
+ continue
726
+ parts = line.split("\t")
727
+ slug = parts[0].strip()
728
+ xml_url = parts[1].strip() if len(parts) > 1 else f"https://www.gesetze-im-internet.de/{slug}/xml.zip"
729
+ title = parts[2] if len(parts) > 2 else ""
730
+ if not slug or slug in seen:
731
+ continue
732
+ seen.add(slug)
733
+ items.append({"slug": slug, "title": title, "xml_url": https_url(xml_url)})
734
+ log.info("TOC from urls.tsv: %s items", len(items))
735
+ return items
736
+ return fetch_toc()
737
+
738
+
739
+ def list_finished_zips() -> list[Path]:
740
+ if not CACHE.exists():
741
+ return []
742
+ out = []
743
+ for pth in CACHE.iterdir():
744
+ if not pth.is_file():
745
+ continue
746
+ if pth.suffix != ".zip":
747
+ continue
748
+ if pth.name.endswith(".part") or pth.name.endswith(".tmp"):
749
+ continue
750
+ try:
751
+ if pth.stat().st_size <= 32:
752
+ continue
753
+ except OSError:
754
+ continue
755
+ out.append(pth)
756
+ return out
757
+
758
+
759
+ def de_downloaders_running() -> bool:
760
+ try:
761
+ import subprocess
762
+ proc = subprocess.run(["ps", "ax", "-o", "args="], capture_output=True, text=True, timeout=5)
763
+ text = proc.stdout or ""
764
+ except Exception:
765
+ return False
766
+ for line in text.splitlines():
767
+ if "fetch_one.sh" in line:
768
+ return True
769
+ if "curl" in line and "gesetze-im-internet.de" in line and "/xml.zip" in line:
770
+ return True
771
+ return False
772
+
773
+
774
+ def part_files() -> list[Path]:
775
+ if not CACHE.exists():
776
+ return []
777
+ return [p for p in CACHE.iterdir() if p.name.endswith(".part")]
778
+
779
+
780
+ def record_needs_reparse(path: Path) -> bool:
781
+ if not path.exists() or path.stat().st_size < 20:
782
+ return True
783
+ head = path.read_bytes()[:6000].decode("utf-8", errors="replace")
784
+ if '"source_type":"gesetze_im_internet"' not in head and '"source_type": "gesetze_im_internet"' not in head:
785
+ return True
786
+ if '"retrieved_at"' not in head:
787
+ return True
788
+ if '"jurisdiction":"DE"' not in head and '"jurisdiction": "DE"' not in head:
789
+ return True
790
+ return False
791
+
792
+
793
+ def load_written_stems() -> set[str]:
794
+ done: set[str] = set()
795
+ if INSTRUMENTS.exists():
796
+ for pth in INSTRUMENTS.glob("*.json"):
797
+ if pth.name.startswith("."):
798
+ continue
799
+ done.add(pth.stem)
800
+ return done
801
+
802
+
803
+ def parse_zips_parallel(items: list[dict[str, str]], start: datetime, toc_count: int) -> tuple[int, int, list[str]]:
804
+ """CPU-parallel parse of finished zips. Skip ids already correctly written."""
805
+ INSTRUMENTS.mkdir(parents=True, exist_ok=True)
806
+ LOGS.mkdir(parents=True, exist_ok=True)
807
+ pending = []
808
+ skip = 0
809
+ for it in items:
810
+ slug = it["slug"]
811
+ sid = safe_id(slug)
812
+ out = INSTRUMENTS / f"{sid}.json"
813
+ if out.exists() and not record_needs_reparse(out):
814
+ skip += 1
815
+ continue
816
+ zip_path = CACHE / f"{slug}.zip"
817
+ if (CACHE / f"{slug}.zip.part").exists():
818
+ continue
819
+ if not zip_path.exists():
820
+ continue
821
+ pending.append(it)
822
+ log.info("parse batch pending=%s skip_ok=%s workers=%s", len(pending), skip, PARSE_WORKERS)
823
+ fail_count = 0
824
+ failed_ids: list[str] = []
825
+ ok_count = 0
826
+ if not pending:
827
+ return ok_count, fail_count, failed_ids
828
+ processed = 0
829
+ t0 = time.time()
830
+ with ProcessPoolExecutor(max_workers=PARSE_WORKERS) as ex:
831
+ futs = {ex.submit(process_cache_item, it): it for it in pending}
832
+ for fut in as_completed(futs):
833
+ processed += 1
834
+ res = fut.result()
835
+ if res.get("ok"):
836
+ ok_count += 1
837
+ row = res.get("row")
838
+ if row:
839
+ append_index(row)
840
+ else:
841
+ if res.get("transient"):
842
+ pass
843
+ else:
844
+ fail_count += 1
845
+ failed_ids.append(res.get("id") or "?")
846
+ append_failure({
847
+ "id": res.get("id"),
848
+ "error": res.get("error"),
849
+ "ts": iso_z(now_utc()),
850
+ "status": "failed",
851
+ })
852
+ if processed % 100 == 0 or processed == len(pending):
853
+ rate = processed / max(time.time() - t0, 0.001)
854
+ log.info(
855
+ "parse progress %s/%s ok=%s fail=%s rate=%.1f/s",
856
+ processed, len(pending), ok_count, fail_count, rate,
857
+ )
858
+ rewrite_summary_from_disk(items, start, failed_ids)
859
+ return ok_count, fail_count, failed_ids
860
+
861
+
862
+ def cleanup_stripped_filenames(items: list[dict[str, str]]) -> int:
863
+ """Remove leftover files from old safe_id() that stripped leading underscores."""
864
+ wanted = {safe_id(it["slug"]) + ".json" for it in items}
865
+ removed = 0
866
+ if not INSTRUMENTS.exists():
867
+ return 0
868
+ for pth in list(INSTRUMENTS.glob("*.json")):
869
+ if pth.name.startswith("."):
870
+ continue
871
+ if pth.name in wanted:
872
+ continue
873
+ # only drop the 35 stripped-underscore leftovers, not unknowns
874
+ if pth.stem and not pth.stem.startswith("_"):
875
+ unders = INSTRUMENTS / f"_{pth.stem}.json"
876
+ if unders.exists() and unders.name in wanted:
877
+ pth.unlink()
878
+ removed += 1
879
+ return removed
880
+
881
+
882
+ def download_missing(items: list[dict[str, str]]) -> list[str]:
883
+ missing = []
884
+ for it in items:
885
+ z = CACHE / f"{it['slug']}.zip"
886
+ if z.exists() and z.stat().st_size > 32:
887
+ continue
888
+ missing.append(it)
889
+ if not missing:
890
+ log.info("no missing TOC zips")
891
+ return []
892
+ log.info("fetching %s missing TOC slugs (not a full re-download)", len(missing))
893
+ CACHE.mkdir(parents=True, exist_ok=True)
894
+ failed = []
895
+
896
+ def one(it: dict[str, str]) -> dict[str, Any]:
897
+ slug = it["slug"]
898
+ url = it["xml_url"]
899
+ out = CACHE / f"{slug}.zip"
900
+ if out.exists() and out.stat().st_size > 32:
901
+ return {"ok": True, "id": slug, "skipped": True}
902
+ tmp = CACHE / f"{slug}.zip.part"
903
+ try:
904
+ payload, status = download_bytes(url)
905
+ tmp.write_bytes(payload)
906
+ os.replace(tmp, out)
907
+ return {"ok": True, "id": slug, "bytes": len(payload), "status": status}
908
+ except Exception as e:
909
+ try:
910
+ tmp.unlink(missing_ok=True)
911
+ except Exception:
912
+ pass
913
+ return {"ok": False, "id": slug, "error": f"{type(e).__name__}: {e}"}
914
+
915
+ with ThreadPoolExecutor(max_workers=4) as ex:
916
+ futs = [ex.submit(one, it) for it in missing]
917
+ for fut in as_completed(futs):
918
+ res = fut.result()
919
+ if not res.get("ok"):
920
+ failed.append(res.get("id") or "?")
921
+ append_failure({
922
+ "id": res.get("id"),
923
+ "error": res.get("error"),
924
+ "ts": iso_z(now_utc()),
925
+ "status": "download_failed",
926
+ })
927
+ log.error("missing fetch FAIL %s %s", res.get("id"), res.get("error"))
928
+ else:
929
+ log.info("missing fetch OK %s", res.get("id"))
930
+ return failed
931
+
932
+
933
+ def rewrite_summary_from_disk(items: list[dict[str, str]], start: datetime, failed_ids: list[str] | None = None) -> None:
934
+ toc_count = len(items)
935
+ toc_slugs = {it["slug"] for it in items}
936
+ files = [p for p in INSTRUMENTS.glob("*.json") if not p.name.startswith(".")] if INSTRUMENTS.exists() else []
937
+ n_files = len(files)
938
+ total_bytes = 0
939
+ status_hist: dict[str, int] = {}
940
+ parsed_slugs: set[str] = set()
941
+ for pth in files:
942
+ total_bytes += pth.stat().st_size
943
+ parsed_slugs.add(pth.stem)
944
+ # law_status from filename match is enough for histogram; sample via index
945
+ index_lines = 0
946
+ index_ids: set[str] = set()
947
+ if INDEX_PATH.exists():
948
+ with INDEX_PATH.open("r", encoding="utf-8") as f:
949
+ for line in f:
950
+ if not line.strip():
951
+ continue
952
+ index_lines += 1
953
+ try:
954
+ rec = json.loads(line)
955
+ iid = rec.get("id")
956
+ if iid:
957
+ index_ids.add(iid)
958
+ st = rec.get("law_status")
959
+ if st:
960
+ status_hist[st] = status_hist.get(st, 0) + 1
961
+ except Exception:
962
+ pass
963
+ # unique latest status: recount from last index occurrence is hard; compute from files if cheap
964
+ cache_zips = len(list_finished_zips())
965
+ parts = len(part_files())
966
+ missing_toc = sorted(toc_slugs - parsed_slugs)
967
+ failed_ids = failed_ids or []
968
+ extra = sorted(parsed_slugs - toc_slugs)
969
+ coverage = "full" if not missing_toc and not failed_ids else "catalog-backed incomplete"
970
+ end = now_utc()
971
+ elapsed = (end - start).total_seconds()
972
+ hist = ", ".join(f"{k}={v}" for k, v in sorted(status_hist.items())) or "n/a (see instruments)"
973
+ lines = [
974
+ "# German federal law corpus (Bundesrecht)",
975
+ "",
976
+ "- jurisdiction: DE",
977
+ "- source: Bundesministerium der Justiz / gesetze-im-internet.de",
978
+ f"- last_run_retrieved_at: {iso_z(end)} (PT: {iso_pt(end)})",
979
+ f"- instruments_json: {n_files}",
980
+ f"- index_jsonl_lines: {index_lines}",
981
+ f"- index_jsonl_distinct_ids: {len(index_ids)}",
982
+ f"- discovered (TOC): {toc_count}",
983
+ f"- fetched (cache zips): {cache_zips}",
984
+ f"- parsed: {n_files}",
985
+ f"- skipped: 0",
986
+ f"- failed: {len(failed_ids)}",
987
+ f"- law_status: {hist}",
988
+ f"- coverage: {coverage}",
989
+ f"- notes: source_type=gesetze_im_internet; parse from cache xml.zip; fail path logs/failures.jsonl",
990
+ "",
991
+ "## Source",
992
+ "",
993
+ "- Site: https://www.gesetze-im-internet.de/",
994
+ f"- TOC: {TOC_URL}",
995
+ "- Per-instrument XML zip: https://www.gesetze-im-internet.de/{slug}/xml.zip",
996
+ f"- Publisher: {PUBLISHER}",
997
+ f"- Source name: {SOURCE_NAME}",
998
+ f"- source_type: gesetze_im_internet",
999
+ "",
1000
+ "## License",
1001
+ "",
1002
+ LICENSE,
1003
+ "",
1004
+ "Official federal statutes and regulations published on Gesetze im Internet are",
1005
+ "amtliche Werke under § 5 Abs. 1 UrhG and are not protected by copyright.",
1006
+ "",
1007
+ "## Timing",
1008
+ "",
1009
+ f"- Start (UTC): {iso_z(start)}",
1010
+ f"- Start (PT): {iso_pt(start)}",
1011
+ f"- End (UTC): {iso_z(end)}",
1012
+ f"- End (PT): {iso_pt(end)}",
1013
+ f"- Elapsed: {elapsed:.1f} s ({elapsed/60:.1f} min)",
1014
+ "",
1015
+ "## Counts",
1016
+ "",
1017
+ f"- TOC items: {toc_count}",
1018
+ f"- Cache zips (finished): {cache_zips}",
1019
+ f"- In-progress .part: {parts}",
1020
+ f"- Instruments written: {n_files}",
1021
+ f"- index.jsonl lines: {index_lines} (append-only; distinct ids {len(index_ids)})",
1022
+ f"- Failures: {len(failed_ids)}",
1023
+ f"- TOC slugs missing parse:{len(missing_toc)}",
1024
+ f"- Extra files not in TOC: {len(extra)}",
1025
+ f"- Total JSON bytes: {total_bytes} ({total_bytes/1_000_000:.2f} MB)",
1026
+ f"- Fail path: {FAILURES_PATH}",
1027
+ "",
1028
+ "## Layout",
1029
+ "",
1030
+ "- `instruments/{id}.json` — one file per statute/regulation (id = GII URL slug)",
1031
+ "- `cache/{slug}.zip` — official xml.zip payloads",
1032
+ "- `index.jsonl` — append-only",
1033
+ "- `logs/collector.log`",
1034
+ "- `logs/failures.jsonl`",
1035
+ "- `logs/gii-toc.xml` / `logs/urls.tsv`",
1036
+ "",
1037
+ "## Failures",
1038
+ "",
1039
+ ]
1040
+ if not failed_ids and not missing_toc:
1041
+ lines.append("None.")
1042
+ else:
1043
+ if failed_ids:
1044
+ lines.append(f"{len(failed_ids)} failed ids:")
1045
+ lines.append("")
1046
+ for fid in failed_ids[:200]:
1047
+ lines.append(f"- `{fid}`")
1048
+ if len(failed_ids) > 200:
1049
+ lines.append(f"- … {len(failed_ids)-200} more in {FAILURES_PATH}")
1050
+ if missing_toc:
1051
+ lines.append("")
1052
+ lines.append(f"{len(missing_toc)} TOC slugs not yet parsed (see cache):")
1053
+ lines.append("")
1054
+ for fid in missing_toc[:50]:
1055
+ lines.append(f"- `{fid}`")
1056
+ if len(missing_toc) > 50:
1057
+ lines.append(f"- … {len(missing_toc)-50} more")
1058
+ lines.append("")
1059
+ SUMMARY_PATH.write_text("\n".join(lines), encoding="utf-8")
1060
+
1061
+
1062
+ def wait_downloads_idle(idle_sec: float = 60.0, start: datetime | None = None, items: list | None = None) -> None:
1063
+ last_active = time.time() if (de_downloaders_running() or part_files()) else time.time() - idle_sec
1064
+ if not de_downloaders_running() and not part_files():
1065
+ log.info("downloaders already idle")
1066
+ return
1067
+ log.info("waiting for downloaders idle %.0fs (will keep parsing new zips)", idle_sec)
1068
+ while True:
1069
+ running = de_downloaders_running()
1070
+ parts = part_files()
1071
+ if running or parts:
1072
+ last_active = time.time()
1073
+ log.info("downloaders active fetch_one/curl=%s parts=%s", running, len(parts))
1074
+ if items is not None and start is not None:
1075
+ parse_zips_parallel(items, start, len(items))
1076
+ time.sleep(5)
1077
+ continue
1078
+ waited = time.time() - last_active
1079
+ if waited >= idle_sec:
1080
+ log.info("downloaders idle for %.1fs", waited)
1081
+ return
1082
+ time.sleep(min(5, idle_sec - waited + 0.1))
1083
+
1084
+
1085
+ def orchestrate() -> int:
1086
+ setup_logging()
1087
+ CACHE.mkdir(parents=True, exist_ok=True)
1088
+ INSTRUMENTS.mkdir(parents=True, exist_ok=True)
1089
+ start = now_utc()
1090
+ log.info("START parse-from-cache orchestrate PARSE_WORKERS=%s", PARSE_WORKERS)
1091
+ items = load_toc_items()
1092
+ toc_count = len(items)
1093
+ log.info("catalog size %s; finished zips %s; parts %s", toc_count, len(list_finished_zips()), len(part_files()))
1094
+
1095
+ # Parse whatever is already on disk without blocking leftover downloads.
1096
+ parse_zips_parallel(items, start, toc_count)
1097
+ removed = cleanup_stripped_filenames(items)
1098
+ if removed:
1099
+ log.info("removed %s leftover stripped-underscore filenames", removed)
1100
+
1101
+ wait_downloads_idle(60.0, start=start, items=items)
1102
+
1103
+ # After idle + no .part, fetch TOC slugs still missing, then parse those.
1104
+ if part_files():
1105
+ wait_downloads_idle(60.0, start=start, items=items)
1106
+ dl_fail = download_missing(items)
1107
+ if dl_fail:
1108
+ log.warning("missing download failures: %s", dl_fail[:20])
1109
+ ok, fail, failed_ids = parse_zips_parallel(items, start, toc_count)
1110
+ failed_ids = list(dict.fromkeys(failed_ids + dl_fail))
1111
+ removed = cleanup_stripped_filenames(items)
1112
+ if removed:
1113
+ log.info("removed %s leftover stripped-underscore filenames", removed)
1114
+ rewrite_summary_from_disk(items, start, failed_ids)
1115
+
1116
+ n_files = sum(1 for pth in INSTRUMENTS.glob("*.json") if not pth.name.startswith("."))
1117
+ cache_n = len(list_finished_zips())
1118
+ total_bytes = sum(pth.stat().st_size for pth in INSTRUMENTS.glob("*.json") if not pth.name.startswith("."))
1119
+ log.info(
1120
+ "DONE toc=%s cache_zips=%s files=%s fail=%s bytes=%s fail_path=%s",
1121
+ toc_count, cache_n, n_files, len(failed_ids), total_bytes, FAILURES_PATH,
1122
+ )
1123
+ missing = toc_count - n_files
1124
+ return 0 if missing == 0 and not failed_ids else 1
1125
+
1126
+
1127
+ def main() -> int:
1128
+ mode = "run"
1129
+ if len(sys.argv) > 1:
1130
+ a = sys.argv[1]
1131
+ if a in {"--parse", "--parse-cache", "parse"}:
1132
+ mode = "parse"
1133
+ elif a in {"--download", "download"}:
1134
+ mode = "download"
1135
+ elif a in {"--run", "run"}:
1136
+ mode = "run"
1137
+ if mode in {"run", "parse"}:
1138
+ return orchestrate()
1139
+ # legacy download+parse path (network). Prefer cache hits.
1140
+ setup_logging()
1141
+ start = now_utc()
1142
+ log.info("START collector workers=%s (download mode)", WORKERS)
1143
+ items = load_toc_items()
1144
+ toc_count = len(items)
1145
+ pending = []
1146
+ skip_count = 0
1147
+ for it in items:
1148
+ sid = safe_id(it["slug"])
1149
+ out = INSTRUMENTS / f"{sid}.json"
1150
+ if out.exists() and not record_needs_reparse(out):
1151
+ skip_count += 1
1152
+ else:
1153
+ pending.append(it)
1154
+ log.info("Pending: %s skip=%s", len(pending), skip_count)
1155
+ fail_count = 0
1156
+ failed_ids: list[str] = []
1157
+ processed = 0
1158
+ t0 = time.time()
1159
+ with ThreadPoolExecutor(max_workers=WORKERS) as ex:
1160
+ futs = {ex.submit(process_safe, it): it for it in pending}
1161
+ for fut in as_completed(futs):
1162
+ processed += 1
1163
+ res = fut.result()
1164
+ if not res.get("ok"):
1165
+ fail_count += 1
1166
+ failed_ids.append(res.get("id") or "?")
1167
+ if processed % 50 == 0 or processed == len(pending):
1168
+ rate = processed / max(time.time() - t0, 0.001)
1169
+ log.info("download-mode progress %s/%s fail=%s rate=%.1f/s", processed, len(pending), fail_count, rate)
1170
+ rewrite_summary_from_disk(items, start, failed_ids)
1171
+ return 0 if fail_count == 0 else 1
1172
+
1173
+
1174
+ if __name__ == "__main__":
1175
+ sys.exit(main())