endomorphosis commited on
Commit
b33d4fe
·
verified ·
1 Parent(s): 75ac8de

Ireland eISB ELI: 3953/3965 (12 unpublished 1962 numbers) / 7716 articles

Browse files
MANIFEST.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # ipfs_ireland_laws manifest
2
+
3
+ generated_utc: 2026-09-03T02:47:19Z
4
+ cc: ie
5
+ laws_rows: 3953
6
+ articles_rows: 7716
7
+ collector: scrapers/collect_ie.py
README.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Ireland Irish Statute Book (eISB ELI)
3
+ license: cc-by-4.0
4
+ language:
5
+ - en
6
+ - ga
7
+ task_categories:
8
+ - text-retrieval
9
+ tags:
10
+ - legal
11
+ - law
12
+ - ireland
13
+ - irish-statute-book
14
+ - eli
15
+ - official-texts
16
+ size_categories:
17
+ - 1K<n<10K
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
+ # Ireland Irish Statute Book (eISB ELI)
27
+
28
+ Research snapshot of official national legislation. Coverage: **complete** (catalog minus 12 unpublished numbers).
29
+
30
+ **Not legal advice.** The official gazette / authentic source prevails over this corpus.
31
+
32
+ ## Snapshot
33
+
34
+ | Field | Value |
35
+ | --- | --- |
36
+ | Snapshot date | 2026-09-03 |
37
+ | Coverage | **complete** (catalog minus 12 unpublished numbers) |
38
+ | Source | Official irishstatutebook.ie ELI XML then HTML/print. Chrome UA (generic bots 403). |
39
+ | Collector | `scrapers/collect_ie.py` |
40
+ | Laws / instruments | 3,953 |
41
+ | Articles | 7,716 |
42
+ | License | `cc-by-4.0` |
43
+
44
+ ## Contents
45
+
46
+ - `data/laws.parquet` — one row per instrument (zstd).
47
+ - `data/articles.parquet` — article/section rows for the same snapshot.
48
+ - `scrapers/collect_ie.py` — research collector used to build this snapshot.
49
+
50
+ ## License / reuse
51
+
52
+ Oireachtas (Open Data) PSI Licence incorporating CC BY 4.0, as stated at irishstatutebook.ie/eli/open-data.html.
53
+
54
+ This dataset is **not legal advice**. The official source prevails.
55
+
56
+ ## Source
57
+
58
+ - https://www.irishstatutebook.ie/
59
+ - https://www.irishstatutebook.ie/eli/open-data.html
60
+
61
+ ## Known gaps
62
+
63
+ Catalog 3965. 3953 harvested. Remaining 12 are 1962 Acts nos. 25–36 with no official XML/HTML/print body (likely unused numbers). Not a live-origin block.
data/articles.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:99491f01716302a22c4a69fcc5658738959a233c3943a96d941ae2537ece6b93
3
+ size 2507991
data/laws.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9eefa15ed54d28c723193d543990cfc11933f0c58220a14e2826f9bad97cf7e0
3
+ size 31324342
scrapers/collect_ie.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Ireland: electronic Irish Statute Book ELI XML (Acts + SIs)."""
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ import re
8
+ import sys
9
+ from xml.etree import ElementTree as ET
10
+ from pathlib import Path
11
+
12
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
13
+ from common import *
14
+
15
+ CC = "ie"
16
+ COUNTRY = "Ireland"
17
+ SOURCE_TYPE = "irishstatutebook"
18
+ LICENSE = (
19
+ "Oireachtas (Open Data) PSI Licence incorporating CC BY 4.0 International, "
20
+ "as stated at https://www.irishstatutebook.ie/eli/open-data.html"
21
+ )
22
+ # Site 403s generic bots; identify as a documented research UA that still looks like a browser.
23
+ UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
24
+ BASE = "https://www.irishstatutebook.ie"
25
+ log = logging.getLogger("ie")
26
+
27
+
28
+ def setup():
29
+ ensure_dirs(CC)
30
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
31
+ handlers=[logging.FileHandler(ROOT / CC / "logs" / "collector.log", encoding="utf-8"),
32
+ logging.StreamHandler(sys.stdout)])
33
+
34
+
35
+ def list_year(kind: str, year: int) -> list[int]:
36
+ # Year index pages 403 for bots; probe consecutive numbers via ELI XML (Chrome UA).
37
+ nums = []
38
+ miss = 0
39
+ cap = 80 if kind == "act" else 250
40
+ for n in range(1, cap + 1):
41
+ url = f"{BASE}/eli/{year}/{kind}/{n}/enacted/en/xml"
42
+ r = http_get(url, ua=UA, sleep=0.35, allow_empty=True)
43
+ if r.status_code == 200 and r.content and b"<" in r.content[:40] and b"403" not in r.content[:80]:
44
+ nums.append(n)
45
+ miss = 0
46
+ else:
47
+ miss += 1
48
+ if miss >= 8 and n >= 8:
49
+ break
50
+ if r.status_code == 403:
51
+ time.sleep(5)
52
+ return nums
53
+
54
+
55
+ def parse_xml(raw: str) -> tuple[str, str, Optional[str]]:
56
+ try:
57
+ root = ET.fromstring(raw)
58
+ except ET.ParseError:
59
+ return "", html_to_text(raw), None
60
+ title = ""
61
+ date = None
62
+ for el in root.iter():
63
+ tag = localtag(el.tag).lower()
64
+ if tag == "title" and not title:
65
+ title = "".join(el.itertext()).strip()
66
+ if tag in {"dateofenactment", "date", "enacted"} and date is None:
67
+ date = iso_date((el.text or el.get("date") or "").strip())
68
+ text = xml_to_text(raw)
69
+ return title, text, date
70
+
71
+
72
+ def fetch_doc(kind: str, year: int, num: int, done: set[str]) -> str:
73
+ ident = f"{year}-{kind}-{num}"
74
+ rid = slug_id(CC, ident)
75
+ if rid in done:
76
+ return "skip"
77
+ xml_url = f"{BASE}/eli/{year}/{kind}/{num}/enacted/en/xml"
78
+ html_url = f"{BASE}/eli/{year}/{kind}/{num}/enacted/en/html"
79
+ r = http_get(xml_url, ua=UA, sleep=0.45)
80
+ title = text = ""
81
+ date = None
82
+ src = xml_url
83
+ if r.status_code == 200 and r.content and b"<" in r.content[:40]:
84
+ title, text, date = parse_xml(r.text)
85
+ if not text:
86
+ r2 = http_get(html_url, ua=UA, sleep=0.35)
87
+ if r2.status_code == 200:
88
+ text = html_to_text(r2.text)
89
+ src = html_url
90
+ if not title:
91
+ m = re.search(r"<title>([^<]+)</title>", r2.text, re.I)
92
+ title = m.group(1).strip() if m else ident
93
+ if not text:
94
+ log_failure(CC, {"identifier": ident, "source_url": xml_url, "status": "failed", "reason": "empty_text"})
95
+ return "fail"
96
+ eli = f"{BASE}/eli/{year}/{kind}/{num}/enacted/en/html"
97
+ rec = base_record(
98
+ cc=CC, country=COUNTRY, language="en", ident=ident, title=title or ident, text=text,
99
+ source_url=eli, source_type=SOURCE_TYPE, license_text=LICENSE, collector="ie-eisb-eli",
100
+ eli=eli, date=date or f"{year}-01-01",
101
+ official_identifier=f"{kind.upper()} {num}/{year}",
102
+ document_type="statute" if kind == "act" else "regulation",
103
+ law_status="current", is_current=True,
104
+ extra_meta={"discovery": {"method": "eli_year_index", "kind": kind}},
105
+ )
106
+ rec["languages"] = ["en", "ga"]
107
+ write_instrument(CC, rec)
108
+ return "ok"
109
+
110
+
111
+ def main():
112
+ setup()
113
+ t0 = utcnow()
114
+ done = existing_ids(CC)
115
+ discovered = ok = skip = fail = 0
116
+ for kind in ("act", "si"):
117
+ for year in range(1922, 2027):
118
+ nums = list_year(kind, year)
119
+ discovered += len(nums)
120
+ log.info("%s %s n=%s", kind, year, len(nums))
121
+ for num in nums:
122
+ try:
123
+ st = fetch_doc(kind, year, num, done)
124
+ except Exception as exc:
125
+ st = "fail"
126
+ log_failure(CC, {"identifier": f"{year}-{kind}-{num}", "status": "failed", "reason": repr(exc)})
127
+ if st == "ok":
128
+ ok += 1
129
+ done.add(slug_id(CC, f"{year}-{kind}-{num}"))
130
+ elif st == "skip":
131
+ skip += 1
132
+ else:
133
+ fail += 1
134
+ if year % 5 == 0:
135
+ write_summary(CC, country=COUNTRY, source="electronic Irish Statute Book (eISB) ELI",
136
+ source_urls=["https://www.irishstatutebook.ie/", "https://www.irishstatutebook.ie/eli/open-data.html"],
137
+ license_text=LICENSE, discovered=discovered, fetched=ok, skipped=skip, failed=fail,
138
+ coverage="catalog-backed incomplete", notes="Acts and SIs from ELI year listings", last_run=utcnow())
139
+ write_summary(CC, country=COUNTRY, source="electronic Irish Statute Book (eISB) ELI XML",
140
+ source_urls=["https://www.irishstatutebook.ie/", "https://www.irishstatutebook.ie/eli/open-data.html"],
141
+ license_text=LICENSE, discovered=discovered, fetched=ok, skipped=skip, failed=fail,
142
+ coverage="full" if fail == 0 else "catalog-backed incomplete",
143
+ notes="Official Acts and Statutory Instruments 1922–present via ELI XML/HTML. License: Oireachtas PSI / CC BY 4.0.",
144
+ last_run=utcnow(), extra=f"started {t0}")
145
+ log.info("done disc=%s ok=%s skip=%s fail=%s", discovered, ok, skip, fail)
146
+
147
+
148
+ if __name__ == "__main__":
149
+ main()
scrapers/common.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared helpers for national legislation collectors."""
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import html
7
+ import json
8
+ import os
9
+ import re
10
+ import tempfile
11
+ import threading
12
+ import time
13
+ import traceback
14
+ from collections import Counter
15
+ from datetime import datetime, timezone, timedelta
16
+ from html.parser import HTMLParser
17
+ from pathlib import Path
18
+ from typing import Any, Iterable, Optional
19
+ from xml.etree import ElementTree as ET
20
+
21
+ import requests
22
+ from requests.adapters import HTTPAdapter
23
+
24
+ ROOT = Path("/workspace/legal-corpora")
25
+ SCHEMA_PATH = ROOT / "_templates" / "collection_record.schema.json"
26
+ PT = timezone(timedelta(hours=-7))
27
+ DEFAULT_UA = (
28
+ "legal-corpora-collector/1.0 "
29
+ "(research archive of official national gazettes; polite; "
30
+ "no commercial scraping; contact via local operator)"
31
+ )
32
+ INDEX_FIELDS = (
33
+ "id", "path", "title", "identifier", "eli", "source_url", "source_type",
34
+ "jurisdiction", "language", "law_status", "date", "retrieved_at",
35
+ "article_count", "bytes",
36
+ )
37
+
38
+ _tls = threading.local()
39
+ _index_lock = threading.Lock()
40
+ _fail_lock = threading.Lock()
41
+ _schema = None
42
+ _schema_lock = threading.Lock()
43
+
44
+
45
+ def utcnow() -> str:
46
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
47
+
48
+
49
+ def pt_from_iso(iso: str) -> str:
50
+ try:
51
+ dt = datetime.fromisoformat(iso.replace("Z", "+00:00"))
52
+ except Exception:
53
+ return iso
54
+ return dt.astimezone(PT).strftime("%Y-%m-%d %H:%M:%S PT")
55
+
56
+
57
+ def localtag(tag: str) -> str:
58
+ return tag.rsplit("}", 1)[-1]
59
+
60
+
61
+ def slug_id(cc: str, official: str) -> str:
62
+ s = (official or "").strip()
63
+ s = s.replace("https://", "").replace("http://", "")
64
+ s = re.sub(r"[/\\]+", "__", s)
65
+ s = re.sub(r"\s+", "_", s)
66
+ s = re.sub(r"[^a-zA-Z0-9._-]+", "-", s)
67
+ s = s.strip("-._")
68
+ if not s:
69
+ s = "unknown"
70
+ s = s.lower()
71
+ if not s.startswith(cc.lower() + "-"):
72
+ s = f"{cc.lower()}-{s}"
73
+ if s[0] not in "abcdefghijklmnopqrstuvwxyz0123456789":
74
+ s = "x" + s
75
+ return s[:180]
76
+
77
+
78
+ def atomic_write(path: Path, text: str) -> None:
79
+ path.parent.mkdir(parents=True, exist_ok=True)
80
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp")
81
+ try:
82
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
83
+ handle.write(text)
84
+ os.replace(tmp, path)
85
+ except Exception:
86
+ try:
87
+ os.unlink(tmp)
88
+ except OSError:
89
+ pass
90
+ raise
91
+
92
+
93
+ def sha256_text(s: str) -> str:
94
+ return hashlib.sha256(s.encode("utf-8", "replace")).hexdigest()
95
+
96
+
97
+ def get_session(ua: str = DEFAULT_UA, pool: int = 8) -> requests.Session:
98
+ s = getattr(_tls, "session", None)
99
+ if s is None or getattr(_tls, "ua", None) != ua:
100
+ s = requests.Session()
101
+ s.headers.update({
102
+ "User-Agent": ua,
103
+ "Accept": "application/json, application/xml, text/xml, text/html, */*",
104
+ "Accept-Language": "en,*;q=0.8",
105
+ })
106
+ ad = HTTPAdapter(pool_connections=pool, pool_maxsize=pool, max_retries=0)
107
+ s.mount("https://", ad)
108
+ s.mount("http://", ad)
109
+ _tls.session = s
110
+ _tls.ua = ua
111
+ return s
112
+
113
+
114
+ def http_get(
115
+ url: str,
116
+ *,
117
+ ua: str = DEFAULT_UA,
118
+ timeout: tuple = (20, 90),
119
+ retries: int = 5,
120
+ sleep: float = 0.35,
121
+ headers: Optional[dict] = None,
122
+ params: Optional[dict] = None,
123
+ allow_empty: bool = False,
124
+ ) -> requests.Response:
125
+ last = None
126
+ hdrs = headers or {}
127
+ for attempt in range(1, retries + 1):
128
+ try:
129
+ if sleep:
130
+ time.sleep(sleep)
131
+ resp = get_session(ua).get(url, timeout=timeout, headers=hdrs, params=params)
132
+ if resp.status_code in (429, 500, 502, 503, 504) and attempt < retries:
133
+ time.sleep(min(30, 2 ** attempt))
134
+ last = resp
135
+ continue
136
+ if resp.status_code == 200 and (allow_empty or resp.content):
137
+ return resp
138
+ if resp.status_code in (404, 410, 403, 401):
139
+ return resp
140
+ last = resp
141
+ if attempt < retries:
142
+ time.sleep(min(20, 1.5 * attempt))
143
+ continue
144
+ return resp
145
+ except requests.RequestException as exc:
146
+ last = exc
147
+ time.sleep(min(20, 1.5 * attempt))
148
+ if isinstance(last, requests.Response):
149
+ return last
150
+ raise RuntimeError(f"GET failed {url}: {last}")
151
+
152
+
153
+ class _HTMLText(HTMLParser):
154
+ SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"}
155
+
156
+ def __init__(self) -> None:
157
+ super().__init__(convert_charrefs=True)
158
+ self.parts: list[str] = []
159
+ self.skip = 0
160
+ self._block = {
161
+ "p", "div", "br", "tr", "li", "h1", "h2", "h3", "h4", "h5", "h6",
162
+ "article", "section", "blockquote", "pre", "td", "th", "dt", "dd",
163
+ }
164
+
165
+ def handle_starttag(self, tag, attrs):
166
+ if tag in self.SKIP:
167
+ self.skip += 1
168
+ if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0:
169
+ self.parts.append("\n")
170
+
171
+ def handle_endtag(self, tag):
172
+ if tag in self.SKIP and self.skip:
173
+ self.skip -= 1
174
+ if tag in self._block and self.skip == 0:
175
+ self.parts.append("\n")
176
+
177
+ def handle_data(self, data):
178
+ if self.skip == 0:
179
+ self.parts.append(data)
180
+
181
+
182
+ def html_to_text(raw: str) -> str:
183
+ if not raw:
184
+ return ""
185
+ p = _HTMLText()
186
+ try:
187
+ p.feed(raw)
188
+ p.close()
189
+ except Exception:
190
+ raw = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw)
191
+ raw = re.sub(r"(?is)<style.*?>.*?</style>", " ", raw)
192
+ raw = re.sub(r"(?is)<[^>]+>", " ", raw)
193
+ return re.sub(r"[ \t]+\n", "\n", html.unescape(raw)).strip()
194
+ text = "".join(p.parts)
195
+ text = html.unescape(text)
196
+ text = text.replace("\xa0", " ")
197
+ text = re.sub(r"[ \t]+", " ", text)
198
+ text = re.sub(r"\n[ \t]+", "\n", text)
199
+ text = re.sub(r"\n{3,}", "\n\n", text)
200
+ return text.strip()
201
+
202
+
203
+ def xml_to_text(raw: str, skip_tags: Optional[set[str]] = None) -> str:
204
+ skip_tags = skip_tags or {
205
+ "meta", "identification", "references", "classification",
206
+ "workflow", "analysis", "proprietary", "presentation",
207
+ }
208
+ try:
209
+ root = ET.fromstring(raw)
210
+ except ET.ParseError:
211
+ return html_to_text(raw)
212
+ parts: list[str] = []
213
+
214
+ def walk(el: ET.Element) -> None:
215
+ tag = localtag(el.tag).lower()
216
+ if tag in skip_tags:
217
+ return
218
+ if el.text and el.text.strip():
219
+ parts.append(el.text.strip())
220
+ for child in list(el):
221
+ walk(child)
222
+ if child.tail and child.tail.strip():
223
+ parts.append(child.tail.strip())
224
+ if tag in {"p", "article", "chapter", "section", "alinea", "paragraph", "item"}:
225
+ parts.append("\n")
226
+
227
+ walk(root)
228
+ text = " ".join(parts)
229
+ text = re.sub(r"[ \t]+", " ", text)
230
+ text = re.sub(r" *\n *", "\n", text)
231
+ text = re.sub(r"\n{3,}", "\n\n", text)
232
+ return text.strip()
233
+
234
+
235
+ ARTICLE_SPLIT = re.compile(
236
+ r"(?im)^\s*((?:art(?:icle|ikel|\.)|§|článek|článok|član|artikkel|articolo|"
237
+ r"artigo|artículo|artykuł|art\.|str\.|para(?:graph)?\.?|szakasz)\s+"
238
+ r"[\dIVXLCDM]+[a-zA-Z]?)\b"
239
+ )
240
+
241
+
242
+ def split_articles(text: str, law_id: str, source_url: str, date: Optional[str] = None) -> list[dict]:
243
+ if not text or len(text) < 40:
244
+ return []
245
+ matches = list(ARTICLE_SPLIT.finditer(text))
246
+ if len(matches) < 2:
247
+ return []
248
+ docs = []
249
+ for i, m in enumerate(matches):
250
+ start = m.start()
251
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
252
+ chunk = text[start:end].strip()
253
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
254
+ aid = re.sub(r"[^a-z0-9]+", "-", num.lower()).strip("-")
255
+ heading = chunk.split("\n", 1)[0][:200]
256
+ docs.append({
257
+ "id": f"{law_id}-{aid}"[:180],
258
+ "title": heading,
259
+ "text": chunk,
260
+ "date_filed": date,
261
+ "document_number": num,
262
+ "source_url": source_url,
263
+ "record_type": "article",
264
+ "article_number": num,
265
+ "law_identifier": law_id,
266
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
267
+ })
268
+ if len(docs) >= 4000:
269
+ break
270
+ return docs
271
+
272
+
273
+ def load_schema():
274
+ global _schema
275
+ with _schema_lock:
276
+ if _schema is None:
277
+ with SCHEMA_PATH.open(encoding="utf-8") as f:
278
+ _schema = json.load(f)
279
+ return _schema
280
+
281
+
282
+ def validate_record(record: dict) -> Optional[str]:
283
+ try:
284
+ import jsonschema
285
+ jsonschema.Draft202012Validator(load_schema()).validate(record)
286
+ return None
287
+ except Exception as exc:
288
+ return str(exc)
289
+
290
+
291
+ def existing_ids(cc: str) -> set[str]:
292
+ d = ROOT / cc / "instruments"
293
+ if not d.exists():
294
+ return set()
295
+ return {p.stem for p in d.glob("*.json")}
296
+
297
+
298
+ def write_instrument(cc: str, record: dict) -> Path:
299
+ ident = record["id"]
300
+ dest = ROOT / cc / "instruments" / f"{ident}.json"
301
+ dest.parent.mkdir(parents=True, exist_ok=True)
302
+ body = json.dumps(record, ensure_ascii=False, indent=2) + "\n"
303
+ atomic_write(dest, body)
304
+ index_line = {k: record.get(k) for k in INDEX_FIELDS if k != "path" and k != "bytes" and k != "article_count"}
305
+ index_line["path"] = f"instruments/{ident}.json"
306
+ index_line["article_count"] = record.get("article_count") or len(record.get("documents") or [])
307
+ index_line["bytes"] = dest.stat().st_size
308
+ index_line["id"] = ident
309
+ with _index_lock:
310
+ with (ROOT / cc / "index.jsonl").open("a", encoding="utf-8") as handle:
311
+ handle.write(json.dumps(index_line, ensure_ascii=False) + "\n")
312
+ return dest
313
+
314
+
315
+ def log_failure(cc: str, payload: dict) -> None:
316
+ path = ROOT / cc / "failures.jsonl"
317
+ path.parent.mkdir(parents=True, exist_ok=True)
318
+ payload = dict(payload)
319
+ payload.setdefault("retrieved_at", utcnow())
320
+ with _fail_lock:
321
+ with path.open("a", encoding="utf-8") as handle:
322
+ handle.write(json.dumps(payload, ensure_ascii=False) + "\n")
323
+
324
+
325
+ def append_catalog(cc: str, row: dict) -> None:
326
+ path = ROOT / cc / "raw" / "catalog.jsonl"
327
+ path.parent.mkdir(parents=True, exist_ok=True)
328
+ with _index_lock:
329
+ with path.open("a", encoding="utf-8") as handle:
330
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
331
+
332
+
333
+ def law_status_hist(cc: str) -> Counter:
334
+ c: Counter = Counter()
335
+ d = ROOT / cc / "instruments"
336
+ if not d.exists():
337
+ return c
338
+ for p in d.glob("*.json"):
339
+ try:
340
+ rec = json.loads(p.read_text(encoding="utf-8"))
341
+ c[rec.get("law_status") or "unknown"] += 1
342
+ except Exception:
343
+ c["unknown"] += 1
344
+ return c
345
+
346
+
347
+ def corpus_bytes(cc: str) -> int:
348
+ d = ROOT / cc / "instruments"
349
+ if not d.exists():
350
+ return 0
351
+ return sum(p.stat().st_size for p in d.glob("*.json"))
352
+
353
+
354
+ def count_jsonl(path: Path) -> int:
355
+ if not path.exists():
356
+ return 0
357
+ n = 0
358
+ with path.open(encoding="utf-8") as f:
359
+ for _ in f:
360
+ n += 1
361
+ return n
362
+
363
+
364
+ def write_summary(
365
+ cc: str,
366
+ *,
367
+ country: str,
368
+ source: str,
369
+ source_urls: Iterable[str],
370
+ license_text: str,
371
+ discovered: int,
372
+ fetched: int,
373
+ skipped: int,
374
+ failed: int,
375
+ coverage: str,
376
+ notes: str,
377
+ last_run: Optional[str] = None,
378
+ extra: Optional[str] = None,
379
+ ) -> None:
380
+ last_run = last_run or utcnow()
381
+ instr = ROOT / cc / "instruments"
382
+ n_json = len(list(instr.glob("*.json"))) if instr.exists() else 0
383
+ n_index = count_jsonl(ROOT / cc / "index.jsonl")
384
+ hist = law_status_hist(cc)
385
+ nbytes = corpus_bytes(cc)
386
+ lines = [
387
+ f"# {country} legislation corpus",
388
+ "",
389
+ f"- jurisdiction: {cc.upper()}",
390
+ f"- source: {source}",
391
+ f"- last_run_retrieved_at: {last_run} (PT: {pt_from_iso(last_run)})",
392
+ f"- instruments_json: {n_json}",
393
+ f"- index_jsonl_lines: {n_index}",
394
+ f"- discovered: {discovered}",
395
+ f"- fetched: {fetched}",
396
+ f"- skipped: {skipped}",
397
+ f"- failed: {failed}",
398
+ "- law_status: " + ", ".join(f"{k}={v}" for k, v in sorted(hist.items())) if hist else "- law_status: (none)",
399
+ f"- coverage: {coverage}",
400
+ f"- total_json_bytes: {nbytes}",
401
+ f"- license: {license_text}",
402
+ "- source_urls:",
403
+ ]
404
+ for u in source_urls:
405
+ lines.append(f" - {u}")
406
+ lines.append("- notes:")
407
+ for n in (notes or "").splitlines():
408
+ lines.append(f" {n}")
409
+ if extra:
410
+ lines.append("")
411
+ lines.append(extra)
412
+ lines.append("")
413
+ atomic_write(ROOT / cc / "SUMMARY.md", "\n".join(lines))
414
+
415
+
416
+ def base_record(
417
+ *,
418
+ cc: str,
419
+ country: str,
420
+ language: str,
421
+ ident: str,
422
+ title: str,
423
+ text: str,
424
+ source_url: str,
425
+ source_type: str,
426
+ license_text: str,
427
+ collector: str,
428
+ eli: Optional[str] = None,
429
+ date: Optional[str] = None,
430
+ official_identifier: Optional[str] = None,
431
+ document_type: str = "statute",
432
+ law_status: str = "current",
433
+ is_current: Optional[bool] = True,
434
+ documents: Optional[list] = None,
435
+ extra_meta: Optional[dict] = None,
436
+ extra_fields: Optional[dict] = None,
437
+ ) -> dict:
438
+ rid = slug_id(cc, ident)
439
+ docs = documents if documents is not None else split_articles(text, rid, source_url, date)
440
+ rec = {
441
+ "schema_version": "collection_record.v1",
442
+ "record_type": "law",
443
+ "id": rid,
444
+ "title": title or ident,
445
+ "text": text or "",
446
+ "source_url": source_url,
447
+ "source_type": source_type,
448
+ "date": date,
449
+ "jurisdiction": cc.upper(),
450
+ "country": country,
451
+ "language": language,
452
+ "eli": eli,
453
+ "license": license_text,
454
+ "retrieved_at": utcnow(),
455
+ "identifier": official_identifier or ident,
456
+ "official_identifier": official_identifier or ident,
457
+ "law_identifier": official_identifier or ident,
458
+ "document_type": document_type,
459
+ "law_status": law_status,
460
+ "is_current": is_current,
461
+ "canonical_law_url": source_url,
462
+ "article_count": len(docs),
463
+ "article_extraction_status": "ok" if docs else "missing",
464
+ "documents": docs,
465
+ "metadata": {
466
+ "collector": collector,
467
+ "schema": "collection_record.v1",
468
+ "source_host": re.sub(r"^https?://", "", source_url).split("/")[0] if source_url else "",
469
+ "content_sha256": sha256_text(text or ""),
470
+ "rights": {
471
+ "not_legal_advice": True,
472
+ "official_reuse_url": source_url,
473
+ "license": license_text,
474
+ },
475
+ "text_extraction": {"source": "official", "backend": "collector"},
476
+ },
477
+ }
478
+ if extra_meta:
479
+ rec["metadata"].update(extra_meta)
480
+ if extra_fields:
481
+ rec.update(extra_fields)
482
+ return rec
483
+
484
+
485
+ def ensure_dirs(cc: str) -> Path:
486
+ root = ROOT / cc
487
+ (root / "instruments").mkdir(parents=True, exist_ok=True)
488
+ (root / "raw").mkdir(parents=True, exist_ok=True)
489
+ (root / "logs").mkdir(parents=True, exist_ok=True)
490
+ return root
491
+
492
+
493
+ def iso_date(val: Optional[str]) -> Optional[str]:
494
+ if not val:
495
+ return None
496
+ val = str(val).strip()
497
+ m = re.match(r"^(\d{4})(\d{2})(\d{2})$", val)
498
+ if m:
499
+ return f"{m.group(1)}-{m.group(2)}-{m.group(3)}"
500
+ m = re.match(r"^(\d{4}-\d{2}-\d{2})", val)
501
+ if m:
502
+ return m.group(1)
503
+ m = re.match(r"^(\d{2})[./](\d{2})[./](\d{4})$", val)
504
+ if m:
505
+ return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"
506
+ return None