endomorphosis commited on
Commit
f2e9425
·
verified ·
1 Parent(s): f1feb70

Refresh cyprus laws research snapshot (incomplete/catalog-backed; official source prevails; not legal advice)

Browse files
Files changed (6) hide show
  1. MANIFEST.md +20 -8
  2. README.md +12 -10
  3. data/articles.parquet +2 -2
  4. data/laws.parquet +2 -2
  5. scrapers/collect_cy.py +636 -273
  6. scrapers/common.py +22 -4
MANIFEST.md CHANGED
@@ -1,9 +1,21 @@
1
- # MANIFEST
2
 
3
- - generated_at: 2026-09-04T19:32:20Z
4
- - laws: 302
5
- - articles: 4398
6
- - files:
7
- - data/laws.parquet: 13048112 bytes
8
- - data/articles.parquet: 9669073 bytes
9
- - README.md: 1631 bytes
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ipfs_cyprus_laws manifest
2
 
3
+ generated_utc: 2026-09-04T19:41:10Z
4
+ cc: cy
5
+ slug: cyprus
6
+ laws_rows: 341
7
+ articles_rows: 111
8
+ laws_bytes: 9687597
9
+ articles_bytes: 279292
10
+ laws_sha256: 97e6df2b84f3ca611e23d8e91d8c942f1741c84307148d19faad09b5bfce6212
11
+ articles_sha256: 345b8cd23246bb4d09a81a6b3e8c62b966ae747ca501be9ffec34303a17d9dc2
12
+ laws_parquet: /workspace/legal-corpora-releases/cyprus/data/laws.parquet
13
+ articles_parquet: /workspace/legal-corpora-releases/cyprus/data/articles.parquet
14
+ compression: zstd
15
+ collector: scrapers/collect_cy.py
16
+ source: Cyprus Government Printing Office gazette (mof.gov.cy)
17
+ coverage: CDX/Wayback expand research snapshot; quality_good>=400=340 short=1 junk=0
18
+ snapshot_date: 2026-09-04
19
+ uploaded: false
20
+ gaps:
21
+ Method: cdx_parallel_expand + archive_fallbacks. Not complete. Official source prevails. Not legal advice.
README.md CHANGED
@@ -1,7 +1,7 @@
1
  ---
2
- pretty_name: Laws of Cyprus
3
  license: other
4
- license_name: cyprus-gpo-gazette
5
  language:
6
  - el
7
  task_categories:
@@ -10,6 +10,8 @@ tags:
10
  - legal
11
  - law
12
  - cyprus
 
 
13
  - official-texts
14
  size_categories:
15
  - n<1K
@@ -21,9 +23,9 @@ configs:
21
  data_files: data/articles.parquet
22
  ---
23
 
24
- # Laws of Cyprus
25
 
26
- Research snapshot of official legislation collected from **GPO mof.gov.cy**.
27
 
28
  **Not legal advice.** Official gazettes / government portals prevail over this corpus.
29
 
@@ -32,14 +34,14 @@ Research snapshot of official legislation collected from **GPO mof.gov.cy**.
32
  | Field | Value |
33
  | --- | --- |
34
  | Snapshot date | 2026-09-04 |
35
- | Coverage | catalog-backed incomplete |
36
- | Source | GPO mof.gov.cy |
37
  | Collector | `scrapers/collect_cy.py` |
38
- | Laws / instruments | 302 |
39
- | Articles | 4398 |
40
  | Language | el |
41
  | Jurisdiction | Cyprus |
42
- | License | `cyprus-gpo-gazette` |
43
 
44
  ## Contents
45
 
@@ -61,4 +63,4 @@ The official source prevails.
61
 
62
  ## Notes
63
 
64
- Deepen: GPO gazette PDFs via Wayback CDX (no cylaw) + cy_extract_articles. Not legal advice.
 
1
  ---
2
+ pretty_name: Laws of Cyprus (GPO gazette)
3
  license: other
4
+ license_name: cyprus-gpo-official
5
  language:
6
  - el
7
  task_categories:
 
10
  - legal
11
  - law
12
  - cyprus
13
+ - gpo
14
+ - gazette
15
  - official-texts
16
  size_categories:
17
  - n<1K
 
23
  data_files: data/articles.parquet
24
  ---
25
 
26
+ # Laws of Cyprus (GPO gazette)
27
 
28
+ Research snapshot of official legislation collected from **Cyprus Government Printing Office gazette (mof.gov.cy)**.
29
 
30
  **Not legal advice.** Official gazettes / government portals prevail over this corpus.
31
 
 
34
  | Field | Value |
35
  | --- | --- |
36
  | Snapshot date | 2026-09-04 |
37
+ | Coverage | CDX/Wayback expand research snapshot; quality_good>=400=340 short=1 junk=0 |
38
+ | Source | Cyprus Government Printing Office gazette (mof.gov.cy) |
39
  | Collector | `scrapers/collect_cy.py` |
40
+ | Laws / instruments | 341 |
41
+ | Articles | 111 |
42
  | Language | el |
43
  | Jurisdiction | Cyprus |
44
+ | License | `cyprus-gpo-official` |
45
 
46
  ## Contents
47
 
 
63
 
64
  ## Notes
65
 
66
+ Method: cdx_parallel_expand + archive_fallbacks. Not complete. Official source prevails. Not legal advice.
data/articles.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:92692042d7ead4a887d448971284ebbdc9927cde1e2053650a5821d371b805f4
3
- size 9669073
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:345b8cd23246bb4d09a81a6b3e8c62b966ae747ca501be9ffec34303a17d9dc2
3
+ size 279292
data/laws.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0869c92729d15d1bbb3fae32f3feead651fdacecd7aa141a070073539dcd89cf
3
- size 13048112
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:97e6df2b84f3ca611e23d8e91d8c942f1741c84307148d19faad09b5bfce6212
3
+ size 9687597
scrapers/collect_cy.py CHANGED
@@ -1,319 +1,682 @@
1
  #!/usr/bin/env python3
2
- """Cyprus: official GPO gazette (mof.gov.cy). PDF body extraction. Not cylaw.org."""
 
 
 
 
 
 
 
 
 
 
3
  from __future__ import annotations
4
- import io, json, logging, os, re, sys, time
 
 
 
 
 
 
 
5
  from pathlib import Path
6
- from urllib.parse import urljoin, unquote
 
7
  sys.path.insert(0, str(Path(__file__).resolve().parent))
8
- from common import *
9
- import archive_fallbacks as af
 
 
10
 
11
  CC, COUNTRY, SOURCE_TYPE = "cy", "Cyprus", "gpo_gazette"
12
- LICENSE = "Official Gazette of the Republic of Cyprus, Government Printing Office (mof.gov.cy/gpo). cylaw.org is unofficial and is NOT used."
 
 
 
13
  UA = DEFAULT_UA + " source=https://www.mof.gov.cy/mof/gpo/"
 
 
14
  log = logging.getLogger("cy")
15
 
16
- ASSET_RE = re.compile(r"\.(css|js|png|jpe?g|gif|svg|ico|woff2?|ttf|map)(\?|$)", re.I)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
 
19
  def setup():
20
  ensure_dirs(CC)
21
- logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",
22
- handlers=[logging.FileHandler(ROOT / CC / "logs" / "collector.log", encoding="utf-8"),
23
- logging.StreamHandler(sys.stdout)])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
 
27
- def known_fail_keys() -> set[str]:
28
- """Skip identifiers / URL keys that already failed empty extracts this session history."""
29
- out = set()
30
- fp = ROOT / CC / "failures.jsonl"
31
- if not fp.exists():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  return out
33
- for line in fp.open(encoding="utf-8"):
34
  try:
35
- d = json.loads(line)
36
  except Exception:
37
  continue
38
- ident = str(d.get("identifier") or "")
39
- url = str(d.get("source_url") or "")
40
- if ident:
41
- out.add(ident.lower())
42
- if url:
43
- out.add(unquote(url).lower())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  return out
45
 
46
 
47
- def try_get(url, verify_first=True):
48
- last = None
49
- order = (True, False) if verify_first else (False, True)
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:
57
- last = exc
58
- return last, None
 
 
 
 
 
 
 
 
 
59
 
 
 
 
 
 
 
 
 
 
60
 
61
- def pdf_to_text(data: bytes) -> str:
62
- """Extract PDF text; prefer pdfplumber (ipfs_datasets_py IntegratedPDFProcessor path)."""
63
- # 1) pdfplumber — same primary backend as IntegratedPDFProcessor._extract_text_from_pdf
64
  try:
65
- import pdfplumber
66
- with pdfplumber.open(io.BytesIO(data)) as pdf:
67
- parts = []
68
- for page in pdf.pages[:120]:
69
- try:
70
- parts.append(page.extract_text() or "")
71
- except Exception:
72
- continue
73
- text = "\n".join(parts)
74
- text = re.sub(r"[ \t]+", " ", text)
75
- text = re.sub(r"\n{3,}", "\n\n", text).strip()
76
- if len(text) >= 40:
77
- return text
78
  except Exception as exc:
79
- log.info("pdfplumber fail: %s", exc)
80
- # 2) pypdf fallback
 
81
  try:
82
- from pypdf import PdfReader
83
- reader = PdfReader(io.BytesIO(data))
84
- parts = []
85
- for page in reader.pages[:120]:
86
- try:
87
- parts.append(page.extract_text() or "")
88
- except Exception:
89
- continue
90
- text = "\n".join(parts)
91
- text = re.sub(r"[ \t]+", " ", text)
92
- text = re.sub(r"\n{3,}", "\n\n", text)
93
- return text.strip()
94
  except Exception as exc:
95
- log.info("pdf extract fail: %s", exc)
96
- return ""
 
97
 
98
-
99
- def is_gazette_pdf_url(url: str) -> bool:
100
- u = (url or "").lower()
101
- if "cylaw.org" in u:
102
- return False
103
- if ASSET_RE.search(u):
104
- return False
105
- uq = unquote(u)
106
- if ("$file/" in uq or "%24file/" in u) and (uq.rstrip().endswith(".pdf") or ".pdf" in uq):
107
- if "mof.gov.cy" in u and "gpo" in u:
108
- return True
109
- if uq.rstrip().endswith(".pdf") and "mof.gov.cy" in u and "gpo" in u:
110
- return True
111
- return False
112
-
113
-
114
- def fetch_pdf(url: str, ts: str = "", *, prefer_wayback: bool = False) -> tuple[str, str, str]:
115
- """Return (text, source_url, kind). When CDX ts known, try Wayback first to avoid live hangs."""
116
- def _live():
117
- r, verify = try_get(url, verify_first=False)
118
- if hasattr(r, "status_code") and r.status_code == 200 and r.content and r.content[:5] == b"%PDF-":
119
- text = pdf_to_text(r.content)
120
- if len(text) >= 80:
121
- return text, url, "pdf_live"
122
- return None
123
-
124
- def _wb(ts_in: str):
125
  try:
126
- t = ts_in
127
- u = url
128
- if not t:
129
- hits = af.search_wayback_machine(u, limit=1, collapse="")
130
- if hits:
131
- t = hits[0].get("timestamp") or ""
132
- u = hits[0].get("original") or u
133
- if not t:
134
- return None
135
- w = af.get_wayback_content(u, timestamp=t)
136
- if w.get("status") == "success":
137
- content = w.get("content")
138
- if isinstance(content, bytes) and content[:5] == b"%PDF-":
139
- text = pdf_to_text(content)
140
- if len(text) >= 80:
141
- return text, w.get("url") or u, "pdf_wayback"
142
  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"
157
-
158
-
159
- def cdx_pdf_candidates(limit: int = 400) -> list[tuple[str, str]]:
160
- """Return list of (url, timestamp) for official GPO gazette PDFs via Wayback CDX."""
161
- out, seen = [], set()
162
- # Direct CDX with mime filter — more reliable than generic helper for Domino $file PDFs
163
- import requests
164
- params = {
165
- "url": "www.mof.gov.cy/mof/gpo/gazette.nsf/*",
166
- "output": "json",
167
- "fl": "timestamp,original,mimetype,statuscode",
168
- "filter": ["mimetype:application/pdf", "statuscode:200"],
169
- "collapse": "urlkey",
170
- "limit": str(limit),
171
- }
172
  try:
173
- import json
174
- q = [
175
- ("url", "www.mof.gov.cy/mof/gpo/gazette.nsf/*"),
176
- ("output", "json"),
177
- ("fl", "timestamp,original,mimetype,statuscode"),
178
- ("filter", "mimetype:application/pdf"),
179
- ("filter", "statuscode:200"),
180
- ("collapse", "urlkey"),
181
- ("limit", str(limit)),
182
- ]
183
- last = None
184
- for attempt in range(1, 5):
185
- time.sleep(0.6 * attempt)
186
- r = requests.get("https://web.archive.org/cdx/search/cdx", params=q, timeout=(20, 120),
187
- headers={"User-Agent": UA})
188
- last = r
189
- if r.status_code == 200 and r.content and r.content[:1] == b"[":
190
- rows = json.loads(r.content)
191
- for row in rows[1:]:
192
- ts, orig = row[0], row[1]
193
- if not is_gazette_pdf_url(orig):
194
- continue
195
- key = unquote(orig).lower()
196
- if key in seen:
197
- continue
198
- seen.add(key)
199
- out.append((orig, ts))
200
- log.info("cdx mime-pdf unique=%s", len(out))
201
- break
202
- log.info("cdx attempt %s HTTP %s", attempt, getattr(r, "status_code", "?"))
203
- time.sleep(2 * attempt)
204
- else:
205
- log.info("cdx direct exhausted last=%s", getattr(last, "status_code", last))
206
  except Exception as exc:
207
- log.info("cdx direct fail: %s", exc)
208
- if len(out) < 20:
209
- # fallback via helper + $file filter
210
- try:
211
- hits = af.search_wayback_machine(
212
- "www.mof.gov.cy/mof/gpo/gazette.nsf/*", limit=limit, match_type="prefix", collapse="urlkey"
213
- )
214
- for h in hits or []:
215
- u = (h.get("original") or "").strip()
216
- if not is_gazette_pdf_url(u):
217
- continue
218
- key = unquote(u).lower()
219
- if key in seen:
220
- continue
221
- seen.add(key)
222
- out.append((u, h.get("timestamp") or ""))
223
- log.info("cdx helper pdf unique=%s", len(out))
224
- except Exception as exc:
225
- log.info("cdx helper fail: %s", exc)
226
- out.sort(key=lambda x: x[1] or "", reverse=True)
227
- return out
228
 
 
 
 
229
 
230
- def main():
231
- setup(); t0 = utcnow()
232
- max_new = int(os.environ.get("MAX_NEW", "0") or 0)
233
- max_seconds = int(os.environ.get("MAX_SECONDS", "0") or 0)
234
- t_start = time.time()
235
- notes = ["PDF-focused CDX of official GPO gazette.nsf $file URLs. cylaw.org not used."]
236
- cands = cdx_pdf_candidates(int(os.environ.get("MAX_CATALOG", "400") or 400))
237
- # Also scrape live listing pages for any $file PDF hrefs
238
- seeds = [
239
- "https://www.mof.gov.cy/mof/gpo/gazette.nsf/dmlgaz_NEW_gr/dmlgaz_NEW_gr?OpenDocument",
240
- "https://www.mof.gov.cy/mof/gpo/gazette.nsf/dmlgaz_app_gr/dmlgaz_app_gr?OpenDocument",
241
- "https://www.mof.gov.cy/mof/gpo/gazette.nsf/dmlgazette_archive_gr/dmlgazette_archive_gr?OpenForm",
242
- "https://www.mof.gov.cy/mof/gpo/gazette.nsf/officialgazette-el/officialgazette-el?OpenDocument",
243
- ]
244
- seen = {unquote(u).lower() for u, _ in cands}
245
- for url in seeds:
246
- r, verify = try_get(url, verify_first=False)
247
- if not hasattr(r, "status_code"):
248
- notes.append(f"seed {url} ERROR {r}")
249
- continue
250
- notes.append(f"seed {url} -> HTTP {r.status_code} bytes={len(r.content or b'')} verify={verify}")
251
- if r.status_code == 200 and r.content:
252
- for href in re.findall(r'href=["\']([^"\']+)["\']', r.text, flags=re.I):
253
- href = urljoin(url, href)
254
- if is_gazette_pdf_url(href) and unquote(href).lower() not in seen:
255
- seen.add(unquote(href).lower())
256
- cands.append((href, ""))
257
- log.info("pdf candidates %s", len(cands))
258
- done = existing_ids(CC); ok = skip = fail = 0
259
- known_fail = known_fail_keys()
260
- log.info("known_fail keys=%s", len(known_fail))
261
- for href, ts in cands:
262
- if max_new and ok >= max_new:
263
- break
264
- if max_seconds and (time.time() - t_start) > max_seconds:
265
- break
266
- ident = re.sub(r"^https?://", "", href)
267
- # Prefer filename as stable id when Domino $file present
268
- m = re.search(r"\$file/([^/?#]+)", href, re.I)
269
- if m:
270
- ident = "gpo-pdf-" + unquote(m.group(1))
271
  rid = slug_id(CC, ident)
272
- if rid in done:
 
273
  skip += 1
274
  continue
275
- if ident.lower() in known_fail or unquote(href).lower() in known_fail:
276
- skip += 1
 
 
 
277
  continue
278
- log.info("try %s ts=%s", ident[:80], (ts or "")[:14])
279
- text, src, kind = fetch_pdf(href, ts, prefer_wayback=bool(ts))
280
- if len(text) < 80:
281
  fail += 1
282
- log_failure(CC, {"identifier": ident, "source_url": href, "status": "failed", "reason": f"empty_{kind}"})
283
- log.info("fail %s kind=%s", ident[:70], kind)
284
  continue
285
- title = unquote(m.group(1)) if m else ident
286
- for line in text.splitlines():
287
- if len(line.strip()) > 12:
288
- title = line.strip()[:240]
289
- break
290
- rec = base_record(
291
- cc=CC, country=COUNTRY, language="el", ident=ident, title=title, text=text,
292
- source_url=src, source_type=SOURCE_TYPE, license_text=LICENSE,
293
- collector="cy-gpo-gazette-pdf", eli=None, date=None, official_identifier=ident,
294
- document_type="gazette_pdf", law_status="unknown", is_current=None,
295
- documents=[], # whole-issue PDFs; no honest per-article split from structure
296
- extra_meta={"discovery": {"backend": kind, "original_url": href, "wayback_ts": ts,
297
- "article_note": "whole_issue_pdf_articles_0"}},
298
- )
299
- write_instrument(CC, rec); ok += 1; done.add(rid)
300
- log.info("ok %s kind=%s chars=%s", rid[:70], kind, len(text))
301
- if ok and ok % 10 == 0:
302
- write_summary(CC, country=COUNTRY, source="Cyprus GPO gazette PDFs",
303
- source_urls=["https://www.mof.gov.cy/mof/gpo/gazette.nsf/"],
304
- license_text=LICENSE, discovered=len(cands), fetched=ok, skipped=skip, failed=fail,
305
- coverage="shard", notes="\n".join(notes), last_run=utcnow())
306
- if not ok:
307
- notes.append(
308
- "Blocker: few/no extractable PDF bodies this run. legislation.gov.cy NXDOMAIN; "
309
- "GPO TLS incomplete chain; cylaw.org forbidden. Used Wayback CDX of official $file PDFs."
310
- )
311
- write_summary(CC, country=COUNTRY, source="Cyprus Government Printing Office gazette PDFs",
312
- source_urls=["https://www.mof.gov.cy/mof/gpo/gazette.nsf/officialgazette-el/officialgazette-el?OpenDocument",
313
- "https://www.gov.cy/en/service/episimi-efimerida-tis-dimokratias/"],
314
- license_text=LICENSE, discovered=len(cands), fetched=ok, skipped=skip, failed=fail,
315
- coverage="catalog-backed incomplete", notes="\n".join(notes), last_run=utcnow(), extra=f"started {t0}")
316
- log.info("done disc=%s ok=%s fail=%s skip=%s", len(cands), ok, fail, skip)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
 
318
 
319
  if __name__ == "__main__":
 
1
  #!/usr/bin/env python3
2
+ """Cyprus: official GPO gazette PDFs (mof.gov.cy). No cylaw.org.
3
+
4
+ Discovery:
5
+ 1) Live Domino section views (Κύριο Μέρος / Παραρτήματα)
6
+ 2) Archive outline Expand=year.month.part (2004–present)
7
+ 3) Per-issue OpenDocument pages → $file PDF attachments
8
+ 4) Wayback CDX of official GPO $file / gazette.nsf URLs (fallback)
9
+
10
+ PDFs extracted via pdftotext (common.pdf_bytes_to_text). TLS verify may fail
11
+ on incomplete GPO chain from this network — official host still used.
12
+ """
13
  from __future__ import annotations
14
+
15
+ import html as htmlmod
16
+ import json
17
+ import logging
18
+ import re
19
+ import sys
20
+ import time
21
+ import warnings
22
  from pathlib import Path
23
+ from urllib.parse import urljoin, unquote, quote
24
+
25
  sys.path.insert(0, str(Path(__file__).resolve().parent))
26
+ from common import * # noqa: F401,F403
27
+ from archive_fallbacks import search_wayback_machine, get_wayback_content
28
+
29
+ warnings.filterwarnings("ignore", message="Unverified HTTPS request")
30
 
31
  CC, COUNTRY, SOURCE_TYPE = "cy", "Cyprus", "gpo_gazette"
32
+ LICENSE = (
33
+ "Official Gazette of the Republic of Cyprus, Government Printing Office "
34
+ "(mof.gov.cy/gpo). cylaw.org is unofficial and is NOT used."
35
+ )
36
  UA = DEFAULT_UA + " source=https://www.mof.gov.cy/mof/gpo/"
37
+ BASE = "https://www.mof.gov.cy"
38
+ GAZETTE_NSF = f"{BASE}/mof/gpo/gazette.nsf"
39
  log = logging.getLogger("cy")
40
 
41
+ # Domino All/{UNID}?OpenDocument
42
+ UNID_RE = re.compile(r"/mof/gpo/gazette\.nsf/All/([0-9A-Fa-f]{32})\?OpenDocument", re.I)
43
+ # $file PDF hrefs (spaces in filenames are common)
44
+ FILE_RE = re.compile(
45
+ r"""(?:href|src)\s*=\s*["']([^"']*\$[Ff][Ii][Ll][Ee]/[^"']+\.pdf)["']""",
46
+ re.I,
47
+ )
48
+ # Expand=Y.M.P outline links
49
+ EXPAND_RE = re.compile(
50
+ r"dmlgazette_archive_gr\?OpenForm[^\"']*Expand=([0-9]+(?:\.[0-9]+){0,3})",
51
+ re.I,
52
+ )
53
+ # Skip chrome / policy pages
54
+ SKIP_PATH_RE = re.compile(
55
+ r"(accessibility|privacypolicy|gazetteinfo|favicon|settings\.css|"
56
+ r"officialgazette-(?:el|en)|dmlgaz_NEW_|dmlgaz_app_|dmlprevious|"
57
+ r"dmlgazette_archive|dmlgaz_view_sections|SearchResults|"
58
+ r"font-awesome|icon-font|layers\.css|navigation\.css)",
59
+ re.I,
60
+ )
61
+ CYLAW_RE = re.compile(r"cylaw\.org", re.I)
62
+
63
+ # Greek gazette instrument markers inside PDF text
64
+ CY_ART_RE = re.compile(
65
+ r"(?im)^\s*((?:Άρθρο|Αρθρο|Aρθρο|Άρθρον|Αριθμός|Aριθμός|Αρ\.)\s+"
66
+ r"[\dIVXLCDM]+[A-Za-zΑ-Ωα-ω΄']*)\b"
67
+ )
68
+
69
+ # How far back to walk the archive outline (Expand index 1 = newest year)
70
+ MAX_YEAR_EXPAND = 23 # ~2004–2026
71
+ MAX_CDX = 2500
72
+ FETCH_SLEEP = 0.35
73
 
74
 
75
  def setup():
76
  ensure_dirs(CC)
77
+ logging.basicConfig(
78
+ level=logging.INFO,
79
+ format="%(asctime)s %(levelname)s %(message)s",
80
+ handlers=[
81
+ logging.FileHandler(ROOT / CC / "logs" / "collector.log", encoding="utf-8"),
82
+ logging.StreamHandler(sys.stdout),
83
+ ],
84
+ force=True,
85
+ )
86
+
87
+
88
+ def try_get(url: str, *, accept: str = "text/html, application/pdf, */*", binary_ok: bool = True):
89
+ """GET official GPO; retry with verify=False (incomplete cert chain)."""
90
+ last = None
91
+ for verify in (True, False):
92
+ try:
93
+ time.sleep(FETCH_SLEEP)
94
+ r = get_session(UA).get(
95
+ url,
96
+ timeout=(20, 120),
97
+ verify=verify,
98
+ headers={"User-Agent": UA, "Accept": accept},
99
+ allow_redirects=True,
100
+ )
101
+ if r.status_code == 200 and (binary_ok or r.content):
102
+ return r, verify
103
+ last = r
104
+ if r.status_code in (404, 410):
105
+ return r, verify
106
+ except Exception as exc:
107
+ last = exc
108
+ return last, None
109
+
110
+
111
+ def is_official(url: str) -> bool:
112
+ if not url or CYLAW_RE.search(url):
113
+ return False
114
+ u = url.lower()
115
+ return "mof.gov.cy" in u and ("/gpo/" in u or "gazette.nsf" in u or "gpo.nsf" in u)
116
+
117
+
118
+ def extract_unids(html: str) -> list[str]:
119
+ return list(dict.fromkeys(m.group(1).upper() for m in UNID_RE.finditer(html or "")))
120
+
121
+
122
+ def extract_pdf_hrefs(page_url: str, html: str) -> list[str]:
123
+ out = []
124
+ seen = set()
125
+ for m in FILE_RE.finditer(html or ""):
126
+ href = htmlmod.unescape(m.group(1).strip())
127
+ full = urljoin(page_url, href)
128
+ if not is_official(full):
129
+ continue
130
+ if SKIP_PATH_RE.search(full):
131
+ continue
132
+ if full.lower() in seen:
133
+ continue
134
+ seen.add(full.lower())
135
+ out.append(full)
136
+ # also bare $file paths without href=
137
+ for m in re.finditer(r"(/mof/gpo/gazette\.nsf/[0-9A-Fa-f]{32}/\$file/[^\s\"'<>]+\.pdf)", html or "", re.I):
138
+ full = urljoin(BASE, htmlmod.unescape(m.group(1)))
139
+ if full.lower() not in seen and is_official(full):
140
+ seen.add(full.lower())
141
+ out.append(full)
142
+ return out
143
+
144
+
145
+ def split_cy_articles(text: str, law_id: str, source_url: str, date: str | None) -> list[dict]:
146
+ if not text or len(text) < 40:
147
+ return []
148
+ matches = list(CY_ART_RE.finditer(text))
149
+ if len(matches) < 2:
150
+ # fall back to common splitter (may still yield 0)
151
+ return split_articles(text, law_id, source_url, date)
152
+ docs = []
153
+ for i, m in enumerate(matches):
154
+ start = m.start()
155
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
156
+ chunk = text[start:end].strip()
157
+ if len(chunk) < 30:
158
+ continue
159
+ num = re.sub(r"\s+", " ", m.group(1)).strip()
160
+ aid = re.sub(r"[^a-z0-9]+", "-", num.lower()).strip("-") or f"n{i}"
161
+ heading = chunk.split("\n", 1)[0][:200]
162
+ docs.append({
163
+ "id": f"{law_id}-{aid}"[:180],
164
+ "title": heading,
165
+ "text": chunk,
166
+ "date_filed": date,
167
+ "document_number": num,
168
+ "source_url": source_url,
169
+ "record_type": "article",
170
+ "article_number": num,
171
+ "law_identifier": law_id,
172
+ "metadata": {"text_extraction": {"source": "official", "backend": "pdftotext"}},
173
+ })
174
+ if len(docs) >= 4000:
175
+ break
176
+ return docs
177
+
178
 
179
+ def title_from_pdf_url(url: str, text: str) -> str:
180
+ name = unquote(url.split("/")[-1])
181
+ name = re.sub(r"\.pdf$", "", name, flags=re.I).strip()
182
+ name = re.sub(r"\s+", " ", name)
183
+ if text:
184
+ # first non-empty line that looks like gazette header
185
+ for line in text.splitlines()[:40]:
186
+ line = line.strip()
187
+ if len(line) > 12 and re.search(r"(ΕΦΗΜΕΡΙΔΑ|Επίσημη|PARARTIMA|ΠΑΡΑΡΤΗΜΑ|ΚΥΡΙΟ|KYRIO)", line, re.I):
188
+ return line[:240]
189
+ if re.match(r"^Αριθμός\s+\d+", line, re.I) or re.match(r"^Aριθμός\s+\d+", line):
190
+ return (name + " — " + line)[:240]
191
+ return name[:240] or url
192
 
193
 
194
+ def date_from_name(name: str) -> str | None:
195
+ # e.g. "5885 4 9 2026 KYRIO MEROS..." or "4597Α 6 10 2023 PARARTIMA..."
196
+ m = re.search(r"\b(\d{1,2})\s+(\d{1,2})\s+(20\d{2})\b", name)
197
+ if m:
198
+ d, mo, y = int(m.group(1)), int(m.group(2)), int(m.group(3))
199
+ if 1 <= mo <= 12 and 1 <= d <= 31:
200
+ return f"{y:04d}-{mo:02d}-{d:02d}"
201
+ m = re.search(r"\b(20\d{2})[-_/](\d{1,2})[-_/](\d{1,2})\b", name)
202
+ if m:
203
+ return f"{int(m.group(1)):04d}-{int(m.group(2)):02d}-{int(m.group(3)):02d}"
204
+ return None
205
+
206
+
207
+ def pdf_ident(url: str) -> str:
208
+ """Stable identifier from UNID + filename."""
209
+ m = re.search(r"/gazette\.nsf/(?:All/)?([0-9A-Fa-f]{32})/", url, re.I)
210
+ unid = (m.group(1).upper() if m else "nouid")
211
+ fname = unquote(url.split("/")[-1])
212
+ fname = re.sub(r"\.pdf$", "", fname, flags=re.I)
213
+ fname = re.sub(r"\s+", "_", fname.strip())
214
+ return f"gpo-{unid}-{fname}"[:160]
215
+
216
+
217
+ def discover_section_unids(notes: list[str]) -> set[str]:
218
+ unids: set[str] = set()
219
+ # Main + appendix landing pages → section links
220
+ seeds = [
221
+ f"{GAZETTE_NSF}/dmlgaz_NEW_gr/dmlgaz_NEW_gr?OpenDocument",
222
+ f"{GAZETTE_NSF}/dmlgaz_NEW_en/dmlgaz_NEW_en?OpenDocument",
223
+ f"{GAZETTE_NSF}/dmlgaz_app_gr/dmlgaz_app_gr?OpenDocument",
224
+ f"{GAZETTE_NSF}/dmlgaz_app_en/dmlgaz_app_en?OpenDocument",
225
+ f"{GAZETTE_NSF}/officialgazette-el/officialgazette-el?OpenDocument",
226
+ ]
227
+ section_urls = set()
228
+ for url in seeds:
229
+ r, verify = try_get(url)
230
+ if not hasattr(r, "status_code"):
231
+ notes.append(f"seed {url} ERROR {r}")
232
+ continue
233
+ notes.append(f"seed {url} -> HTTP {r.status_code} bytes={len(r.content or b'')} verify={verify}")
234
+ if r.status_code != 200 or not r.content:
235
+ continue
236
+ html = r.text or ""
237
+ unids.update(extract_unids(html))
238
+ for m in re.finditer(r'href=["\']([^"\']*dmlgaz_view_sections[^"\']+)["\']', html, re.I):
239
+ section_urls.add(urljoin(url, htmlmod.unescape(m.group(1))))
240
+ for m in re.finditer(r'href=["\']([^"\']*view_sections[^"\']+)["\']', html, re.I):
241
+ section_urls.add(urljoin(url, htmlmod.unescape(m.group(1))))
242
+ # Explicit sectionNumber sweeps (main parts 1–3; appendices often reuse)
243
+ for sec in range(1, 8):
244
+ for cp in ("11", "21", "22", "12", "31", "32"):
245
+ section_urls.add(
246
+ f"{GAZETTE_NSF}/dmlgaz_view_sections_gr/dmlgaz_view_sections_gr"
247
+ f"?OpenDocument&OpenView&Count=1000&cp={cp}&sectionNumber={sec}"
248
+ )
249
+ section_urls.add(
250
+ f"{GAZETTE_NSF}/dmlgaz_view_sections_gr/dmlgaz_view_sections_gr"
251
+ f"?OpenDocument&sectionNumber={sec}&cp={cp}"
252
+ )
253
+ # Prefer Count=1000 OpenView URLs; skip redundant Start pagination when
254
+ # Domino returns a small page (typical ~20) — use archive Expand for depth.
255
+ prefer = [u for u in sorted(section_urls) if "Count=1000" in u or "OpenView" in u]
256
+ rest = [u for u in sorted(section_urls) if u not in prefer]
257
+ for url in prefer + rest[:20]:
258
+ if not is_official(url):
259
+ continue
260
+ r, _ = try_get(url)
261
+ if not hasattr(r, "status_code") or r.status_code != 200 or not r.content:
262
+ continue
263
+ found = extract_unids(r.text or "")
264
+ before = len(unids)
265
+ unids.update(found)
266
+ # Only paginate when the view clearly has a large batch
267
+ if len(found) >= 80 and ("OpenView" in url or "Count=" in url):
268
+ for start in (31, 61, 91, 121, 151, 181, 211, 241, 271, 301):
269
+ page = url
270
+ if "Start=" in page:
271
+ page = re.sub(r"Start=\d+", f"Start={start}", page)
272
+ else:
273
+ page = page + ("&" if "?" in page else "?") + f"Start={start}"
274
+ r2, _ = try_get(page)
275
+ if not hasattr(r2, "status_code") or r2.status_code != 200 or not r2.content:
276
+ break
277
+ more = extract_unids(r2.text or "")
278
+ new_n = len(set(more) - unids)
279
+ unids.update(more)
280
+ if new_n == 0:
281
+ break
282
+ log.info("section +%s total_unids=%s url=%s", len(unids) - before, len(unids), url[-80:])
283
+ return unids
284
+
285
+
286
+ def discover_archive_unids(notes: list[str]) -> set[str]:
287
+ """Walk Domino outline Expand=year[.month[.part]]."""
288
+ unids: set[str] = set()
289
+ archive = f"{GAZETTE_NSF}/dmlgazette_archive_gr/dmlgazette_archive_gr?OpenForm&Start=1&Count=9999"
290
+ # First fetch root to learn year expand indices
291
+ r, _ = try_get(archive)
292
+ year_idxs = list(range(1, MAX_YEAR_EXPAND + 1))
293
+ if hasattr(r, "status_code") and r.status_code == 200 and r.content:
294
+ found_exp = {int(m.group(1).split(".")[0]) for m in EXPAND_RE.finditer(r.text or "") if "." not in m.group(1)}
295
+ if found_exp:
296
+ year_idxs = sorted(found_exp)[:MAX_YEAR_EXPAND]
297
+ notes.append(f"archive root years={year_idxs[:5]}... n={len(year_idxs)}")
298
+ for y in year_idxs:
299
+ for m in range(1, 13):
300
+ for p in (1, 2): # Κύριο Μέρος / Παραρτήματα
301
+ exp = f"{y}.{m}.{p}"
302
+ url = f"{archive}&Expand={exp}&Seq=1"
303
+ r, _ = try_get(url)
304
+ if not hasattr(r, "status_code") or r.status_code != 200 or not r.content:
305
+ continue
306
+ found = extract_unids(r.text or "")
307
+ # Sometimes need deeper Expand=y.m.p.q
308
+ if not found:
309
+ deeper = set()
310
+ for m2 in EXPAND_RE.finditer(r.text or ""):
311
+ key = m2.group(1)
312
+ if key.startswith(exp + "."):
313
+ deeper.add(key)
314
+ for key in sorted(deeper)[:8]:
315
+ r2, _ = try_get(f"{archive}&Expand={key}&Seq=1")
316
+ if hasattr(r2, "status_code") and r2.status_code == 200 and r2.content:
317
+ found.extend(extract_unids(r2.text or ""))
318
+ before = len(unids)
319
+ unids.update(found)
320
+ if found:
321
+ log.info("archive Expand=%s +%s total_unids=%s", exp, len(unids) - before, len(unids))
322
+ log.info("archive year_idx=%s total_unids=%s", y, len(unids))
323
+ # Previous-years index form
324
+ prev = f"{GAZETTE_NSF}/dmlprevious_Archive_gr/dmlprevious_Archive_gr?OpenForm"
325
+ r, _ = try_get(prev)
326
+ if hasattr(r, "status_code") and r.status_code == 200 and r.content:
327
+ unids.update(extract_unids(r.text or ""))
328
+ for m in re.finditer(r'href=["\']([^"\']+)["\']', r.text or ""):
329
+ href = urljoin(prev, htmlmod.unescape(m.group(1)))
330
+ if "gazette.nsf" in href and is_official(href) and not SKIP_PATH_RE.search(href):
331
+ if "OpenDocument" in href or "OpenForm" in href or "Expand=" in href:
332
+ r2, _ = try_get(href)
333
+ if hasattr(r2, "status_code") and r2.status_code == 200 and r2.content:
334
+ unids.update(extract_unids(r2.text or ""))
335
+ notes.append(f"archive_unids={len(unids)}")
336
+ return unids
337
+
338
+
339
+ def discover_cdx_pdfs(notes: list[str]) -> list[dict]:
340
+ """Wayback CDX for official GPO PDF attachments."""
341
+ patterns = [
342
+ "www.mof.gov.cy/mof/gpo/gazette.nsf/*$file*",
343
+ "www.mof.gov.cy/mof/gpo/gazette.nsf/*.pdf",
344
+ "www.mof.gov.cy/mof/gpo/gazette.nsf/*",
345
+ ]
346
+ out = []
347
+ seen = set()
348
+ for pat in patterns:
349
+ try:
350
+ rows = search_wayback_machine(
351
+ pat,
352
+ limit=MAX_CDX if "file" in pat or "pdf" in pat else 800,
353
+ collapse="digest",
354
+ match_type=None,
355
+ extra_filters=["mimetype:application/pdf"],
356
+ )
357
+ except Exception as exc:
358
+ notes.append(f"cdx {pat} ERROR {exc}")
359
+ continue
360
+ n = 0
361
+ for rec in rows:
362
+ orig = rec.get("original") or ""
363
+ if not is_official(orig):
364
+ continue
365
+ if ".pdf" not in orig.lower() and "$file" not in orig.lower() and "$FILE" not in orig:
366
+ continue
367
+ if CYLAW_RE.search(orig) or SKIP_PATH_RE.search(orig):
368
+ continue
369
+ key = orig.lower()
370
+ if key in seen:
371
+ continue
372
+ seen.add(key)
373
+ out.append(rec)
374
+ n += 1
375
+ notes.append(f"cdx {pat} pdfish={n} raw={len(rows)}")
376
+ log.info("cdx %s pdfish=%s", pat, n)
377
+ time.sleep(2.0)
378
+ return out
379
+
380
+
381
+ def issue_pdfs_from_unid(unid: str) -> list[str]:
382
+ page = f"{GAZETTE_NSF}/All/{unid}?OpenDocument"
383
+ r, _ = try_get(page)
384
+ if not hasattr(r, "status_code") or r.status_code != 200 or not r.content:
385
+ return []
386
+ return extract_pdf_hrefs(page, r.text or "")
387
+
388
+
389
+ def fetch_pdf_bytes(url: str, wayback_ts: str | None = None) -> tuple[bytes, str, str]:
390
+ """Return (bytes, resolved_url, method)."""
391
+ # Live first
392
+ r, _ = try_get(url, accept="application/pdf, */*")
393
+ if hasattr(r, "status_code") and r.status_code == 200 and r.content and r.content[:4] == b"%PDF":
394
+ return r.content, url, "live_gpo"
395
+ # URL-encode spaces if needed
396
+ if " " in url:
397
+ parts = url.split("/$file/", 1)
398
+ if len(parts) == 2:
399
+ enc = parts[0] + "/$file/" + quote(parts[1], safe="/()")
400
+ r2, _ = try_get(enc, accept="application/pdf, */*")
401
+ if hasattr(r2, "status_code") and r2.status_code == 200 and r2.content and r2.content[:4] == b"%PDF":
402
+ return r2.content, enc, "live_gpo_encoded"
403
+ # Wayback
404
+ try:
405
+ wb = get_wayback_content(url, timestamp=wayback_ts)
406
+ except Exception:
407
+ wb = {"status": "error"}
408
+ if wb.get("status") in (None, "ok", "success") or wb.get("content") or wb.get("body"):
409
+ body = wb.get("content") or wb.get("body") or b""
410
+ if isinstance(body, str):
411
+ body = body.encode("utf-8", "replace")
412
+ if body[:4] == b"%PDF":
413
+ return body, wb.get("wayback_url") or url, "wayback"
414
+ # Direct wayback id_ URL if we have ts
415
+ if wayback_ts:
416
+ wb_url = f"https://web.archive.org/web/{wayback_ts}id_/{url}"
417
+ try:
418
+ time.sleep(1.0)
419
+ r3 = get_session(UA).get(wb_url, timeout=(20, 120), headers={"User-Agent": UA})
420
+ if r3.status_code == 200 and r3.content[:4] == b"%PDF":
421
+ return r3.content, wb_url, "wayback_direct"
422
+ except Exception:
423
+ pass
424
+ return b"", url, "fail"
425
+
426
+
427
+ def save_pdf_instrument(url: str, raw: bytes, method: str, done: set[str]) -> str:
428
+ ident = pdf_ident(url)
429
+ rid = slug_id(CC, ident)
430
+ if rid in done:
431
+ return "skip"
432
+ text = pdf_bytes_to_text(raw, timeout=240)
433
+ if not text or len(text) < 80:
434
+ log_failure(CC, {"identifier": ident, "source_url": url, "status": "failed", "reason": "pdf_empty_text"})
435
+ return "fail"
436
+ fname = unquote(url.split("/")[-1])
437
+ date = date_from_name(fname) or date_from_name(text[:500])
438
+ title = title_from_pdf_url(url, text)
439
+ docs = split_cy_articles(text, rid, url, date)
440
+ rec = base_record(
441
+ cc=CC,
442
+ country=COUNTRY,
443
+ language="el",
444
+ ident=ident,
445
+ title=title,
446
+ text=text,
447
+ source_url=url,
448
+ source_type=SOURCE_TYPE,
449
+ license_text=LICENSE,
450
+ collector="cy-gpo-pdf",
451
+ eli=None,
452
+ date=date,
453
+ official_identifier=ident,
454
+ document_type="gazette_pdf",
455
+ law_status="unknown",
456
+ is_current=None,
457
+ documents=docs if docs else None,
458
+ extra_meta={
459
+ "discovery": {"method": method},
460
+ "text_extraction": {"backend": "pdftotext", "source": "official_gpo_pdf"},
461
+ "pdf_bytes": len(raw),
462
+ },
463
+ )
464
+ write_instrument(CC, rec)
465
+ done.add(rid)
466
+ return "ok"
467
+
468
+
469
+
470
+ def existing_source_urls(cc: str) -> set[str]:
471
+ """URLs already stored for cross-slug dedup with cy_fetch_discovery."""
472
+ out: set[str] = set()
473
+ d = ROOT / cc / "instruments"
474
+ if not d.exists():
475
  return out
476
+ for path in d.glob("*.json"):
477
  try:
478
+ rec = json.loads(path.read_text(encoding="utf-8"))
479
  except Exception:
480
  continue
481
+ for key in ("source_url", "canonical_law_url", "original_url"):
482
+ u = (rec.get(key) or "").strip()
483
+ if u:
484
+ out.add(u.split("?")[0].lower())
485
+ meta = rec.get("metadata") or {}
486
+ if isinstance(meta, dict):
487
+ for key in ("canonical_law_url", "original_url"):
488
+ u = (meta.get(key) or "").strip()
489
+ if u:
490
+ out.add(u.split("?")[0].lower())
491
+ disc = meta.get("discovery") or {}
492
+ if isinstance(disc, dict):
493
+ u = (disc.get("original_url") or "").strip()
494
+ if u:
495
+ out.add(u.split("?")[0].lower())
496
+ ef = meta.get("extra_fields") or rec.get("extra_fields") or {}
497
+ if isinstance(ef, dict):
498
+ u = (ef.get("canonical_law_url") or "").strip()
499
+ if u:
500
+ out.add(u.split("?")[0].lower())
501
  return out
502
 
503
 
504
+ def load_cdx_discovery_file() -> list[tuple[str, str | None]]:
505
+ path = ROOT / CC / "raw" / "cdx_discovery.jsonl"
506
+ out: list[tuple[str, str | None]] = []
507
+ if not path.exists():
508
+ return out
509
+ seen = set()
510
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
511
+ line = line.strip()
512
+ if not line:
513
+ continue
514
  try:
515
+ rec = json.loads(line)
516
+ except Exception:
517
+ continue
518
+ url = (rec.get("original") or rec.get("url") or "").strip()
519
+ if not url or not is_official(url):
520
+ continue
521
+ low = url.lower()
522
+ if ".pdf" not in low and "$file" not in low:
523
+ continue
524
+ key = url.split("?")[0].lower()
525
+ if key in seen:
526
+ continue
527
+ seen.add(key)
528
+ out.append((url, rec.get("timestamp")))
529
+ return out
530
+
531
 
532
+ def main():
533
+ setup()
534
+ t0 = utcnow()
535
+ notes: list[str] = []
536
+ done = existing_ids(CC)
537
+ have_urls = existing_source_urls(CC)
538
+ ok = skip = fail = 0
539
+
540
+ log.info("=== CY GPO PDF harvest start existing=%s urls=%s ===", len(done), len(have_urls))
541
 
542
+ # --- Discovery: UNIDs from live site ---
543
+ unids: set[str] = set()
 
544
  try:
545
+ unids |= discover_section_unids(notes)
 
 
 
 
 
 
 
 
 
 
 
 
546
  except Exception as exc:
547
+ notes.append(f"section_discover ERROR {exc}")
548
+ log.exception("section_discover")
549
+ log.info("after sections unids=%s", len(unids))
550
  try:
551
+ unids |= discover_archive_unids(notes)
 
 
 
 
 
 
 
 
 
 
 
552
  except Exception as exc:
553
+ notes.append(f"archive_discover ERROR {exc}")
554
+ log.exception("archive_discover")
555
+ log.info("after archive unids=%s", len(unids))
556
 
557
+ # Resolve UNIDs → PDF URLs
558
+ pdf_jobs: list[tuple[str, str | None]] = [] # (url, wayback_ts)
559
+ seen_pdf = set()
560
+ for i, unid in enumerate(sorted(unids)):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
561
  try:
562
+ pdfs = issue_pdfs_from_unid(unid)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
563
  except Exception as exc:
564
+ log.warning("issue %s fail %s", unid, exc)
565
+ fail += 1
566
+ continue
567
+ for u in pdfs:
568
+ key = u.lower()
569
+ if key in seen_pdf:
570
+ continue
571
+ seen_pdf.add(key)
572
+ pdf_jobs.append((u, None))
573
+ if (i + 1) % 25 == 0:
574
+ log.info("resolved issues %s/%s pdfs=%s", i + 1, len(unids), len(pdf_jobs))
575
+
576
+ notes.append(f"live_unids={len(unids)} live_pdfs={len(pdf_jobs)}")
577
+
578
+ # --- Prior CDX discovery file ---
579
+ for url, ts in load_cdx_discovery_file():
580
+ key = url.split("?")[0].lower()
581
+ if key in seen_pdf:
582
+ continue
583
+ seen_pdf.add(key)
584
+ pdf_jobs.append((url, ts))
585
+ notes.append(f"after_cdx_file pdfs={len(pdf_jobs)}")
586
+
587
+ # --- CDX fallback PDFs ---
 
 
 
 
 
588
  try:
589
+ cdx_rows = discover_cdx_pdfs(notes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590
  except Exception as exc:
591
+ cdx_rows = []
592
+ notes.append(f"cdx ERROR {exc}")
593
+ for rec in cdx_rows:
594
+ orig = rec.get("original") or ""
595
+ key = orig.lower()
596
+ if key in seen_pdf:
597
+ continue
598
+ seen_pdf.add(key)
599
+ pdf_jobs.append((orig, rec.get("timestamp")))
 
 
 
 
 
 
 
 
 
 
 
 
600
 
601
+ discovered = len(pdf_jobs)
602
+ log.info("=== fetch phase discovered_pdfs=%s ===", discovered)
603
+ notes.append(f"discovered_pdfs={discovered}")
604
 
605
+ # Persist discovery list for resume/debug
606
+ disc_path = ROOT / CC / "raw" / "discovered_pdfs.txt"
607
+ disc_path.parent.mkdir(parents=True, exist_ok=True)
608
+ disc_path.write_text("\n".join(u for u, _ in pdf_jobs) + "\n", encoding="utf-8")
609
+
610
+ for i, (url, ts) in enumerate(pdf_jobs):
611
+ ident = pdf_ident(url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
612
  rid = slug_id(CC, ident)
613
+ url_key = url.split("?")[0].lower()
614
+ if rid in done or url_key in have_urls:
615
  skip += 1
616
  continue
617
+ try:
618
+ raw, resolved, method = fetch_pdf_bytes(url, wayback_ts=ts)
619
+ except Exception as exc:
620
+ fail += 1
621
+ log_failure(CC, {"identifier": ident, "source_url": url, "status": "failed", "reason": repr(exc)})
622
  continue
623
+ if not raw:
 
 
624
  fail += 1
625
+ log_failure(CC, {"identifier": ident, "source_url": url, "status": "failed", "reason": "pdf_fetch_fail"})
 
626
  continue
627
+ st = save_pdf_instrument(resolved, raw, method, done)
628
+ if st == "ok":
629
+ have_urls.add(url_key)
630
+ have_urls.add(resolved.split("?")[0].lower())
631
+ ok += st == "ok"
632
+ skip += st == "skip"
633
+ fail += st == "fail"
634
+ if (ok + fail) % 10 == 0 or i < 3:
635
+ log.info("progress i=%s/%s ok=%s skip=%s fail=%s last=%s", i + 1, discovered, ok, skip, fail, method)
636
+ if (ok + fail) % 50 == 0:
637
+ write_summary(
638
+ CC,
639
+ country=COUNTRY,
640
+ source="Cyprus Government Printing Office gazette PDFs",
641
+ source_urls=[
642
+ f"{GAZETTE_NSF}/officialgazette-el/officialgazette-el?OpenDocument",
643
+ f"{GAZETTE_NSF}/dmlgazette_archive_gr/dmlgazette_archive_gr?OpenForm",
644
+ ],
645
+ license_text=LICENSE,
646
+ discovered=discovered,
647
+ fetched=ok,
648
+ skipped=skip,
649
+ failed=fail,
650
+ coverage="catalog-backed incomplete",
651
+ notes="\n".join(notes[-40:]),
652
+ last_run=utcnow(),
653
+ )
654
+
655
+ # Also keep any useful HTML-only pages already present; do not re-scrape shallow seeds as instruments.
656
+ notes.append(
657
+ "GPO PDF harvest via live Domino archive/sections + Wayback CDX of official mof.gov.cy URLs. "
658
+ "cylaw.org unused. legislation.gov.cy NXDOMAIN."
659
+ )
660
+ write_summary(
661
+ CC,
662
+ country=COUNTRY,
663
+ source="Cyprus Government Printing Office gazette PDFs",
664
+ source_urls=[
665
+ f"{GAZETTE_NSF}/officialgazette-el/officialgazette-el?OpenDocument",
666
+ f"{GAZETTE_NSF}/dmlgazette_archive_gr/dmlgazette_archive_gr?OpenForm",
667
+ "https://www.gov.cy/en/service/episimi-efimerida-tis-dimokratias/",
668
+ ],
669
+ license_text=LICENSE,
670
+ discovered=discovered,
671
+ fetched=ok,
672
+ skipped=skip,
673
+ failed=fail,
674
+ coverage="catalog-backed incomplete",
675
+ notes="\n".join(notes),
676
+ last_run=utcnow(),
677
+ extra=f"started {t0} instruments_on_disk={len(existing_ids(CC))}",
678
+ )
679
+ log.info("done disc=%s ok=%s skip=%s fail=%s instruments=%s", discovered, ok, skip, fail, len(existing_ids(CC)))
680
 
681
 
682
  if __name__ == "__main__":
scrapers/common.py CHANGED
@@ -234,13 +234,11 @@ def xml_to_text(raw: str, skip_tags: Optional[set[str]] = None) -> str:
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\.\s*|str\.\s*|para(?:graph)?\.?|szakasz|"
238
- r"άρθρο|Άρθρο|ΑΡΘΡΟ)\s+"
239
- r"[\dIVXLCDMΑ-Ω]+[a-zA-ZΑ-Ωa-z]?)\b"
240
  )
241
 
242
 
243
-
244
  def split_articles(text: str, law_id: str, source_url: str, date: Optional[str] = None) -> list[dict]:
245
  if not text or len(text) < 40:
246
  return []
@@ -506,3 +504,23 @@ def iso_date(val: Optional[str]) -> Optional[str]:
506
  if m:
507
  return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"
508
  return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 []
 
504
  if m:
505
  return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"
506
  return None
507
+
508
+
509
+ def pdf_bytes_to_text(raw: bytes, timeout: int = 180) -> str:
510
+ """Extract text from PDF bytes via pdftotext. Empty on failure."""
511
+ import subprocess
512
+ if not raw or raw[:4] != b"%PDF":
513
+ return ""
514
+ try:
515
+ with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:
516
+ tmp.write(raw)
517
+ tmp.flush()
518
+ proc = subprocess.run(
519
+ ["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],
520
+ check=False, capture_output=True, timeout=timeout,
521
+ )
522
+ if proc.returncode == 0 and proc.stdout:
523
+ return proc.stdout.decode("utf-8", "replace").strip()
524
+ except Exception:
525
+ return ""
526
+ return ""