endomorphosis commited on
Commit
ad5393e
·
verified ·
1 Parent(s): b06a903

Deepen cy: 261 laws / 3619 arts (honest counts)

Browse files
MANIFEST.md CHANGED
@@ -1,9 +1,5 @@
1
  # MANIFEST
2
 
3
- - generated_at: 2026-09-04T17:50:59Z
4
- - laws: 198
5
- - articles: 2690
6
- - files:
7
- - data/laws.parquet: 9537903 bytes
8
- - data/articles.parquet: 6783079 bytes
9
- - README.md: 1670 bytes
 
1
  # MANIFEST
2
 
3
+ - generated_at: 2026-09-04T19:25:23Z
4
+ - laws: 261
5
+ - articles: 3619
 
 
 
 
README.md CHANGED
@@ -35,30 +35,18 @@ Research snapshot of official legislation collected from **GPO mof.gov.cy**.
35
  | Coverage | catalog-backed incomplete |
36
  | Source | GPO mof.gov.cy |
37
  | Collector | `scrapers/collect_cy.py` |
38
- | Laws / instruments | 198 |
39
- | Articles | 2690 |
40
  | Language | el |
41
  | Jurisdiction | Cyprus |
42
  | License | `cyprus-gpo-gazette` |
43
 
44
  ## Contents
45
 
46
- - `data/laws.parquet` — one row per instrument (id, title, full text, ELI,
47
- dates, status, identifiers, article count, source URL).
48
- - `data/articles.parquet` — one row per article/section (`law_id`, article
49
- number, title, text, source URL).
50
- - `scrapers/collect_cy.py` — research collector used to build this snapshot.
51
- - `scrapers/common.py` — shared collector helpers.
52
-
53
- ## License / reuse
54
-
55
- Official government / gazette texts; reuse per public-sector terms of the
56
- source portal. This packaging, metadata, and collector script are provided
57
- for research.
58
-
59
- This dataset is **not** an official consolidation and is **not legal advice**.
60
- The official source prevails.
61
 
62
  ## Notes
63
 
64
- Round 4: +71 GPO PDFs (Wayback-prefer + skip known fails); honest article split → 2690 arts across 87/198 laws. Not legal advice.
 
35
  | Coverage | catalog-backed incomplete |
36
  | Source | GPO mof.gov.cy |
37
  | Collector | `scrapers/collect_cy.py` |
38
+ | Laws / instruments | 261 |
39
+ | Articles | 3619 |
40
  | Language | el |
41
  | Jurisdiction | Cyprus |
42
  | License | `cyprus-gpo-gazette` |
43
 
44
  ## Contents
45
 
46
+ - `data/laws.parquet` — one row per instrument
47
+ - `data/articles.parquet` — one row per article/section
48
+ - `scrapers/collect_cy.py` — research collector
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  ## Notes
51
 
52
+ Deepen: official GPO gazette PDFs (no cylaw.org). Honest Άρθρο/Αριθμός/ΜΕΡΟΣ heading splits (>=2). README matches parquet. Not legal advice.
data/articles.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:d20e7f4cf526643ee657d822713ae2f1243203dd75454f150d7fd8f9166bd92e
3
- size 6783079
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8c386514b14360d36674fe1e1a52b1f043a30ddafaa1f3444cad5f1415b2eaa8
3
+ size 8349005
data/laws.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:180661ed8a35bfc2bbeb6d9ef7d048d8b0e65753267b32b50ad2a1baadb966fe
3
- size 9537903
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1dbcfbebc5796a555aadd04cc8c7e79d44ddb3b776a27eabb34c82a5c65eb802
3
+ size 11900105
scrapers/collect_cy.py CHANGED
@@ -50,7 +50,7 @@ def try_get(url, verify_first=True):
50
  for verify in order:
51
  try:
52
  time.sleep(0.35)
53
- r = get_session(UA).get(url, timeout=(10, 45), verify=verify,
54
  headers={"User-Agent": UA, "Accept": "text/html, application/pdf, */*"})
55
  return r, verify
56
  except Exception as exc:
@@ -143,12 +143,14 @@ def fetch_pdf(url: str, ts: str = "", *, prefer_wayback: bool = False) -> tuple[
143
  log.info("wayback pdf %s: %s", url[-50:], exc)
144
  return None
145
 
146
- order = (_wb, _live) if (prefer_wayback and ts) else (_live, _wb)
147
- for fn in order:
148
- if fn is _wb:
149
- got = _wb(ts)
150
- else:
151
- got = _live()
 
 
152
  if got:
153
  return got
154
  return "", url, "none"
 
50
  for verify in order:
51
  try:
52
  time.sleep(0.35)
53
+ r = get_session(UA).get(url, timeout=(5, 15), verify=verify,
54
  headers={"User-Agent": UA, "Accept": "text/html, application/pdf, */*"})
55
  return r, verify
56
  except Exception as exc:
 
143
  log.info("wayback pdf %s: %s", url[-50:], exc)
144
  return None
145
 
146
+ # Live mof.gov.cy often hangs; when CDX ts is known, Wayback-only.
147
+ if prefer_wayback and ts:
148
+ got = _wb(ts)
149
+ if got:
150
+ return got
151
+ return "", url, "none"
152
+ for fn in (_live, _wb):
153
+ got = fn(ts) if fn is _wb else _live()
154
  if got:
155
  return got
156
  return "", url, "none"
scrapers/world_lib.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared helpers for new-country official gazette collectors."""
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import re
8
+ import time
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ from pathlib import Path
13
+ from typing import Optional
14
+ from urllib.parse import urljoin, urlparse
15
+
16
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
17
+ from common import (
18
+ ROOT,
19
+ DEFAULT_UA,
20
+ base_record,
21
+ ensure_dirs,
22
+ existing_ids,
23
+ html_to_text,
24
+ http_get,
25
+ iso_date,
26
+ log_failure,
27
+ slug_id,
28
+ split_articles,
29
+ utcnow,
30
+ write_instrument,
31
+ write_summary,
32
+ )
33
+ import archive_fallbacks as af
34
+
35
+ log = logging.getLogger("world_lib")
36
+
37
+ MIN_TEXT = 80
38
+ MAX_PDF = 35 * 1024 * 1024
39
+
40
+
41
+ def setup_log(cc: str, name: str | None = None) -> None:
42
+ ensure_dirs(cc)
43
+ logging.basicConfig(
44
+ level=logging.INFO,
45
+ format="%(asctime)s %(levelname)s %(message)s",
46
+ handlers=[
47
+ logging.FileHandler(ROOT / cc / "logs" / "collector.log", encoding="utf-8"),
48
+ logging.StreamHandler(sys.stdout),
49
+ ],
50
+ force=True,
51
+ )
52
+
53
+
54
+ def pdf_to_text(raw: bytes) -> str:
55
+ if not raw or raw[:4] != b"%PDF":
56
+ return ""
57
+ try:
58
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
59
+ tmp.write(raw)
60
+ tmp.flush()
61
+ proc = subprocess.run(
62
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
63
+ check=False,
64
+ capture_output=True,
65
+ timeout=180,
66
+ )
67
+ if proc.returncode == 0 and proc.stdout:
68
+ return proc.stdout.decode("utf-8", "replace").strip()
69
+ except Exception as exc:
70
+ log.warning("pdftotext: %s", exc)
71
+ return ""
72
+
73
+
74
+ def split_custom(text: str, law_id: str, source_url: str, date: Optional[str], pattern: Optional[re.Pattern]) -> list[dict]:
75
+ docs = split_articles(text, law_id, source_url, date)
76
+ if not pattern:
77
+ return docs
78
+ matches = list(pattern.finditer(text or ""))
79
+ if len(matches) < 2:
80
+ return docs if len(docs) >= 2 else []
81
+ out = []
82
+ for i, m in enumerate(matches):
83
+ start = m.start()
84
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
85
+ chunk = text[start:end].strip()
86
+ if len(chunk) < 20:
87
+ continue
88
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
89
+ aid = re.sub(r"[^a-zA-Z0-9\u0400-\u04FF\u0530-\u058F-]+", "-", num.lower()).strip("-")[:80]
90
+ heading = chunk.split("\n", 1)[0][:200]
91
+ out.append({
92
+ "id": f"{law_id}-{aid}"[:180],
93
+ "title": heading,
94
+ "text": chunk,
95
+ "date_filed": date,
96
+ "document_number": num,
97
+ "source_url": source_url,
98
+ "record_type": "article",
99
+ "article_number": num,
100
+ "law_identifier": law_id,
101
+ "metadata": {"text_extraction": {"source": "official", "backend": "collector"}},
102
+ })
103
+ if len(out) >= 4000:
104
+ break
105
+ return out if len(out) >= 2 else docs
106
+
107
+
108
+ def live_get(url: str, *, ua: str = DEFAULT_UA, timeout: tuple = (20, 90), verify: bool = True, retries: int = 3):
109
+ import requests
110
+ from requests.packages.urllib3.exceptions import InsecureRequestWarning
111
+ requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
112
+ last = None
113
+ headers = {"User-Agent": ua, "Accept": "application/pdf, text/html, application/xml, */*"}
114
+ for attempt in range(1, retries + 1):
115
+ try:
116
+ time.sleep(0.2)
117
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=verify, allow_redirects=True)
118
+ return resp
119
+ except Exception as exc:
120
+ last = exc
121
+ if verify and ("SSL" in type(exc).__name__ or "SSL" in str(exc)):
122
+ try:
123
+ resp = requests.get(url, timeout=timeout, headers=headers, verify=False, allow_redirects=True)
124
+ return resp
125
+ except Exception as exc2:
126
+ last = exc2
127
+ time.sleep(min(8, 1.5 * attempt))
128
+ raise RuntimeError(f"live_get failed {url}: {last}")
129
+
130
+
131
+ def fetch_official(
132
+ url: str,
133
+ *,
134
+ ua: str = DEFAULT_UA,
135
+ verify: bool = True,
136
+ wayback: bool = True,
137
+ wayback_ts: Optional[str] = None,
138
+ min_text: int = MIN_TEXT,
139
+ ) -> dict:
140
+ """Live official URL first; Wayback of the same official URL on failure. No WAF bypass."""
141
+ out = {
142
+ "status": "error",
143
+ "text": "",
144
+ "content": b"",
145
+ "source_url": url,
146
+ "method": "",
147
+ "content_type": "",
148
+ "error": "",
149
+ }
150
+ body = b""
151
+ ctype = ""
152
+ try:
153
+ r = live_get(url, ua=ua, verify=verify)
154
+ body = r.content or b""
155
+ ctype = r.headers.get("content-type") or ""
156
+ if r.status_code == 200 and body:
157
+ if body[:4] == b"%PDF" or "pdf" in ctype.lower():
158
+ text = pdf_to_text(body)
159
+ if len(text) >= min_text:
160
+ out.update(status="success", text=text, content=body, method="http_pdf", content_type=ctype)
161
+ return out
162
+ text = ""
163
+ if "html" in ctype.lower() or "xml" in ctype.lower() or "json" in ctype.lower() or body[:1] in (b"<", b"{", b"["):
164
+ raw = body.decode(r.encoding or "utf-8", "replace")
165
+ if af.is_challenge(raw, r.status_code):
166
+ out["error"] = "challenge_or_shell"
167
+ else:
168
+ text = html_to_text(raw) if "<" in raw[:500] else raw
169
+ if len(text) >= min_text and not af.is_spa_shell(raw, text):
170
+ out.update(status="success", text=text, content=body, method="http_html", content_type=ctype)
171
+ return out
172
+ if len(text) < min_text:
173
+ out["error"] = "short_or_spa"
174
+ elif body[:4] == b"%PDF":
175
+ out["error"] = "pdf_extract_failed"
176
+ elif len(body) > min_text:
177
+ try:
178
+ text = body.decode("utf-8", "replace")
179
+ if text.lstrip().startswith("%PDF") or "endobj" in text[:200]:
180
+ out["error"] = "raw_pdf_bytes"
181
+ elif len(text) >= min_text:
182
+ out.update(status="success", text=text, content=body, method="http_text", content_type=ctype)
183
+ return out
184
+ except Exception:
185
+ pass
186
+ else:
187
+ out["error"] = f"http_{getattr(r, 'status_code', '?')}"
188
+ except Exception as exc:
189
+ out["error"] = f"live:{exc}"
190
+
191
+ if wayback:
192
+ try:
193
+ w = af.get_wayback_content(url, timestamp=wayback_ts)
194
+ if w.get("status") == "success":
195
+ raw_b = w.get("content") or b""
196
+ raw_t = w.get("text") or ""
197
+ if (isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF") or (raw_t[:4] == "%PDF"):
198
+ pdf_bytes = raw_b if isinstance(raw_b, bytes) and raw_b[:4] == b"%PDF" else raw_t.encode("latin-1", "replace")
199
+ text = pdf_to_text(pdf_bytes)
200
+ if len(text) >= min_text and not text.lstrip().startswith("%PDF"):
201
+ out.update(
202
+ status="success",
203
+ text=text,
204
+ content=pdf_bytes,
205
+ method="wayback_pdf",
206
+ source_url=w.get("url") or url,
207
+ content_type="application/pdf",
208
+ )
209
+ return out
210
+ out["error"] = (out.get("error") or "") + ";pdf_extract_failed"
211
+ return out
212
+ if not raw_t and isinstance(raw_b, bytes):
213
+ raw_t = raw_b.decode("utf-8", "replace")
214
+ if raw_t.lstrip().startswith("%PDF") or "endobj" in raw_t[:200]:
215
+ out["error"] = (out.get("error") or "") + ";raw_pdf_bytes"
216
+ return out
217
+ text = html_to_text(raw_t) if "<" in (raw_t[:400] or "") else raw_t
218
+ if len(text) >= min_text and not af.is_challenge(raw_t, 200):
219
+ out.update(
220
+ status="success",
221
+ text=text,
222
+ content=raw_b if isinstance(raw_b, bytes) else raw_t.encode("utf-8", "replace"),
223
+ method="wayback_html",
224
+ source_url=w.get("url") or url,
225
+ content_type=w.get("content_type") or "text/html",
226
+ )
227
+ return out
228
+ out["error"] = (out.get("error") or "") + ";wayback_short"
229
+ else:
230
+ out["error"] = (out.get("error") or "") + f";wayback:{w.get('error')}"
231
+ except Exception as exc:
232
+ out["error"] = (out.get("error") or "") + f";wayback:{exc}"
233
+ return out
234
+
235
+
236
+ def first_title(text: str, fallback: str) -> str:
237
+ for line in (text or "").splitlines():
238
+ s = line.strip()
239
+ if len(s) >= 12 and not s.lower().startswith("just a moment"):
240
+ return s[:240]
241
+ return fallback[:240]
242
+
243
+
244
+ def save_instrument(
245
+ *,
246
+ cc: str,
247
+ country: str,
248
+ language: str,
249
+ ident: str,
250
+ title: str,
251
+ text: str,
252
+ source_url: str,
253
+ source_type: str,
254
+ license_text: str,
255
+ collector: str,
256
+ date: Optional[str] = None,
257
+ article_re: Optional[re.Pattern] = None,
258
+ extra_meta: Optional[dict] = None,
259
+ ) -> bool:
260
+ if not text or len(text) < MIN_TEXT:
261
+ return False
262
+ rid = slug_id(cc, ident)
263
+ docs = split_custom(text, rid, source_url, date, article_re)
264
+ rec = base_record(
265
+ cc=cc,
266
+ country=country,
267
+ language=language,
268
+ ident=ident,
269
+ title=title or first_title(text, ident),
270
+ text=text,
271
+ source_url=source_url,
272
+ source_type=source_type,
273
+ license_text=license_text,
274
+ collector=collector,
275
+ date=iso_date(date) or date,
276
+ documents=docs,
277
+ extra_meta=extra_meta,
278
+ )
279
+ write_instrument(cc, rec)
280
+ return True
281
+
282
+
283
+ def cdx_urls(host_or_url: str, *, limit: int = 200, match_type: str = "prefix", extra_filters=None) -> list[dict]:
284
+ try:
285
+ hits = af.search_wayback_machine(
286
+ host_or_url,
287
+ limit=limit,
288
+ match_type=match_type,
289
+ collapse="urlkey",
290
+ extra_filters=extra_filters,
291
+ )
292
+ except Exception as exc:
293
+ log.info("cdx err %s: %s", host_or_url, exc)
294
+ return []
295
+ return hits or []
296
+
297
+
298
+ def env_int(name: str, default: int) -> int:
299
+ try:
300
+ return int(os.environ.get(name, str(default)) or default)
301
+ except Exception:
302
+ return default