endomorphosis commited on
Commit
5adf94b
·
verified ·
1 Parent(s): b05ea89

UAE federal: 237/237 Constitution+Federal Law+Decree-Law

Browse files
MANIFEST.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ipfs_uae_laws manifest
2
+
3
+ generated_utc: 2026-09-03T02:50:08Z
4
+ cc: ae
5
+ country: United Arab Emirates
6
+ laws_rows: 237
7
+ articles_rows: 182
8
+ laws_bytes: 2179256
9
+ articles_bytes: 84017
10
+ laws_sha256: b7aaf5bc972ec75f99379cb5e87eea144b7906286803d24c08f355ef0bd19698
11
+ articles_sha256: edb2e03006dafa2c8acb32a332f9669428ff5fc1652954c534d130865b37d88b
12
+ laws_parquet: /workspace/legal-corpora/hf-staging/ipfs_uae_laws/data/laws.parquet
13
+ articles_parquet: /workspace/legal-corpora/hf-staging/ipfs_uae_laws/data/articles.parquet
14
+ compression: zstd
15
+ collector: scrapers/collect_ae.py
16
+ license: Official UAE Legislation texts; authentic Official Gazette prevails; not legal advice.
17
+ source: https://uaelegislation.gov.ae/
18
+ gaps: |
19
+ Federal Law / Federal Decree-Law / Constitution from official uaelegislation.gov.ae list API and PDF downloads. Cabinet resolutions excluded. 429/403 uses archive_fallbacks of official URLs. Started 2026-09-03T02:41:24Z.
20
+
21
+ started 2026-09-03T02:41:24Z
README.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: UAE Federal Laws and Constitution (UAE Legislation)
3
+ license: other
4
+ license_name: uae-legislation-terms
5
+ language:
6
+ - en
7
+ task_categories:
8
+ - text-retrieval
9
+ tags:
10
+ - legal
11
+ - law
12
+ - uae
13
+ - uaelegislation
14
+ - official-texts
15
+ size_categories:
16
+ - n<1K
17
+ configs:
18
+ - config_name: laws
19
+ data_files: data/laws.parquet
20
+ default: true
21
+ - config_name: articles
22
+ data_files: data/articles.parquet
23
+ ---
24
+
25
+ # UAE Federal Laws and Constitution (UAE Legislation)
26
+
27
+ Research snapshot of official national legislation from **UAE Legislation (General Secretariat of the UAE Cabinet)**.
28
+
29
+ **Not legal advice.** The official gazette / authentic source prevails over this corpus.
30
+
31
+ ## Snapshot
32
+
33
+ | Field | Value |
34
+ | --- | --- |
35
+ | Snapshot date | 2026-09-03 |
36
+ | Coverage | snapshot |
37
+ | Source | UAE Legislation (General Secretariat of the UAE Cabinet) |
38
+ | Collector | `scrapers/collect_ae.py` |
39
+ | Laws / instruments | 237 |
40
+ | Articles | 182 |
41
+ | Language | en |
42
+ | Jurisdiction | United Arab Emirates |
43
+ | License | `uae-legislation-terms` |
44
+
45
+ ## Contents
46
+
47
+ - `data/laws.parquet` — one row per instrument (LAW_FLAT, zstd).
48
+ - `data/articles.parquet` — article/section rows for the same snapshot.
49
+ - `scrapers/collect_ae.py` — research collector used to build this snapshot.
50
+
51
+ ## License / reuse
52
+
53
+ Official UAE Legislation texts; authentic Official Gazette prevails; not legal advice.
54
+
55
+ This dataset is **not legal advice**. The official source prevails.
56
+
57
+ ## Source
58
+
59
+ - https://uaelegislation.gov.ae/
60
+
61
+ ## Known gaps
62
+
63
+ Federal Law / Federal Decree-Law / Constitution. Not commercial compilations.
64
+
65
+ Federal Law / Federal Decree-Law / Constitution from official uaelegislation.gov.ae list API and PDF downloads. Cabinet resolutions excluded. 429/403 uses archive_fallbacks of official URLs. Started 2026-09-03T02:41:24Z.
66
+
67
+ started 2026-09-03T02:41:24Z
data/articles.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:edb2e03006dafa2c8acb32a332f9669428ff5fc1652954c534d130865b37d88b
3
+ size 84017
data/laws.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b7aaf5bc972ec75f99379cb5e87eea144b7906286803d24c08f355ef0bd19698
3
+ size 2179256
data/manifest.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "slug": "ipfs_uae_laws",
3
+ "cc": "ae",
4
+ "laws_rows": 237,
5
+ "articles_rows": 182,
6
+ "laws_bytes": 2179256,
7
+ "articles_bytes": 84017,
8
+ "laws_sha256": "b7aaf5bc972ec75f99379cb5e87eea144b7906286803d24c08f355ef0bd19698",
9
+ "articles_sha256": "edb2e03006dafa2c8acb32a332f9669428ff5fc1652954c534d130865b37d88b",
10
+ "compression": "zstd",
11
+ "collector": "collect_ae.py",
12
+ "license": "Official UAE Legislation texts; authentic Official Gazette prevails; not legal advice.",
13
+ "generated_utc": "2026-09-03T02:50:08Z"
14
+ }
scrapers/archive_fallbacks.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Public Wayback CDX + Common Crawl CDX/WARC fetch (ipfs_datasets_py fallback intent).
3
+
4
+ Does not import the full ipfs_datasets_py package. Matches:
5
+ search_wayback_machine / get_wayback_content (wayback_machine_engine.py)
6
+ Common Crawl CDX at https://index.commoncrawl.org/
7
+ archive.is newest lookup
8
+ Brave Search is skipped when no API key is present.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import gzip
13
+ import io
14
+ import json
15
+ import logging
16
+ import os
17
+ import re
18
+ import time
19
+ from typing import Any, Optional
20
+ from urllib.parse import quote, urljoin, urlparse
21
+
22
+ import requests
23
+ from requests.adapters import HTTPAdapter
24
+
25
+ log = logging.getLogger("archive_fallbacks")
26
+
27
+ WAYBACK_CDX = "https://web.archive.org/cdx/search/cdx"
28
+ WAYBACK_WEB = "https://web.archive.org/web"
29
+ CC_COLLINFO = "https://index.commoncrawl.org/collinfo.json"
30
+ CC_DATA = "https://data.commoncrawl.org"
31
+ ARCHIVE_IS_NEWEST = "https://archive.is/newest/"
32
+ ARCHIVE_PH_NEWEST = "https://archive.ph/newest/"
33
+
34
+ UA = (
35
+ "legal-corpora-collector/1.0 "
36
+ "(research archive of official national gazettes; polite; "
37
+ "contact via local operator)"
38
+ )
39
+
40
+ CHALLENGE_RE = re.compile(
41
+ r"just\s+a\s+moment|cf-browser-verification|cloudflare|enable\s+javascript|"
42
+ r"you\s+need\s+to\s+enable\s+javascript|tspd_|bobcmn|attention\s+required|"
43
+ r"checking\s+your\s+browser|please\s+wait\s+while\s+we\s+verify|"
44
+ r"request\s+rejected|access\s+denied",
45
+ re.I,
46
+ )
47
+ SPA_SHELL_RE = re.compile(
48
+ r"<app-root[\s>]|ng-version=|outsystems-ui|data-block=\"MainContent\"|"
49
+ r"id=\"outsystems\"|window\.__INITIAL_STATE__\s*=\s*\{\s*\}",
50
+ re.I,
51
+ )
52
+
53
+ _session: Optional[requests.Session] = None
54
+ _cc_indexes: Optional[list[str]] = None
55
+ _cc_dead: set[str] = set()
56
+ _last_wayback = 0.0
57
+ _last_cc = 0.0
58
+
59
+
60
+ def session() -> requests.Session:
61
+ global _session
62
+ if _session is None:
63
+ s = requests.Session()
64
+ s.headers.update({"User-Agent": UA, "Accept": "*/*"})
65
+ ad = HTTPAdapter(pool_connections=8, pool_maxsize=8, max_retries=0)
66
+ s.mount("https://", ad)
67
+ s.mount("http://", ad)
68
+ _session = s
69
+ return _session
70
+
71
+
72
+ def _sleep_wayback(delay: float = 1.0) -> None:
73
+ global _last_wayback
74
+ now = time.time()
75
+ wait = delay - (now - _last_wayback)
76
+ if wait > 0:
77
+ time.sleep(wait)
78
+ _last_wayback = time.time()
79
+
80
+
81
+ def _sleep_cc(delay: float = 0.35) -> None:
82
+ global _last_cc
83
+ now = time.time()
84
+ wait = delay - (now - _last_cc)
85
+ if wait > 0:
86
+ time.sleep(wait)
87
+ _last_cc = time.time()
88
+
89
+
90
+ def has_brave_key() -> bool:
91
+ return bool(
92
+ (os.environ.get("BRAVE_API_KEY") or os.environ.get("BRAVE_SEARCH_API_KEY") or "").strip()
93
+ )
94
+
95
+
96
+ def is_challenge(html: str, status: int = 200) -> bool:
97
+ if status in (401, 403, 429, 503):
98
+ return True
99
+ if not html:
100
+ return False
101
+ head = html[:8000]
102
+ if CHALLENGE_RE.search(head):
103
+ return True
104
+ if SPA_SHELL_RE.search(head) and len(html) < 8000:
105
+ return True
106
+ return False
107
+
108
+
109
+ def is_spa_shell(html: str, text: str) -> bool:
110
+ if not html:
111
+ return False
112
+ if SPA_SHELL_RE.search(html[:12000]) and len(text or "") < 400:
113
+ return True
114
+ return False
115
+
116
+
117
+ # --- Wayback ---
118
+
119
+ CDX_PAGE = 200 # large single-shot limits (2000+) 504 on web.archive.org
120
+
121
+
122
+ def _parse_cdx_json(data: Any, mime_prefix: Optional[str] = None) -> tuple[list[dict], Optional[str]]:
123
+ """Parse Wayback CDX JSON, including showResumeKey trailer."""
124
+ if not isinstance(data, list) or len(data) <= 1:
125
+ return [], None
126
+ resume = None
127
+ rows = data
128
+ # Trailer: ..., [], ["resumeKey"]
129
+ if len(data) >= 3 and data[-2] == [] and isinstance(data[-1], list) and data[-1]:
130
+ resume = str(data[-1][0]) if data[-1][0] else None
131
+ rows = data[:-2]
132
+ headers = rows[0] if rows else []
133
+ out: list[dict] = []
134
+ for row in rows[1:]:
135
+ if not row:
136
+ continue
137
+ rec = dict(zip(headers, row)) if headers and isinstance(headers[0], str) else {}
138
+ if not rec and isinstance(row, list) and len(row) >= 5:
139
+ rec = {
140
+ "urlkey": row[0],
141
+ "timestamp": row[1],
142
+ "original": row[2],
143
+ "mimetype": row[3],
144
+ "statuscode": row[4],
145
+ "digest": row[5] if len(row) > 5 else "",
146
+ "length": row[6] if len(row) > 6 else "0",
147
+ }
148
+ orig = rec.get("original") or rec.get("url") or ""
149
+ ts = rec.get("timestamp") or ""
150
+ mime = rec.get("mimetype") or ""
151
+ if mime_prefix and mime and not mime.lower().startswith(mime_prefix.lower()) and mime not in (
152
+ "application/pdf",
153
+ "application/xml",
154
+ "text/xml",
155
+ "application/xhtml+xml",
156
+ "text/html",
157
+ "application/json",
158
+ ):
159
+ continue
160
+ if not orig or not ts:
161
+ continue
162
+ rec["wayback_url"] = f"{WAYBACK_WEB}/{ts}id_/{orig}"
163
+ rec["source"] = "wayback"
164
+ out.append(rec)
165
+ return out, resume
166
+
167
+
168
+ def _wayback_cdx_page(
169
+ url: str,
170
+ *,
171
+ limit: int,
172
+ collapse: str,
173
+ filter_status: str,
174
+ from_date: Optional[str],
175
+ to_date: Optional[str],
176
+ match_type: Optional[str],
177
+ extra_filters: Optional[list[str]],
178
+ resume_key: Optional[str],
179
+ mime_prefix: Optional[str],
180
+ page_size: int,
181
+ ) -> tuple[list[dict], Optional[str]]:
182
+ items: list[tuple[str, Any]] = [
183
+ ("url", url),
184
+ ("output", "json"),
185
+ ("fl", "urlkey,timestamp,original,mimetype,statuscode,digest,length"),
186
+ ("limit", int(page_size)),
187
+ ("showResumeKey", "true"),
188
+ ]
189
+ if collapse:
190
+ items.append(("collapse", collapse))
191
+ if from_date:
192
+ items.append(("from", from_date))
193
+ if to_date:
194
+ items.append(("to", to_date))
195
+ if match_type:
196
+ items.append(("matchType", match_type))
197
+ if filter_status:
198
+ items.append(("filter", f"statuscode:{filter_status}"))
199
+ for flt in extra_filters or []:
200
+ items.append(("filter", flt))
201
+ if resume_key:
202
+ items.append(("resumeKey", resume_key))
203
+ _sleep_wayback(1.0)
204
+ last_err = None
205
+ for attempt, psz in enumerate((page_size, 120, 80), 1):
206
+ if attempt > 1:
207
+ items = [(k, psz if k == "limit" else v) for k, v in items]
208
+ _sleep_wayback(1.5)
209
+ try:
210
+ r = session().get(WAYBACK_CDX, params=items, timeout=(20, 90))
211
+ except requests.RequestException as exc:
212
+ last_err = exc
213
+ log.warning("wayback cdx fail %s: %s", url, exc)
214
+ continue
215
+ if r.status_code in (502, 503, 504) or not r.content:
216
+ last_err = f"http_{r.status_code}"
217
+ log.info("wayback cdx HTTP %s for %s (page_size=%s)", r.status_code, url, psz)
218
+ continue
219
+ if r.status_code != 200:
220
+ log.info("wayback cdx HTTP %s for %s", r.status_code, url)
221
+ return [], None
222
+ try:
223
+ data = r.json()
224
+ except Exception:
225
+ return [], None
226
+ return _parse_cdx_json(data, mime_prefix=mime_prefix)
227
+ log.info("wayback cdx gave up %s last=%s", url, last_err)
228
+ return [], None
229
+
230
+
231
+ def search_wayback_machine(
232
+ url: str,
233
+ *,
234
+ from_date: Optional[str] = None,
235
+ to_date: Optional[str] = None,
236
+ limit: int = 100,
237
+ collapse: str = "urlkey",
238
+ filter_status: str = "200",
239
+ match_type: Optional[str] = None,
240
+ mime_prefix: Optional[str] = None,
241
+ extra_filters: Optional[list[str]] = None,
242
+ ) -> list[dict]:
243
+ """CDX search with resumeKey pagination (single-shot limit>=2000 504s)."""
244
+ target = max(1, int(limit))
245
+ page_size = CDX_PAGE if target > CDX_PAGE else target
246
+ out: list[dict] = []
247
+ seen = set()
248
+ resume: Optional[str] = None
249
+ empty = 0
250
+ while len(out) < target:
251
+ need = min(page_size, target - len(out))
252
+ batch, resume = _wayback_cdx_page(
253
+ url,
254
+ limit=need,
255
+ collapse=collapse,
256
+ filter_status=filter_status,
257
+ from_date=from_date,
258
+ to_date=to_date,
259
+ match_type=match_type,
260
+ extra_filters=extra_filters,
261
+ resume_key=resume,
262
+ mime_prefix=mime_prefix,
263
+ page_size=need,
264
+ )
265
+ added = 0
266
+ for rec in batch:
267
+ key = (rec.get("original"), rec.get("timestamp"), rec.get("digest"))
268
+ if key in seen:
269
+ continue
270
+ seen.add(key)
271
+ out.append(rec)
272
+ added += 1
273
+ if added == 0:
274
+ empty += 1
275
+ if empty >= 2 or not resume:
276
+ break
277
+ else:
278
+ empty = 0
279
+ if not resume:
280
+ break
281
+ log.info("wayback cdx %s page n=%s total=%s/%s", url, added, len(out), target)
282
+ return out[:target]
283
+
284
+
285
+ def get_wayback_content(url: str, timestamp: Optional[str] = None) -> dict:
286
+ """Fetch a snapshot; id_ modifier skips Wayback chrome. No CDX search."""
287
+ if timestamp:
288
+ wb = f"{WAYBACK_WEB}/{timestamp}id_/{url}"
289
+ else:
290
+ wb = f"{WAYBACK_WEB}/2id_/{url}"
291
+ r = None
292
+ last_err = None
293
+ for attempt in range(1, 5):
294
+ _sleep_wayback(1.2 if attempt == 1 else min(20.0, 2.5 * attempt))
295
+ try:
296
+ r = session().get(wb, timeout=(20, 90), allow_redirects=True)
297
+ except requests.RequestException as exc:
298
+ last_err = str(exc)
299
+ log.info("wayback replay fail %s: %s", url, exc)
300
+ continue
301
+ if r.status_code in (403, 429, 503, 502, 504) and attempt < 4:
302
+ log.info("wayback replay HTTP %s %s attempt=%s", r.status_code, url, attempt)
303
+ continue
304
+ break
305
+ if r is None:
306
+ return {"status": "error", "error": last_err or "no_response", "url": url}
307
+ cap_ts = timestamp or ""
308
+ m = re.search(r"/web/(\d{14})", r.url or "")
309
+ if m:
310
+ cap_ts = m.group(1)
311
+ ctype = r.headers.get("content-type") or ""
312
+ body = r.content or b""
313
+ text = ""
314
+ if "html" in ctype or "xml" in ctype or "text/" in ctype or not ctype:
315
+ enc = r.encoding or "utf-8"
316
+ try:
317
+ text = body.decode(enc, "replace")
318
+ except Exception:
319
+ text = body.decode("utf-8", "replace")
320
+ if r.status_code != 200 or not body:
321
+ return {
322
+ "status": "error",
323
+ "error": f"http_{r.status_code}",
324
+ "http_status": r.status_code,
325
+ "wayback_url": r.url,
326
+ "original_url": url,
327
+ }
328
+ if text and is_challenge(text, r.status_code):
329
+ return {
330
+ "status": "error",
331
+ "error": "challenge_or_shell",
332
+ "http_status": r.status_code,
333
+ "wayback_url": r.url,
334
+ "original_url": url,
335
+ "content": text[:2000],
336
+ }
337
+ return {
338
+ "status": "success",
339
+ "content": body,
340
+ "text": text,
341
+ "content_type": ctype,
342
+ "wayback_url": r.url,
343
+ "capture_timestamp": cap_ts,
344
+ "original_url": url,
345
+ "http_status": r.status_code,
346
+ "method": "wayback",
347
+ }
348
+
349
+
350
+ # --- Common Crawl ---
351
+
352
+ def cc_indexes(n: int = 6) -> list[str]:
353
+ global _cc_indexes
354
+ if _cc_indexes is None:
355
+ try:
356
+ r = session().get(CC_COLLINFO, timeout=30)
357
+ cols = r.json() if r.status_code == 200 else []
358
+ ids = []
359
+ for c in cols:
360
+ cid = c.get("id") or ""
361
+ cdx = c.get("cdx-api") or c.get("cdx_api") or ""
362
+ if cid:
363
+ ids.append(cdx or f"https://index.commoncrawl.org/{cid}-index")
364
+ # collinfo is newest-first. Do not drop crawls that 404 a
365
+ # specific URL (that means "no captures", not a dead index).
366
+ _cc_indexes = ids or [
367
+ "https://index.commoncrawl.org/CC-MAIN-2025-18-index",
368
+ "https://index.commoncrawl.org/CC-MAIN-2024-33-index",
369
+ ]
370
+ except Exception as exc:
371
+ log.warning("cc collinfo: %s", exc)
372
+ _cc_indexes = [
373
+ "https://index.commoncrawl.org/CC-MAIN-2026-34-index",
374
+ "https://index.commoncrawl.org/CC-MAIN-2026-30-index",
375
+ "https://index.commoncrawl.org/CC-MAIN-2026-25-index",
376
+ "https://index.commoncrawl.org/CC-MAIN-2024-33-index",
377
+ ]
378
+ return _cc_indexes[:n]
379
+
380
+
381
+ def search_common_crawl(url: str, *, limit: int = 80, indexes: Optional[list[str]] = None) -> list[dict]:
382
+ """Query public CC CDX (https://index.commoncrawl.org/).
383
+
384
+ Do not send filter=status:200 — on some shards that returns a false
385
+ 404 "No Captures found". Filter status client-side instead.
386
+ HTTP 404 with that message means no hits in this crawl, not a dead index.
387
+ """
388
+ out = []
389
+ seen = set()
390
+ empty = 0
391
+ for idx in (indexes or cc_indexes(12)):
392
+ if idx in _cc_dead:
393
+ continue
394
+ params = {
395
+ "url": url,
396
+ "output": "json",
397
+ "limit": str(limit),
398
+ }
399
+ _sleep_cc(0.3)
400
+ try:
401
+ r = session().get(idx, params=params, timeout=(12, 25))
402
+ except requests.RequestException as exc:
403
+ log.info("cc cdx %s fail %s", idx, exc)
404
+ continue
405
+ if r.status_code == 404:
406
+ msg = (r.text or "")[:80]
407
+ log.info("cc cdx no-captures %s %s", idx.split("/")[-1], msg)
408
+ empty += 1
409
+ if empty >= 8 and not out:
410
+ continue
411
+ continue
412
+ if r.status_code in (410,):
413
+ _cc_dead.add(idx)
414
+ log.info("cc cdx dead HTTP %s %s", r.status_code, idx.split("/")[-1])
415
+ continue
416
+ if r.status_code != 200 or not r.content:
417
+ log.info("cc cdx HTTP %s %s", r.status_code, idx.split("/")[-1])
418
+ continue
419
+ for line in r.text.splitlines():
420
+ line = line.strip()
421
+ if not line or line[0] not in "{[":
422
+ continue
423
+ try:
424
+ rec = json.loads(line)
425
+ except Exception:
426
+ continue
427
+ orig = rec.get("url") or rec.get("original") or ""
428
+ st = str(rec.get("status") or rec.get("statuscode") or "200")
429
+ if st and st not in ("200", "201", "206"):
430
+ continue
431
+ key = (orig, rec.get("filename"), rec.get("offset"))
432
+ if not orig or key in seen:
433
+ continue
434
+ seen.add(key)
435
+ rec["original"] = orig
436
+ rec["source"] = "common_crawl"
437
+ rec["cc_index"] = idx
438
+ out.append(rec)
439
+ if out:
440
+ log.info("cc cdx %s hits=%s", idx.split("/")[-1], len(out))
441
+ if len(out) >= limit or out:
442
+ break
443
+ return out[:limit]
444
+
445
+
446
+ def _parse_warc_http(raw: bytes) -> tuple[int, str, bytes]:
447
+ data = raw
448
+ if data[:2] == b"\x1f\x8b":
449
+ try:
450
+ data = gzip.decompress(data)
451
+ except Exception:
452
+ try:
453
+ data = gzip.GzipFile(fileobj=io.BytesIO(data)).read()
454
+ except Exception:
455
+ pass
456
+ # WARC record: headers, then HTTP payload
457
+ split = data.split(b"\r\n\r\n", 1)
458
+ if len(split) < 2:
459
+ return 0, "", data
460
+ warc_headers, rest = split
461
+ if rest.startswith(b"HTTP/") or rest.startswith(b"http/"):
462
+ http_split = rest.split(b"\r\n\r\n", 1)
463
+ http_head = http_split[0].decode("latin-1", "replace")
464
+ body = http_split[1] if len(http_split) > 1 else b""
465
+ m = re.search(r"HTTP/\d\.\d\s+(\d{3})", http_head)
466
+ status = int(m.group(1)) if m else 0
467
+ cm = re.search(r"Content-Type:\s*([^\r\n]+)", http_head, re.I)
468
+ ctype = cm.group(1).strip() if cm else ""
469
+ return status, ctype, body
470
+ return 0, "", rest
471
+
472
+
473
+ def fetch_common_crawl_warc(rec: dict, max_bytes: int = 4_000_000) -> dict:
474
+ fn = rec.get("filename") or rec.get("warc_filename") or ""
475
+ try:
476
+ off = int(rec.get("offset") or rec.get("warc_offset") or 0)
477
+ ln = int(rec.get("length") or rec.get("warc_length") or 0)
478
+ except Exception:
479
+ return {"status": "error", "error": "bad_pointer"}
480
+ if not fn or ln <= 0:
481
+ return {"status": "error", "error": "missing_pointer"}
482
+ ln = min(ln, max_bytes)
483
+ url = fn if str(fn).startswith("http") else f"{CC_DATA}/{fn.lstrip('/')}"
484
+ _sleep_cc(0.25)
485
+ try:
486
+ r = session().get(
487
+ url,
488
+ headers={"Range": f"bytes={off}-{off + ln - 1}"},
489
+ timeout=(20, 90),
490
+ )
491
+ except requests.RequestException as exc:
492
+ return {"status": "error", "error": str(exc)}
493
+ if r.status_code not in (200, 206) or not r.content:
494
+ return {"status": "error", "error": f"http_{r.status_code}"}
495
+ status, ctype, body = _parse_warc_http(r.content)
496
+ text = ""
497
+ if body and (
498
+ "html" in (ctype or "")
499
+ or "xml" in (ctype or "")
500
+ or "text/" in (ctype or "")
501
+ or not ctype
502
+ ):
503
+ text = body.decode("utf-8", "replace")
504
+ orig = rec.get("original") or rec.get("url") or ""
505
+ if text and is_challenge(text, status or 200):
506
+ return {"status": "error", "error": "challenge_or_shell", "original_url": orig}
507
+ return {
508
+ "status": "success",
509
+ "content": body,
510
+ "text": text,
511
+ "content_type": ctype,
512
+ "original_url": orig,
513
+ "http_status": status or 200,
514
+ "method": "common_crawl",
515
+ "cc_record": {
516
+ "filename": fn,
517
+ "offset": off,
518
+ "length": ln,
519
+ "timestamp": rec.get("timestamp"),
520
+ },
521
+ }
522
+
523
+
524
+ # --- archive.is ---
525
+
526
+ def get_archive_is_content(url: str) -> dict:
527
+ for base in (ARCHIVE_IS_NEWEST, ARCHIVE_PH_NEWEST):
528
+ try:
529
+ r = session().get(base + url, timeout=(8, 15), allow_redirects=True)
530
+ except requests.RequestException as exc:
531
+ log.info("archive.is %s", exc)
532
+ continue
533
+ if r.status_code != 200 or not r.content:
534
+ continue
535
+ if "archive." not in (r.url or ""):
536
+ continue
537
+ text = r.text or ""
538
+ if is_challenge(text, r.status_code):
539
+ continue
540
+ return {
541
+ "status": "success",
542
+ "content": r.content,
543
+ "text": text,
544
+ "content_type": r.headers.get("content-type") or "text/html",
545
+ "archive_url": r.url,
546
+ "original_url": url,
547
+ "http_status": r.status_code,
548
+ "method": "archive_is",
549
+ }
550
+ return {"status": "error", "error": "no_archive_is_snapshot", "original_url": url}
551
+
552
+
553
+ # --- Direct HTTP last ---
554
+
555
+ def get_http(url: str) -> dict:
556
+ try:
557
+ r = session().get(url, timeout=(20, 60), allow_redirects=True)
558
+ except requests.RequestException as exc:
559
+ return {"status": "error", "error": str(exc), "original_url": url}
560
+ text = ""
561
+ ctype = r.headers.get("content-type") or ""
562
+ body = r.content or b""
563
+ if body and ("html" in ctype or "xml" in ctype or "text/" in ctype or not ctype):
564
+ text = body.decode(r.encoding or "utf-8", "replace")
565
+ if r.status_code != 200 or not body:
566
+ return {"status": "error", "error": f"http_{r.status_code}", "http_status": r.status_code}
567
+ if text and is_challenge(text, r.status_code):
568
+ return {"status": "error", "error": "challenge_or_shell", "http_status": r.status_code}
569
+ return {
570
+ "status": "success",
571
+ "content": body,
572
+ "text": text,
573
+ "content_type": ctype,
574
+ "original_url": url,
575
+ "http_status": r.status_code,
576
+ "method": "http",
577
+ "final_url": r.url,
578
+ }
579
+
580
+
581
+ def fetch_with_fallbacks(
582
+ url: str,
583
+ *,
584
+ cc_record: Optional[dict] = None,
585
+ wayback_ts: Optional[str] = None,
586
+ try_archive_is: bool = False,
587
+ try_http: bool = True,
588
+ try_cc: bool = True,
589
+ ) -> dict:
590
+ """Prefer archives: CC WARC -> Wayback replay -> archive.is -> direct HTTP.
591
+
592
+ Brave Search skipped (no API key in this environment).
593
+ Playwright is attempted by the caller when this returns a SPA shell.
594
+ Does not run Wayback CDX search; Wayback is replay only.
595
+ """
596
+ errors = []
597
+ cc_recs: list[dict] = []
598
+ if cc_record and (cc_record.get("filename") or cc_record.get("warc_filename")):
599
+ cc_recs = [cc_record]
600
+ elif try_cc:
601
+ try:
602
+ cc_recs = search_common_crawl(url, limit=4)
603
+ except Exception as exc:
604
+ errors.append(f"common_crawl:{exc}")
605
+ cc_recs = []
606
+ for rec in cc_recs:
607
+ res = fetch_common_crawl_warc(rec)
608
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
609
+ return res
610
+ errors.append(f"common_crawl:{res.get('error')}")
611
+ if wayback_ts or url:
612
+ res = get_wayback_content(url, timestamp=wayback_ts)
613
+ if res.get("status") == "success" and (res.get("text") or res.get("content")):
614
+ return res
615
+ errors.append(f"wayback:{res.get('error')}")
616
+ if try_archive_is:
617
+ res = get_archive_is_content(url)
618
+ if res.get("status") == "success":
619
+ return res
620
+ errors.append(f"archive_is:{res.get('error')}")
621
+ if try_http:
622
+ res = get_http(url)
623
+ if res.get("status") == "success":
624
+ return res
625
+ errors.append(f"http:{res.get('error')}")
626
+ return {"status": "error", "error": "; ".join(errors) or "all_failed", "original_url": url}
scrapers/collect_ae.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """UAE: Federal laws + Constitution from UAE Legislation.
3
+
4
+ Official sources only:
5
+ https://uaelegislation.gov.ae (General Secretariat of the UAE Cabinet)
6
+ List API: POST /en/legislations/list
7
+ Item: /en/legislations/{id}
8
+ PDF: /en/legislations/{id}/download
9
+ Constitution id=1000
10
+
11
+ Federal laws (Federal Law / Federal Decree-Law) first. Cabinet resolutions
12
+ and ministerial circulars are out of scope. No commercial compilations.
13
+ No WAF bypass.
14
+
15
+ On HTTP 429/403 of official URLs, archive_fallbacks.py of those URLs only.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import logging
21
+ import re
22
+ import time
23
+ import subprocess
24
+ import sys
25
+ import tempfile
26
+ from concurrent.futures import ThreadPoolExecutor, as_completed
27
+ from pathlib import Path
28
+ from typing import Optional
29
+
30
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
31
+ from common import *
32
+ import archive_fallbacks as af
33
+
34
+ CC = "ae"
35
+ COUNTRY = "United Arab Emirates"
36
+ SOURCE_TYPE = "uaelegislation"
37
+ LICENSE = (
38
+ "Official UAE Legislation texts (uaelegislation.gov.ae / UAE Cabinet). "
39
+ "Authentic Official Gazette prevails. Not legal advice."
40
+ )
41
+ UA = DEFAULT_UA + " source=https://uaelegislation.gov.ae/"
42
+ PORTAL = "https://uaelegislation.gov.ae/"
43
+ LIST = "https://uaelegislation.gov.ae/en/legislations/list"
44
+ BROWSE = "https://uaelegislation.gov.ae/en/legislations"
45
+ CONST_ID = "1000"
46
+ WORKERS = 3
47
+ SLEEP = 0.5
48
+ log = logging.getLogger("ae")
49
+
50
+ FED_RE = re.compile(
51
+ r"Federal(?:\s+Decree[-\s]?Law|\s+Law)\b|^Constitution\b|The Constitution of the United Arab Emirates",
52
+ re.I,
53
+ )
54
+ SKIP_RE = re.compile(r"Cabinet Resolution|Ministerial|Circular|Administrative Decision", re.I)
55
+ ART_AE = re.compile(r"(?im)^\s*((?:Article|المادة)\s+[0-9\u0660-\u0669]+)\b")
56
+ ID_RE = re.compile(r"/en/legislations/(\d+)(?:/|$|\?)")
57
+
58
+
59
+ def setup():
60
+ ensure_dirs(CC)
61
+ logging.basicConfig(
62
+ level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
63
+ handlers=[
64
+ logging.FileHandler(ROOT / CC / "logs" / "collector.log", encoding="utf-8"),
65
+ logging.StreamHandler(sys.stdout),
66
+ ],
67
+ )
68
+
69
+
70
+ def pdf_to_text(raw: bytes) -> str:
71
+ if not raw or raw[:4] != b"%PDF":
72
+ return ""
73
+ try:
74
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
75
+ tmp.write(raw)
76
+ tmp.flush()
77
+ proc = subprocess.run(
78
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
79
+ check=False, capture_output=True, timeout=180,
80
+ )
81
+ if proc.returncode == 0 and proc.stdout:
82
+ return proc.stdout.decode("utf-8", "replace").strip()
83
+ except Exception as exc:
84
+ log.warning("pdftotext: %s", exc)
85
+ return ""
86
+
87
+
88
+ def official_get(url: str, *, binary: bool = False, retries: int = 4) -> dict:
89
+ headers = {"Accept": "application/pdf, */*" if binary else "text/html, application/json, */*"}
90
+ try:
91
+ r = http_get(url, ua=UA, sleep=SLEEP, retries=retries, timeout=(20, 90), headers=headers)
92
+ except Exception as exc:
93
+ log.info("live fail %s: %s", url, exc)
94
+ r = None
95
+ if r is not None and r.status_code == 200 and r.content:
96
+ if binary or not af.is_challenge(r.text or "", r.status_code):
97
+ return {"ok": True, "content": r.content, "text": "" if binary else (r.text or ""),
98
+ "method": "live", "status": 200}
99
+ if r is not None and r.status_code in (404, 410):
100
+ return {"ok": False, "error": f"http_{r.status_code}", "status": r.status_code}
101
+ need = r is None or r.status_code in (429, 403, 503, 502, 504)
102
+ if r is not None and not binary and af.is_challenge(r.text or "", r.status_code):
103
+ need = True
104
+ if need:
105
+ res = af.fetch_with_fallbacks(url, try_http=False, try_cc=True, try_archive_is=False)
106
+ if res.get("status") == "success" and (res.get("content") or res.get("text")):
107
+ return {"ok": True, "content": res.get("content") or b"", "text": res.get("text") or "",
108
+ "method": res.get("method") or "archive", "archive": res}
109
+ return {"ok": False, "error": (res or {}).get("error") or "archive_fail"}
110
+ return {"ok": False, "error": f"http_{getattr(r, 'status_code', 0)}"}
111
+
112
+
113
+ def session_token() -> tuple[object, str]:
114
+ sess = get_session(UA, pool=WORKERS)
115
+ r = sess.get(BROWSE, timeout=(20, 60), headers={"User-Agent": UA, "Accept": "text/html"})
116
+ m = re.search(r'_token:\s*"([^"]+)"', r.text or "")
117
+ token = m.group(1) if m else ""
118
+ # also csrf cookie
119
+ if not token:
120
+ m = re.search(r'name="csrf-token"\s+content="([^"]+)"', r.text or "")
121
+ token = m.group(1) if m else ""
122
+ return sess, token
123
+
124
+
125
+ def list_page(sess, token: str, page: int, law_types: list) -> dict:
126
+ payload = {
127
+ "_token": token,
128
+ "page": page,
129
+ "paginateBy": 50,
130
+ "year": None,
131
+ "lawTypes": law_types,
132
+ "subject": "",
133
+ }
134
+ headers = {
135
+ "User-Agent": UA,
136
+ "Accept": "application/json, text/javascript, */*; q=0.01",
137
+ "Content-Type": "application/json",
138
+ "X-Requested-With": "XMLHttpRequest",
139
+ "Referer": BROWSE,
140
+ }
141
+ time.sleep(SLEEP)
142
+ r = sess.post(LIST, json=payload, headers=headers, timeout=(20, 90))
143
+ if r.status_code in (429, 403, 503):
144
+ log.info("list HTTP %s page=%s — archive not used for POST body", r.status_code, page)
145
+ return {}
146
+ if r.status_code != 200:
147
+ log.info("list HTTP %s page=%s", r.status_code, page)
148
+ return {}
149
+ try:
150
+ return r.json()
151
+ except Exception:
152
+ return {}
153
+
154
+
155
+ def parse_list_payload(js: dict) -> list[dict]:
156
+ items = []
157
+ blob = json.dumps(js, ensure_ascii=False)
158
+ html = js.get("html") or js.get("view") or js.get("content") or ""
159
+ # data array
160
+ data = js.get("data") or js.get("legislations") or js.get("items") or []
161
+ if isinstance(data, dict):
162
+ data = data.get("data") or data.get("items") or []
163
+ if isinstance(data, list):
164
+ for rec in data:
165
+ if not isinstance(rec, dict):
166
+ continue
167
+ lid = rec.get("id") or rec.get("legislation_id") or rec.get("legislationId")
168
+ title = rec.get("title") or rec.get("name") or rec.get("title_en") or ""
169
+ if lid:
170
+ items.append({
171
+ "id": str(lid),
172
+ "title": re.sub(r"\s+", " ", str(title)).strip(),
173
+ "year": rec.get("year") or rec.get("issue_year"),
174
+ "law_type": rec.get("law_type") or rec.get("type"),
175
+ "source": "list_json",
176
+ })
177
+ for lid in ID_RE.findall(html + "\n" + blob):
178
+ items.append({"id": lid, "title": "", "source": "list_html"})
179
+ # titles next to ids in HTML
180
+ for lid, title in re.findall(
181
+ r'href="[^"]*/en/legislations/(\d+)[^"]*"[^>]*>\s*([^<]{3,220})\s*<', html
182
+ ):
183
+ items.append({"id": lid, "title": re.sub(r"\s+", " ", title).strip(), "source": "list_anchor"})
184
+ return items
185
+
186
+
187
+ def load_catalog() -> list[dict]:
188
+ p = ROOT / CC / "raw" / "catalog.jsonl"
189
+ if not p.exists() or p.stat().st_size < 50:
190
+ return []
191
+ items, seen = [], set()
192
+ with p.open(encoding="utf-8") as f:
193
+ for line in f:
194
+ line = line.strip()
195
+ if not line:
196
+ continue
197
+ try:
198
+ row = json.loads(line)
199
+ except Exception:
200
+ continue
201
+ lid = str(row.get("id") or "")
202
+ if not lid or lid in seen:
203
+ continue
204
+ seen.add(lid)
205
+ items.append(row)
206
+ return items
207
+
208
+
209
+ def add_item(items, seen, row):
210
+ lid = str(row.get("id") or "")
211
+ if not lid or lid in seen:
212
+ if lid in seen and row.get("title"):
213
+ for it in items:
214
+ if str(it.get("id")) == lid and not it.get("title"):
215
+ it["title"] = row["title"]
216
+ return
217
+ seen.add(lid)
218
+ row["url"] = f"https://uaelegislation.gov.ae/en/legislations/{lid}"
219
+ row["pdf_url"] = f"https://uaelegislation.gov.ae/en/legislations/{lid}/download"
220
+ items.append(row)
221
+ append_catalog(CC, row)
222
+
223
+
224
+ def is_federal(title: str, lid: str) -> bool:
225
+ if lid == CONST_ID:
226
+ return True
227
+ t = title or ""
228
+ if SKIP_RE.search(t):
229
+ return False
230
+ if not t:
231
+ return True
232
+ if FED_RE.search(t) or "قانون اتحادي" in t or "مرسوم بقانون" in t:
233
+ return True
234
+ # type-2/3/14 catalog ids are federal even when title is Arabic-only
235
+ return True
236
+
237
+
238
+ def discover() -> list[dict]:
239
+ items = load_catalog()
240
+ seen = {str(x.get("id")) for x in items}
241
+ add_item(items, seen, {
242
+ "id": CONST_ID,
243
+ "title": "The Constitution of the United Arab Emirates",
244
+ "kind": "constitution",
245
+ "source": "known",
246
+ })
247
+ if len(items) >= 80:
248
+ log.info("resume catalog %s", len(items))
249
+ return items
250
+ sess, token = session_token()
251
+ if not token:
252
+ log.warning("no csrf token; list API may fail")
253
+ # 14 Constitution, 2 Federal Law, 3 Federal Decree-Law. Type 1 is Cabinet Resolutions.
254
+ for types in ([14], [2], [3]):
255
+ js0 = list_page(sess, token, 1, types)
256
+ total = int(js0.get("total") or 0)
257
+ pages = int(js0.get("pages") or 1)
258
+ log.info("list types=%s total=%s pages=%s", types, total, pages)
259
+ for rec in parse_list_payload(js0):
260
+ add_item(items, seen, rec)
261
+ for p in range(2, min(pages, 40) + 1):
262
+ js = list_page(sess, token, p, types)
263
+ if not js:
264
+ break
265
+ before = len(items)
266
+ for rec in parse_list_payload(js):
267
+ add_item(items, seen, rec)
268
+ log.info("page %s types=%s new_total=%s", p, types, len(items))
269
+ if len(items) == before and p > 2:
270
+ break
271
+ # collect all three federal families
272
+ log.info("discovered %s", len(items))
273
+ return items
274
+
275
+
276
+ def page_title(html: str, fallback: str) -> str:
277
+ m = re.search(r"<title>\s*([^<]+)", html or "", re.I)
278
+ if m:
279
+ t = re.sub(r"\s+", " ", m.group(1)).strip()
280
+ t = re.sub(r"^United Arab Emirates Legislations\s*[|:—-]+\s*", "", t, flags=re.I)
281
+ if t:
282
+ return t
283
+ m = re.search(r"<h1[^>]*>([\s\S]{3,240})</h1>", html or "", re.I)
284
+ if m:
285
+ t = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", m.group(1))).strip()
286
+ if t:
287
+ return t
288
+ return fallback
289
+
290
+
291
+ def fetch_one(it: dict, done: set[str]) -> str:
292
+ lid = str(it.get("id") or "")
293
+ if not lid:
294
+ return "fail"
295
+ rid = slug_id(CC, f"leg-{lid}")
296
+ if rid in done:
297
+ return "skip"
298
+ url = it.get("url") or f"https://uaelegislation.gov.ae/en/legislations/{lid}"
299
+ pdf_url = it.get("pdf_url") or f"{url}/download"
300
+ page = official_get(url)
301
+ html = page.get("text") or ""
302
+ title = page_title(html, it.get("title") or f"Legislation {lid}")
303
+ if not is_federal(title, lid):
304
+ return "skip"
305
+ text = ""
306
+ backend = page.get("method") or "live"
307
+ pdf = official_get(pdf_url, binary=True)
308
+ if pdf.get("ok"):
309
+ text = pdf_to_text(pdf.get("content") or b"")
310
+ backend = f"pdf-{(pdf.get('method') or 'live')}"
311
+ if len(text) < 80 and html:
312
+ body = html_to_text(html)
313
+ m = re.search(r"(Article\s+1\b|المادة|We, |WE, |The President)", body)
314
+ if m:
315
+ body = body[m.start():]
316
+ if len(body) > len(text):
317
+ text = body
318
+ backend = f"html-{(page.get('method') or 'live')}"
319
+ if len(text) < 80:
320
+ log_failure(CC, {"identifier": lid, "source_url": url, "status": "failed",
321
+ "reason": "empty_text", "title": title})
322
+ return "fail"
323
+ docs = split_articles(text, rid, url, None)
324
+ if not docs:
325
+ matches = list(ART_AE.finditer(text))
326
+ if len(matches) >= 2:
327
+ docs = []
328
+ for i, m in enumerate(matches):
329
+ start = m.start()
330
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
331
+ chunk = text[start:end].strip()
332
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
333
+ aid = re.sub(r"[^a-z0-9]+", "-", num.lower()).strip("-")
334
+ docs.append({
335
+ "id": f"{rid}-{aid}"[:180], "title": chunk.split("\n", 1)[0][:200],
336
+ "text": chunk, "document_number": num, "source_url": url,
337
+ "record_type": "article", "article_number": num, "law_identifier": rid,
338
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
339
+ })
340
+ kind = "constitution" if lid == CONST_ID or re.search(r"Constitution of the United Arab Emirates", title, re.I) else "statute"
341
+ rec = base_record(
342
+ cc=CC, country=COUNTRY, language="en", ident=f"leg-{lid}", title=title,
343
+ text=text, source_url=url, source_type=SOURCE_TYPE, license_text=LICENSE,
344
+ collector="ae-uaelegislation", date=iso_date(str(it.get("year"))) if it.get("year") else None,
345
+ official_identifier=lid, document_type=kind,
346
+ law_status="current", is_current=True, documents=docs,
347
+ extra_meta={
348
+ "discovery": {"method": "uaelegislation_list", "id": lid, "pdf_url": pdf_url,
349
+ "retrieval": page.get("method")},
350
+ "text_extraction": {"source": "official", "backend": backend},
351
+ },
352
+ )
353
+ rec["languages"] = ["en"]
354
+ write_instrument(CC, rec)
355
+ return "ok"
356
+
357
+
358
+ def main():
359
+ setup()
360
+ t0 = utcnow()
361
+ items = discover()
362
+ items = sorted(items, key=lambda x: (0 if str(x.get("id")) == CONST_ID else 1, int(x.get("id") or 0)))
363
+ done = existing_ids(CC)
364
+ ok = skip = fail = 0
365
+ log.info("queue %s already=%s", len(items), len(done))
366
+ with ThreadPoolExecutor(max_workers=WORKERS) as ex:
367
+ futs = [ex.submit(fetch_one, it, done) for it in items]
368
+ n = 0
369
+ for fut in as_completed(futs):
370
+ n += 1
371
+ try:
372
+ st = fut.result()
373
+ except Exception as exc:
374
+ st = "fail"
375
+ log_failure(CC, {"status": "failed", "reason": repr(exc)})
376
+ ok += st == "ok"
377
+ skip += st == "skip"
378
+ fail += st == "fail"
379
+ if n % 20 == 0 or n == len(items):
380
+ log.info("progress %s/%s ok=%s skip=%s fail=%s", n, len(items), ok, skip, fail)
381
+ write_summary(
382
+ CC, country=COUNTRY,
383
+ source="UAE Legislation (General Secretariat of the UAE Cabinet)",
384
+ source_urls=[PORTAL, BROWSE], license_text=LICENSE,
385
+ discovered=len(items), fetched=ok, skipped=skip, failed=fail,
386
+ coverage="catalog-backed incomplete",
387
+ notes="Federal laws + Constitution. Not commercial compilations.",
388
+ last_run=utcnow(),
389
+ )
390
+ coverage = "snapshot" if ok else "empty"
391
+ if items and fail == 0 and ok + skip >= len(items):
392
+ coverage = "federal-laws snapshot"
393
+ notes = (
394
+ "Federal Law / Federal Decree-Law / Constitution from official "
395
+ "uaelegislation.gov.ae list API and PDF downloads. Cabinet resolutions "
396
+ "excluded. 429/403 uses archive_fallbacks of official URLs. Started "
397
+ f"{t0}."
398
+ )
399
+ write_summary(
400
+ CC, country=COUNTRY,
401
+ source="UAE Legislation (General Secretariat of the UAE Cabinet)",
402
+ source_urls=[PORTAL, BROWSE, f"https://uaelegislation.gov.ae/en/legislations/{CONST_ID}"],
403
+ license_text=LICENSE, discovered=len(items), fetched=ok, skipped=skip, failed=fail,
404
+ coverage=coverage, notes=notes, last_run=utcnow(), extra=f"started {t0}",
405
+ )
406
+ (ROOT / CC / "logs" / "DONE").write_text(json.dumps({
407
+ "ok": ok, "skip": skip, "fail": fail, "discovered": len(items), "coverage": coverage,
408
+ }, indent=2) + "\n", encoding="utf-8")
409
+ log.info("done ok=%s skip=%s fail=%s coverage=%s", ok, skip, fail, coverage)
410
+
411
+
412
+ if __name__ == "__main__":
413
+ 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