Datasets:
Refresh cyprus laws research snapshot (incomplete/catalog-backed; official source prevails; not legal advice)
Browse filesFiles changed (6)
- MANIFEST.md+20-8
- README.md+12-10
- data/articles.parquet+2-2
- data/laws.parquet+2-2
- scrapers/collect_cy.py+636-273
- scrapers/common.py+22-4
123456789# MANIFEST- generated_at: 2026-09-04T19:32:20Z- laws: 302- articles: 4398- files:- data/laws.parquet: 13048112 bytes- data/articles.parquet: 9669073 bytes- README.md: 1631 bytes123456789101112131415161718192021# ipfs_cyprus_laws manifestgenerated_utc: 2026-09-04T19:41:10Zcc: cyslug: cypruslaws_rows: 341articles_rows: 111laws_bytes: 9687597articles_bytes: 279292laws_sha256: 97e6df2b84f3ca611e23d8e91d8c942f1741c84307148d19faad09b5bfce6212articles_sha256: 345b8cd23246bb4d09a81a6b3e8c62b966ae747ca501be9ffec34303a17d9dc2laws_parquet: /workspace/legal-corpora-releases/cyprus/data/laws.parquetarticles_parquet: /workspace/legal-corpora-releases/cyprus/data/articles.parquetcompression: zstdcollector: scrapers/collect_cy.pysource: Cyprus Government Printing Office gazette (mof.gov.cy)coverage: CDX/Wayback expand research snapshot; quality_good>=400=340 short=1 junk=0snapshot_date: 2026-09-04uploaded: falsegaps:Method: cdx_parallel_expand + archive_fallbacks. Not complete. Official source prevails. Not legal advice.
12345672 unmodified lines1011121314155 unmodified lines2122232425262728292 unmodified lines323334353637383940414243444515 unmodified lines61626364---pretty_name: Laws of Cypruslicense: otherlicense_name: cyprus-gpo-gazettelanguage:- eltask_categories:2 unmodified lines- legal- law- cyprus- official-textssize_categories:- n<1K5 unmodified linesdata_files: data/articles.parquet---# Laws of CyprusResearch snapshot of official legislation collected from **GPO mof.gov.cy**.**Not legal advice.** Official gazettes / government portals prevail over this corpus.2 unmodified lines| Field | Value || --- | --- || Snapshot date | 2026-09-04 || Coverage | catalog-backed incomplete || Source | GPO mof.gov.cy || Collector | `scrapers/collect_cy.py` || Laws / instruments | 302 || Articles | 4398 || Language | el || Jurisdiction | Cyprus || License | `cyprus-gpo-gazette` |## Contents15 unmodified lines## NotesDeepen: GPO gazette PDFs via Wayback CDX (no cylaw) + cy_extract_articles. Not legal advice.12345672 unmodified lines10111213141516175 unmodified lines2324252627282930312 unmodified lines343536373839404142434445464715 unmodified lines63646566---pretty_name: Laws of Cyprus (GPO gazette)license: otherlicense_name: cyprus-gpo-officiallanguage:- eltask_categories:2 unmodified lines- legal- law- cyprus- gpo- gazette- official-textssize_categories:- n<1K5 unmodified linesdata_files: data/articles.parquet---# Laws of Cyprus (GPO gazette)Research snapshot of official legislation collected from **Cyprus Government Printing Office gazette (mof.gov.cy)**.**Not legal advice.** Official gazettes / government portals prevail over this corpus.2 unmodified lines| Field | Value || --- | --- || Snapshot date | 2026-09-04 || Coverage | CDX/Wayback expand research snapshot; quality_good>=400=340 short=1 junk=0 || Source | Cyprus Government Printing Office gazette (mof.gov.cy) || Collector | `scrapers/collect_cy.py` || Laws / instruments | 341 || Articles | 111 || Language | el || Jurisdiction | Cyprus || License | `cyprus-gpo-official` |## Contents15 unmodified lines## NotesMethod: cdx_parallel_expand + archive_fallbacks. Not complete. Official source prevails. Not legal advice.
123version https://git-lfs.github.com/spec/v1oid sha256:92692042d7ead4a887d448971284ebbdc9927cde1e2053650a5821d371b805f4size 9669073123version https://git-lfs.github.com/spec/v1oid sha256:345b8cd23246bb4d09a81a6b3e8c62b966ae747ca501be9ffec34303a17d9dc2size 279292
123version https://git-lfs.github.com/spec/v1oid sha256:0869c92729d15d1bbb3fae32f3feead651fdacecd7aa141a070073539dcd89cfsize 13048112123version https://git-lfs.github.com/spec/v1oid sha256:97e6df2b84f3ca611e23d8e91d8c942f1741c84307148d19faad09b5bfce6212size 9687597
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319#!/usr/bin/env python3"""Cyprus: official GPO gazette (mof.gov.cy). PDF body extraction. Not cylaw.org."""from __future__ import annotationsimport io, json, logging, os, re, sys, timefrom pathlib import Pathfrom urllib.parse import urljoin, unquotesys.path.insert(0, str(Path(__file__).resolve().parent))from common import *import archive_fallbacks as afCC, COUNTRY, SOURCE_TYPE = "cy", "Cyprus", "gpo_gazette"LICENSE = "Official Gazette of the Republic of Cyprus, Government Printing Office (mof.gov.cy/gpo). cylaw.org is unofficial and is NOT used."UA = DEFAULT_UA + " source=https://www.mof.gov.cy/mof/gpo/"log = logging.getLogger("cy")ASSET_RE = re.compile(r"\.(css|js|png|jpe?g|gif|svg|ico|woff2?|ttf|map)(\?|$)", re.I)def setup():ensure_dirs(CC)logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",handlers=[logging.FileHandler(ROOT / CC / "logs" / "collector.log", encoding="utf-8"),logging.StreamHandler(sys.stdout)])def known_fail_keys() -> set[str]:"""Skip identifiers / URL keys that already failed empty extracts this session history."""out = set()fp = ROOT / CC / "failures.jsonl"if not fp.exists():return outfor line in fp.open(encoding="utf-8"):try:d = json.loads(line)except Exception:continueident = str(d.get("identifier") or "")url = str(d.get("source_url") or "")if ident:out.add(ident.lower())if url:out.add(unquote(url).lower())return outdef try_get(url, verify_first=True):last = Noneorder = (True, False) if verify_first else (False, True)for verify in order:try:time.sleep(0.35)r = get_session(UA).get(url, timeout=(5, 15), verify=verify,headers={"User-Agent": UA, "Accept": "text/html, application/pdf, */*"})return r, verifyexcept Exception as exc:last = excreturn last, Nonedef pdf_to_text(data: bytes) -> str:"""Extract PDF text; prefer pdfplumber (ipfs_datasets_py IntegratedPDFProcessor path)."""# 1) pdfplumber — same primary backend as IntegratedPDFProcessor._extract_text_from_pdftry:import pdfplumberwith pdfplumber.open(io.BytesIO(data)) as pdf:parts = []for page in pdf.pages[:120]:try:parts.append(page.extract_text() or "")except Exception:continuetext = "\n".join(parts)text = re.sub(r"[ \t]+", " ", text)text = re.sub(r"\n{3,}", "\n\n", text).strip()if len(text) >= 40:return textexcept Exception as exc:log.info("pdfplumber fail: %s", exc)# 2) pypdf fallbacktry:from pypdf import PdfReaderreader = PdfReader(io.BytesIO(data))parts = []for page in reader.pages[:120]:try:parts.append(page.extract_text() or "")except Exception:continuetext = "\n".join(parts)text = re.sub(r"[ \t]+", " ", text)text = re.sub(r"\n{3,}", "\n\n", text)return text.strip()except Exception as exc:log.info("pdf extract fail: %s", exc)return ""def is_gazette_pdf_url(url: str) -> bool:u = (url or "").lower()if "cylaw.org" in u:return Falseif ASSET_RE.search(u):return Falseuq = unquote(u)if ("$file/" in uq or "%24file/" in u) and (uq.rstrip().endswith(".pdf") or ".pdf" in uq):if "mof.gov.cy" in u and "gpo" in u:return Trueif uq.rstrip().endswith(".pdf") and "mof.gov.cy" in u and "gpo" in u:return Truereturn Falsedef fetch_pdf(url: str, ts: str = "", *, prefer_wayback: bool = False) -> tuple[str, str, str]:"""Return (text, source_url, kind). When CDX ts known, try Wayback first to avoid live hangs."""def _live():r, verify = try_get(url, verify_first=False)if hasattr(r, "status_code") and r.status_code == 200 and r.content and r.content[:5] == b"%PDF-":text = pdf_to_text(r.content)if len(text) >= 80:return text, url, "pdf_live"return Nonedef _wb(ts_in: str):try:t = ts_inu = urlif not t:hits = af.search_wayback_machine(u, limit=1, collapse="")if hits:t = hits[0].get("timestamp") or ""u = hits[0].get("original") or uif not t:return Nonew = af.get_wayback_content(u, timestamp=t)if w.get("status") == "success":content = w.get("content")if isinstance(content, bytes) and content[:5] == b"%PDF-":text = pdf_to_text(content)if len(text) >= 80:return text, w.get("url") or u, "pdf_wayback"except Exception as exc:log.info("wayback pdf %s: %s", url[-50:], exc)return None# Live mof.gov.cy often hangs; when CDX ts is known, Wayback-only.if prefer_wayback and ts:got = _wb(ts)if got:return gotreturn "", url, "none"for fn in (_live, _wb):got = fn(ts) if fn is _wb else _live()if got:return gotreturn "", url, "none"def cdx_pdf_candidates(limit: int = 400) -> list[tuple[str, str]]:"""Return list of (url, timestamp) for official GPO gazette PDFs via Wayback CDX."""out, seen = [], set()# Direct CDX with mime filter — more reliable than generic helper for Domino $file PDFsimport requestsparams = {"url": "www.mof.gov.cy/mof/gpo/gazette.nsf/*","output": "json","fl": "timestamp,original,mimetype,statuscode","filter": ["mimetype:application/pdf", "statuscode:200"],"collapse": "urlkey","limit": str(limit),}try:import jsonq = [("url", "www.mof.gov.cy/mof/gpo/gazette.nsf/*"),("output", "json"),("fl", "timestamp,original,mimetype,statuscode"),("filter", "mimetype:application/pdf"),("filter", "statuscode:200"),("collapse", "urlkey"),("limit", str(limit)),]last = Nonefor attempt in range(1, 5):time.sleep(0.6 * attempt)r = requests.get("https://web.archive.org/cdx/search/cdx", params=q, timeout=(20, 120),headers={"User-Agent": UA})last = rif r.status_code == 200 and r.content and r.content[:1] == b"[":rows = json.loads(r.content)for row in rows[1:]:ts, orig = row[0], row[1]if not is_gazette_pdf_url(orig):continuekey = unquote(orig).lower()if key in seen:continueseen.add(key)out.append((orig, ts))log.info("cdx mime-pdf unique=%s", len(out))breaklog.info("cdx attempt %s HTTP %s", attempt, getattr(r, "status_code", "?"))time.sleep(2 * attempt)else:log.info("cdx direct exhausted last=%s", getattr(last, "status_code", last))except Exception as exc:log.info("cdx direct fail: %s", exc)if len(out) < 20:# fallback via helper + $file filtertry:hits = af.search_wayback_machine("www.mof.gov.cy/mof/gpo/gazette.nsf/*", limit=limit, match_type="prefix", collapse="urlkey")for h in hits or []:u = (h.get("original") or "").strip()if not is_gazette_pdf_url(u):continuekey = unquote(u).lower()if key in seen:continueseen.add(key)out.append((u, h.get("timestamp") or ""))log.info("cdx helper pdf unique=%s", len(out))except Exception as exc:log.info("cdx helper fail: %s", exc)out.sort(key=lambda x: x[1] or "", reverse=True)return outdef main():setup(); t0 = utcnow()max_new = int(os.environ.get("MAX_NEW", "0") or 0)max_seconds = int(os.environ.get("MAX_SECONDS", "0") or 0)t_start = time.time()notes = ["PDF-focused CDX of official GPO gazette.nsf $file URLs. cylaw.org not used."]cands = cdx_pdf_candidates(int(os.environ.get("MAX_CATALOG", "400") or 400))# Also scrape live listing pages for any $file PDF hrefsseeds = ["https://www.mof.gov.cy/mof/gpo/gazette.nsf/dmlgaz_NEW_gr/dmlgaz_NEW_gr?OpenDocument","https://www.mof.gov.cy/mof/gpo/gazette.nsf/dmlgaz_app_gr/dmlgaz_app_gr?OpenDocument","https://www.mof.gov.cy/mof/gpo/gazette.nsf/dmlgazette_archive_gr/dmlgazette_archive_gr?OpenForm","https://www.mof.gov.cy/mof/gpo/gazette.nsf/officialgazette-el/officialgazette-el?OpenDocument",]seen = {unquote(u).lower() for u, _ in cands}for url in seeds:r, verify = try_get(url, verify_first=False)if not hasattr(r, "status_code"):notes.append(f"seed {url} ERROR {r}")continuenotes.append(f"seed {url} -> HTTP {r.status_code} bytes={len(r.content or b'')} verify={verify}")if r.status_code == 200 and r.content:for href in re.findall(r'href=["\']([^"\']+)["\']', r.text, flags=re.I):href = urljoin(url, href)if is_gazette_pdf_url(href) and unquote(href).lower() not in seen:seen.add(unquote(href).lower())cands.append((href, ""))log.info("pdf candidates %s", len(cands))done = existing_ids(CC); ok = skip = fail = 0known_fail = known_fail_keys()log.info("known_fail keys=%s", len(known_fail))for href, ts in cands:if max_new and ok >= max_new:breakif max_seconds and (time.time() - t_start) > max_seconds:breakident = re.sub(r"^https?://", "", href)# Prefer filename as stable id when Domino $file presentm = re.search(r"\$file/([^/?#]+)", href, re.I)if m:ident = "gpo-pdf-" + unquote(m.group(1))rid = slug_id(CC, ident)if rid in done:skip += 1continueif ident.lower() in known_fail or unquote(href).lower() in known_fail:skip += 1continuelog.info("try %s ts=%s", ident[:80], (ts or "")[:14])text, src, kind = fetch_pdf(href, ts, prefer_wayback=bool(ts))if len(text) < 80:fail += 1log_failure(CC, {"identifier": ident, "source_url": href, "status": "failed", "reason": f"empty_{kind}"})log.info("fail %s kind=%s", ident[:70], kind)continuetitle = unquote(m.group(1)) if m else identfor line in text.splitlines():if len(line.strip()) > 12:title = line.strip()[:240]breakrec = base_record(cc=CC, country=COUNTRY, language="el", ident=ident, title=title, text=text,source_url=src, source_type=SOURCE_TYPE, license_text=LICENSE,collector="cy-gpo-gazette-pdf", eli=None, date=None, official_identifier=ident,document_type="gazette_pdf", law_status="unknown", is_current=None,documents=[], # whole-issue PDFs; no honest per-article split from structureextra_meta={"discovery": {"backend": kind, "original_url": href, "wayback_ts": ts,"article_note": "whole_issue_pdf_articles_0"}},)write_instrument(CC, rec); ok += 1; done.add(rid)log.info("ok %s kind=%s chars=%s", rid[:70], kind, len(text))if ok and ok % 10 == 0:write_summary(CC, country=COUNTRY, source="Cyprus GPO gazette PDFs",source_urls=["https://www.mof.gov.cy/mof/gpo/gazette.nsf/"],license_text=LICENSE, discovered=len(cands), fetched=ok, skipped=skip, failed=fail,coverage="shard", notes="\n".join(notes), last_run=utcnow())if not ok:notes.append("Blocker: few/no extractable PDF bodies this run. legislation.gov.cy NXDOMAIN; ""GPO TLS incomplete chain; cylaw.org forbidden. Used Wayback CDX of official $file PDFs.")write_summary(CC, country=COUNTRY, source="Cyprus Government Printing Office gazette PDFs",source_urls=["https://www.mof.gov.cy/mof/gpo/gazette.nsf/officialgazette-el/officialgazette-el?OpenDocument","https://www.gov.cy/en/service/episimi-efimerida-tis-dimokratias/"],license_text=LICENSE, discovered=len(cands), fetched=ok, skipped=skip, failed=fail,coverage="catalog-backed incomplete", notes="\n".join(notes), last_run=utcnow(), extra=f"started {t0}")log.info("done disc=%s ok=%s fail=%s skip=%s", len(cands), ok, fail, skip)if __name__ == "__main__":123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682#!/usr/bin/env python3"""Cyprus: official GPO gazette PDFs (mof.gov.cy). No cylaw.org.Discovery:1) Live Domino section views (Κύριο Μέρος / Παραρτήματα)2) Archive outline Expand=year.month.part (2004–present)3) Per-issue OpenDocument pages → $file PDF attachments4) Wayback CDX of official GPO $file / gazette.nsf URLs (fallback)PDFs extracted via pdftotext (common.pdf_bytes_to_text). TLS verify may failon incomplete GPO chain from this network — official host still used."""from __future__ import annotationsimport html as htmlmodimport jsonimport loggingimport reimport sysimport timeimport warningsfrom pathlib import Pathfrom urllib.parse import urljoin, unquote, quotesys.path.insert(0, str(Path(__file__).resolve().parent))from common import * # noqa: F401,F403from archive_fallbacks import search_wayback_machine, get_wayback_contentwarnings.filterwarnings("ignore", message="Unverified HTTPS request")CC, COUNTRY, SOURCE_TYPE = "cy", "Cyprus", "gpo_gazette"LICENSE = ("Official Gazette of the Republic of Cyprus, Government Printing Office ""(mof.gov.cy/gpo). cylaw.org is unofficial and is NOT used.")UA = DEFAULT_UA + " source=https://www.mof.gov.cy/mof/gpo/"BASE = "https://www.mof.gov.cy"GAZETTE_NSF = f"{BASE}/mof/gpo/gazette.nsf"log = logging.getLogger("cy")# Domino All/{UNID}?OpenDocumentUNID_RE = re.compile(r"/mof/gpo/gazette\.nsf/All/([0-9A-Fa-f]{32})\?OpenDocument", re.I)# $file PDF hrefs (spaces in filenames are common)FILE_RE = re.compile(r"""(?:href|src)\s*=\s*["']([^"']*\$[Ff][Ii][Ll][Ee]/[^"']+\.pdf)["']""",re.I,)# Expand=Y.M.P outline linksEXPAND_RE = re.compile(r"dmlgazette_archive_gr\?OpenForm[^\"']*Expand=([0-9]+(?:\.[0-9]+){0,3})",re.I,)# Skip chrome / policy pagesSKIP_PATH_RE = re.compile(r"(accessibility|privacypolicy|gazetteinfo|favicon|settings\.css|"r"officialgazette-(?:el|en)|dmlgaz_NEW_|dmlgaz_app_|dmlprevious|"r"dmlgazette_archive|dmlgaz_view_sections|SearchResults|"r"font-awesome|icon-font|layers\.css|navigation\.css)",re.I,)CYLAW_RE = re.compile(r"cylaw\.org", re.I)# Greek gazette instrument markers inside PDF textCY_ART_RE = re.compile(r"(?im)^\s*((?:Άρθρο|Αρθρο|Aρθρο|Άρθρον|Αριθμός|Aριθμός|Αρ\.)\s+"r"[\dIVXLCDM]+[A-Za-zΑ-Ωα-ω΄']*)\b")# How far back to walk the archive outline (Expand index 1 = newest year)MAX_YEAR_EXPAND = 23 # ~2004–2026MAX_CDX = 2500FETCH_SLEEP = 0.35def setup():ensure_dirs(CC)logging.basicConfig(level=logging.INFO,format="%(asctime)s %(levelname)s %(message)s",handlers=[logging.FileHandler(ROOT / CC / "logs" / "collector.log", encoding="utf-8"),logging.StreamHandler(sys.stdout),],force=True,)def try_get(url: str, *, accept: str = "text/html, application/pdf, */*", binary_ok: bool = True):"""GET official GPO; retry with verify=False (incomplete cert chain)."""last = Nonefor verify in (True, False):try:time.sleep(FETCH_SLEEP)r = get_session(UA).get(url,timeout=(20, 120),verify=verify,headers={"User-Agent": UA, "Accept": accept},allow_redirects=True,)if r.status_code == 200 and (binary_ok or r.content):return r, verifylast = rif r.status_code in (404, 410):return r, verifyexcept Exception as exc:last = excreturn last, Nonedef is_official(url: str) -> bool:if not url or CYLAW_RE.search(url):return Falseu = url.lower()return "mof.gov.cy" in u and ("/gpo/" in u or "gazette.nsf" in u or "gpo.nsf" in u)def extract_unids(html: str) -> list[str]:return list(dict.fromkeys(m.group(1).upper() for m in UNID_RE.finditer(html or "")))def extract_pdf_hrefs(page_url: str, html: str) -> list[str]:out = []seen = set()for m in FILE_RE.finditer(html or ""):href = htmlmod.unescape(m.group(1).strip())full = urljoin(page_url, href)if not is_official(full):continueif SKIP_PATH_RE.search(full):continueif full.lower() in seen:continueseen.add(full.lower())out.append(full)# also bare $file paths without href=for m in re.finditer(r"(/mof/gpo/gazette\.nsf/[0-9A-Fa-f]{32}/\$file/[^\s\"'<>]+\.pdf)", html or "", re.I):full = urljoin(BASE, htmlmod.unescape(m.group(1)))if full.lower() not in seen and is_official(full):seen.add(full.lower())out.append(full)return outdef split_cy_articles(text: str, law_id: str, source_url: str, date: str | None) -> list[dict]:if not text or len(text) < 40:return []matches = list(CY_ART_RE.finditer(text))if len(matches) < 2:# fall back to common splitter (may still yield 0)return split_articles(text, law_id, source_url, date)docs = []for i, m in enumerate(matches):start = m.start()end = matches[i + 1].start() if i + 1 < len(matches) else len(text)chunk = text[start:end].strip()if len(chunk) < 30:continuenum = re.sub(r"\s+", " ", m.group(1)).strip()aid = re.sub(r"[^a-z0-9]+", "-", num.lower()).strip("-") or f"n{i}"heading = chunk.split("\n", 1)[0][:200]docs.append({"id": f"{law_id}-{aid}"[:180],"title": heading,"text": chunk,"date_filed": date,"document_number": num,"source_url": source_url,"record_type": "article","article_number": num,"law_identifier": law_id,"metadata": {"text_extraction": {"source": "official", "backend": "pdftotext"}},})if len(docs) >= 4000:breakreturn docsdef title_from_pdf_url(url: str, text: str) -> str:name = unquote(url.split("/")[-1])name = re.sub(r"\.pdf$", "", name, flags=re.I).strip()name = re.sub(r"\s+", " ", name)if text:# first non-empty line that looks like gazette headerfor line in text.splitlines()[:40]:line = line.strip()if len(line) > 12 and re.search(r"(ΕΦΗΜΕΡΙΔΑ|Επίσημη|PARARTIMA|ΠΑΡΑΡΤΗΜΑ|ΚΥΡΙΟ|KYRIO)", line, re.I):return line[:240]if re.match(r"^Αριθμός\s+\d+", line, re.I) or re.match(r"^Aριθμός\s+\d+", line):return (name + " — " + line)[:240]return name[:240] or urldef date_from_name(name: str) -> str | None:# e.g. "5885 4 9 2026 KYRIO MEROS..." or "4597Α 6 10 2023 PARARTIMA..."m = re.search(r"\b(\d{1,2})\s+(\d{1,2})\s+(20\d{2})\b", name)if m:d, mo, y = int(m.group(1)), int(m.group(2)), int(m.group(3))if 1 <= mo <= 12 and 1 <= d <= 31:return f"{y:04d}-{mo:02d}-{d:02d}"m = re.search(r"\b(20\d{2})[-_/](\d{1,2})[-_/](\d{1,2})\b", name)if m:return f"{int(m.group(1)):04d}-{int(m.group(2)):02d}-{int(m.group(3)):02d}"return Nonedef pdf_ident(url: str) -> str:"""Stable identifier from UNID + filename."""m = re.search(r"/gazette\.nsf/(?:All/)?([0-9A-Fa-f]{32})/", url, re.I)unid = (m.group(1).upper() if m else "nouid")fname = unquote(url.split("/")[-1])fname = re.sub(r"\.pdf$", "", fname, flags=re.I)fname = re.sub(r"\s+", "_", fname.strip())return f"gpo-{unid}-{fname}"[:160]def discover_section_unids(notes: list[str]) -> set[str]:unids: set[str] = set()# Main + appendix landing pages → section linksseeds = [f"{GAZETTE_NSF}/dmlgaz_NEW_gr/dmlgaz_NEW_gr?OpenDocument",f"{GAZETTE_NSF}/dmlgaz_NEW_en/dmlgaz_NEW_en?OpenDocument",f"{GAZETTE_NSF}/dmlgaz_app_gr/dmlgaz_app_gr?OpenDocument",f"{GAZETTE_NSF}/dmlgaz_app_en/dmlgaz_app_en?OpenDocument",f"{GAZETTE_NSF}/officialgazette-el/officialgazette-el?OpenDocument",]section_urls = set()for url in seeds:r, verify = try_get(url)if not hasattr(r, "status_code"):notes.append(f"seed {url} ERROR {r}")continuenotes.append(f"seed {url} -> HTTP {r.status_code} bytes={len(r.content or b'')} verify={verify}")if r.status_code != 200 or not r.content:continuehtml = r.text or ""unids.update(extract_unids(html))for m in re.finditer(r'href=["\']([^"\']*dmlgaz_view_sections[^"\']+)["\']', html, re.I):section_urls.add(urljoin(url, htmlmod.unescape(m.group(1))))for m in re.finditer(r'href=["\']([^"\']*view_sections[^"\']+)["\']', html, re.I):section_urls.add(urljoin(url, htmlmod.unescape(m.group(1))))# Explicit sectionNumber sweeps (main parts 1–3; appendices often reuse)for sec in range(1, 8):for cp in ("11", "21", "22", "12", "31", "32"):section_urls.add(f"{GAZETTE_NSF}/dmlgaz_view_sections_gr/dmlgaz_view_sections_gr"f"?OpenDocument&OpenView&Count=1000&cp={cp}§ionNumber={sec}")section_urls.add(f"{GAZETTE_NSF}/dmlgaz_view_sections_gr/dmlgaz_view_sections_gr"f"?OpenDocument§ionNumber={sec}&cp={cp}")# Prefer Count=1000 OpenView URLs; skip redundant Start pagination when# Domino returns a small page (typical ~20) — use archive Expand for depth.prefer = [u for u in sorted(section_urls) if "Count=1000" in u or "OpenView" in u]rest = [u for u in sorted(section_urls) if u not in prefer]for url in prefer + rest[:20]:if not is_official(url):continuer, _ = try_get(url)if not hasattr(r, "status_code") or r.status_code != 200 or not r.content:continuefound = extract_unids(r.text or "")before = len(unids)unids.update(found)# Only paginate when the view clearly has a large batchif len(found) >= 80 and ("OpenView" in url or "Count=" in url):for start in (31, 61, 91, 121, 151, 181, 211, 241, 271, 301):page = urlif "Start=" in page:page = re.sub(r"Start=\d+", f"Start={start}", page)else:page = page + ("&" if "?" in page else "?") + f"Start={start}"r2, _ = try_get(page)if not hasattr(r2, "status_code") or r2.status_code != 200 or not r2.content:breakmore = extract_unids(r2.text or "")new_n = len(set(more) - unids)unids.update(more)if new_n == 0:breaklog.info("section +%s total_unids=%s url=%s", len(unids) - before, len(unids), url[-80:])return unidsdef discover_archive_unids(notes: list[str]) -> set[str]:"""Walk Domino outline Expand=year[.month[.part]]."""unids: set[str] = set()archive = f"{GAZETTE_NSF}/dmlgazette_archive_gr/dmlgazette_archive_gr?OpenForm&Start=1&Count=9999"# First fetch root to learn year expand indicesr, _ = try_get(archive)year_idxs = list(range(1, MAX_YEAR_EXPAND + 1))if hasattr(r, "status_code") and r.status_code == 200 and r.content:found_exp = {int(m.group(1).split(".")[0]) for m in EXPAND_RE.finditer(r.text or "") if "." not in m.group(1)}if found_exp:year_idxs = sorted(found_exp)[:MAX_YEAR_EXPAND]notes.append(f"archive root years={year_idxs[:5]}... n={len(year_idxs)}")for y in year_idxs:for m in range(1, 13):for p in (1, 2): # Κύριο Μέρος / Παραρτήματαexp = f"{y}.{m}.{p}"url = f"{archive}&Expand={exp}&Seq=1"r, _ = try_get(url)if not hasattr(r, "status_code") or r.status_code != 200 or not r.content:continuefound = extract_unids(r.text or "")# Sometimes need deeper Expand=y.m.p.qif not found:deeper = set()for m2 in EXPAND_RE.finditer(r.text or ""):key = m2.group(1)if key.startswith(exp + "."):deeper.add(key)for key in sorted(deeper)[:8]:r2, _ = try_get(f"{archive}&Expand={key}&Seq=1")if hasattr(r2, "status_code") and r2.status_code == 200 and r2.content:found.extend(extract_unids(r2.text or ""))before = len(unids)unids.update(found)if found:log.info("archive Expand=%s +%s total_unids=%s", exp, len(unids) - before, len(unids))log.info("archive year_idx=%s total_unids=%s", y, len(unids))# Previous-years index formprev = f"{GAZETTE_NSF}/dmlprevious_Archive_gr/dmlprevious_Archive_gr?OpenForm"r, _ = try_get(prev)if hasattr(r, "status_code") and r.status_code == 200 and r.content:unids.update(extract_unids(r.text or ""))for m in re.finditer(r'href=["\']([^"\']+)["\']', r.text or ""):href = urljoin(prev, htmlmod.unescape(m.group(1)))if "gazette.nsf" in href and is_official(href) and not SKIP_PATH_RE.search(href):if "OpenDocument" in href or "OpenForm" in href or "Expand=" in href:r2, _ = try_get(href)if hasattr(r2, "status_code") and r2.status_code == 200 and r2.content:unids.update(extract_unids(r2.text or ""))notes.append(f"archive_unids={len(unids)}")return unidsdef discover_cdx_pdfs(notes: list[str]) -> list[dict]:"""Wayback CDX for official GPO PDF attachments."""patterns = ["www.mof.gov.cy/mof/gpo/gazette.nsf/*$file*","www.mof.gov.cy/mof/gpo/gazette.nsf/*.pdf","www.mof.gov.cy/mof/gpo/gazette.nsf/*",]out = []seen = set()for pat in patterns:try:rows = search_wayback_machine(pat,limit=MAX_CDX if "file" in pat or "pdf" in pat else 800,collapse="digest",match_type=None,extra_filters=["mimetype:application/pdf"],)except Exception as exc:notes.append(f"cdx {pat} ERROR {exc}")continuen = 0for rec in rows:orig = rec.get("original") or ""if not is_official(orig):continueif ".pdf" not in orig.lower() and "$file" not in orig.lower() and "$FILE" not in orig:continueif CYLAW_RE.search(orig) or SKIP_PATH_RE.search(orig):continuekey = orig.lower()if key in seen:continueseen.add(key)out.append(rec)n += 1notes.append(f"cdx {pat} pdfish={n} raw={len(rows)}")log.info("cdx %s pdfish=%s", pat, n)time.sleep(2.0)return outdef issue_pdfs_from_unid(unid: str) -> list[str]:page = f"{GAZETTE_NSF}/All/{unid}?OpenDocument"r, _ = try_get(page)if not hasattr(r, "status_code") or r.status_code != 200 or not r.content:return []return extract_pdf_hrefs(page, r.text or "")def fetch_pdf_bytes(url: str, wayback_ts: str | None = None) -> tuple[bytes, str, str]:"""Return (bytes, resolved_url, method)."""# Live firstr, _ = try_get(url, accept="application/pdf, */*")if hasattr(r, "status_code") and r.status_code == 200 and r.content and r.content[:4] == b"%PDF":return r.content, url, "live_gpo"# URL-encode spaces if neededif " " in url:parts = url.split("/$file/", 1)if len(parts) == 2:enc = parts[0] + "/$file/" + quote(parts[1], safe="/()")r2, _ = try_get(enc, accept="application/pdf, */*")if hasattr(r2, "status_code") and r2.status_code == 200 and r2.content and r2.content[:4] == b"%PDF":return r2.content, enc, "live_gpo_encoded"# Waybacktry:wb = get_wayback_content(url, timestamp=wayback_ts)except Exception:wb = {"status": "error"}if wb.get("status") in (None, "ok", "success") or wb.get("content") or wb.get("body"):body = wb.get("content") or wb.get("body") or b""if isinstance(body, str):body = body.encode("utf-8", "replace")if body[:4] == b"%PDF":return body, wb.get("wayback_url") or url, "wayback"# Direct wayback id_ URL if we have tsif wayback_ts:wb_url = f"https://web.archive.org/web/{wayback_ts}id_/{url}"try:time.sleep(1.0)r3 = get_session(UA).get(wb_url, timeout=(20, 120), headers={"User-Agent": UA})if r3.status_code == 200 and r3.content[:4] == b"%PDF":return r3.content, wb_url, "wayback_direct"except Exception:passreturn b"", url, "fail"def save_pdf_instrument(url: str, raw: bytes, method: str, done: set[str]) -> str:ident = pdf_ident(url)rid = slug_id(CC, ident)if rid in done:return "skip"text = pdf_bytes_to_text(raw, timeout=240)if not text or len(text) < 80:log_failure(CC, {"identifier": ident, "source_url": url, "status": "failed", "reason": "pdf_empty_text"})return "fail"fname = unquote(url.split("/")[-1])date = date_from_name(fname) or date_from_name(text[:500])title = title_from_pdf_url(url, text)docs = split_cy_articles(text, rid, url, date)rec = base_record(cc=CC,country=COUNTRY,language="el",ident=ident,title=title,text=text,source_url=url,source_type=SOURCE_TYPE,license_text=LICENSE,collector="cy-gpo-pdf",eli=None,date=date,official_identifier=ident,document_type="gazette_pdf",law_status="unknown",is_current=None,documents=docs if docs else None,extra_meta={"discovery": {"method": method},"text_extraction": {"backend": "pdftotext", "source": "official_gpo_pdf"},"pdf_bytes": len(raw),},)write_instrument(CC, rec)done.add(rid)return "ok"def existing_source_urls(cc: str) -> set[str]:"""URLs already stored for cross-slug dedup with cy_fetch_discovery."""out: set[str] = set()d = ROOT / cc / "instruments"if not d.exists():return outfor path in d.glob("*.json"):try:rec = json.loads(path.read_text(encoding="utf-8"))except Exception:continuefor key in ("source_url", "canonical_law_url", "original_url"):u = (rec.get(key) or "").strip()if u:out.add(u.split("?")[0].lower())meta = rec.get("metadata") or {}if isinstance(meta, dict):for key in ("canonical_law_url", "original_url"):u = (meta.get(key) or "").strip()if u:out.add(u.split("?")[0].lower())disc = meta.get("discovery") or {}if isinstance(disc, dict):u = (disc.get("original_url") or "").strip()if u:out.add(u.split("?")[0].lower())ef = meta.get("extra_fields") or rec.get("extra_fields") or {}if isinstance(ef, dict):u = (ef.get("canonical_law_url") or "").strip()if u:out.add(u.split("?")[0].lower())return outdef load_cdx_discovery_file() -> list[tuple[str, str | None]]:path = ROOT / CC / "raw" / "cdx_discovery.jsonl"out: list[tuple[str, str | None]] = []if not path.exists():return outseen = set()for line in path.read_text(encoding="utf-8", errors="replace").splitlines():line = line.strip()if not line:continuetry:rec = json.loads(line)except Exception:continueurl = (rec.get("original") or rec.get("url") or "").strip()if not url or not is_official(url):continuelow = url.lower()if ".pdf" not in low and "$file" not in low:continuekey = url.split("?")[0].lower()if key in seen:continueseen.add(key)out.append((url, rec.get("timestamp")))return outdef main():setup()t0 = utcnow()notes: list[str] = []done = existing_ids(CC)have_urls = existing_source_urls(CC)ok = skip = fail = 0log.info("=== CY GPO PDF harvest start existing=%s urls=%s ===", len(done), len(have_urls))# --- Discovery: UNIDs from live site ---unids: set[str] = set()try:unids |= discover_section_unids(notes)except Exception as exc:notes.append(f"section_discover ERROR {exc}")log.exception("section_discover")log.info("after sections unids=%s", len(unids))try:unids |= discover_archive_unids(notes)except Exception as exc:notes.append(f"archive_discover ERROR {exc}")log.exception("archive_discover")log.info("after archive unids=%s", len(unids))# Resolve UNIDs → PDF URLspdf_jobs: list[tuple[str, str | None]] = [] # (url, wayback_ts)seen_pdf = set()for i, unid in enumerate(sorted(unids)):try:pdfs = issue_pdfs_from_unid(unid)except Exception as exc:log.warning("issue %s fail %s", unid, exc)fail += 1continuefor u in pdfs:key = u.lower()if key in seen_pdf:continueseen_pdf.add(key)pdf_jobs.append((u, None))if (i + 1) % 25 == 0:log.info("resolved issues %s/%s pdfs=%s", i + 1, len(unids), len(pdf_jobs))notes.append(f"live_unids={len(unids)} live_pdfs={len(pdf_jobs)}")# --- Prior CDX discovery file ---for url, ts in load_cdx_discovery_file():key = url.split("?")[0].lower()if key in seen_pdf:continueseen_pdf.add(key)pdf_jobs.append((url, ts))notes.append(f"after_cdx_file pdfs={len(pdf_jobs)}")# --- CDX fallback PDFs ---try:cdx_rows = discover_cdx_pdfs(notes)except Exception as exc:cdx_rows = []notes.append(f"cdx ERROR {exc}")for rec in cdx_rows:orig = rec.get("original") or ""key = orig.lower()if key in seen_pdf:continueseen_pdf.add(key)pdf_jobs.append((orig, rec.get("timestamp")))discovered = len(pdf_jobs)log.info("=== fetch phase discovered_pdfs=%s ===", discovered)notes.append(f"discovered_pdfs={discovered}")# Persist discovery list for resume/debugdisc_path = ROOT / CC / "raw" / "discovered_pdfs.txt"disc_path.parent.mkdir(parents=True, exist_ok=True)disc_path.write_text("\n".join(u for u, _ in pdf_jobs) + "\n", encoding="utf-8")for i, (url, ts) in enumerate(pdf_jobs):ident = pdf_ident(url)rid = slug_id(CC, ident)url_key = url.split("?")[0].lower()if rid in done or url_key in have_urls:skip += 1continuetry:raw, resolved, method = fetch_pdf_bytes(url, wayback_ts=ts)except Exception as exc:fail += 1log_failure(CC, {"identifier": ident, "source_url": url, "status": "failed", "reason": repr(exc)})continueif not raw:fail += 1log_failure(CC, {"identifier": ident, "source_url": url, "status": "failed", "reason": "pdf_fetch_fail"})continuest = save_pdf_instrument(resolved, raw, method, done)if st == "ok":have_urls.add(url_key)have_urls.add(resolved.split("?")[0].lower())ok += st == "ok"skip += st == "skip"fail += st == "fail"if (ok + fail) % 10 == 0 or i < 3:log.info("progress i=%s/%s ok=%s skip=%s fail=%s last=%s", i + 1, discovered, ok, skip, fail, method)if (ok + fail) % 50 == 0:write_summary(CC,country=COUNTRY,source="Cyprus Government Printing Office gazette PDFs",source_urls=[f"{GAZETTE_NSF}/officialgazette-el/officialgazette-el?OpenDocument",f"{GAZETTE_NSF}/dmlgazette_archive_gr/dmlgazette_archive_gr?OpenForm",],license_text=LICENSE,discovered=discovered,fetched=ok,skipped=skip,failed=fail,coverage="catalog-backed incomplete",notes="\n".join(notes[-40:]),last_run=utcnow(),)# Also keep any useful HTML-only pages already present; do not re-scrape shallow seeds as instruments.notes.append("GPO PDF harvest via live Domino archive/sections + Wayback CDX of official mof.gov.cy URLs. ""cylaw.org unused. legislation.gov.cy NXDOMAIN.")write_summary(CC,country=COUNTRY,source="Cyprus Government Printing Office gazette PDFs",source_urls=[f"{GAZETTE_NSF}/officialgazette-el/officialgazette-el?OpenDocument",f"{GAZETTE_NSF}/dmlgazette_archive_gr/dmlgazette_archive_gr?OpenForm","https://www.gov.cy/en/service/episimi-efimerida-tis-dimokratias/",],license_text=LICENSE,discovered=discovered,fetched=ok,skipped=skip,failed=fail,coverage="catalog-backed incomplete",notes="\n".join(notes),last_run=utcnow(),extra=f"started {t0} instruments_on_disk={len(existing_ids(CC))}",)log.info("done disc=%s ok=%s skip=%s fail=%s instruments=%s", discovered, ok, skip, fail, len(existing_ids(CC)))if __name__ == "__main__":
233 unmodified lines234235236237238239240241242243244245246259 unmodified lines506507508233 unmodified linesARTICLE_SPLIT = re.compile(r"(?im)^\s*((?:art(?:icle|ikel|\.)|§|článek|článok|član|artikkel|articolo|"r"artigo|artículo|artykuł|art\.\s*|str\.\s*|para(?:graph)?\.?|szakasz|"r"άρθρο|Άρθρο|ΑΡΘΡΟ)\s+"r"[\dIVXLCDMΑ-Ω]+[a-zA-ZΑ-Ωa-z]?)\b")def split_articles(text: str, law_id: str, source_url: str, date: Optional[str] = None) -> list[dict]:if not text or len(text) < 40:return []259 unmodified linesif m:return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"return None233 unmodified lines234235236237238239240241242243244259 unmodified lines504505506507508509510511512513514515516517518519520521522523524525526233 unmodified linesARTICLE_SPLIT = re.compile(r"(?im)^\s*((?:art(?:icle|ikel|\.)|§|článek|článok|član|artikkel|articolo|"r"artigo|artículo|artykuł|art\.|str\.|para(?:graph)?\.?|szakasz)\s+"r"[\dIVXLCDM]+[a-zA-Z]?)\b")def split_articles(text: str, law_id: str, source_url: str, date: Optional[str] = None) -> list[dict]:if not text or len(text) < 40:return []259 unmodified linesif m:return f"{m.group(3)}-{m.group(2)}-{m.group(1)}"return Nonedef pdf_bytes_to_text(raw: bytes, timeout: int = 180) -> str:"""Extract text from PDF bytes via pdftotext. Empty on failure."""import subprocessif not raw or raw[:4] != b"%PDF":return ""try:with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as tmp:tmp.write(raw)tmp.flush()proc = subprocess.run(["pdftotext", "-layout", "-enc", "UTF-8", tmp.name, "-"],check=False, capture_output=True, timeout=timeout,)if proc.returncode == 0 and proc.stdout:return proc.stdout.decode("utf-8", "replace").strip()except Exception:return ""return ""
MANIFEST.md+20-8
README.md+12-10
data/articles.parquet+2-2
data/laws.parquet+2-2
scrapers/collect_cy.py+636-273
scrapers/common.py+22-4