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
11234567893456789101112131415161718192021# MANIFEST# ipfs_cyprus_laws 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 bytesgenerated_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.1223445672 unmodified lines10111213141516175 unmodified lines23242524262726282930312 unmodified lines3435363536373839383940414243424445464715 unmodified lines6364656466---pretty_name: Laws of Cypruspretty_name: Laws of Cyprus (GPO gazette)license: otherlicense_name: cyprus-gpo-gazettelicense_name: cyprus-gpo-officiallanguage:- eltask_categories:2 unmodified lines- legal- law- cyprus- gpo- gazette- official-textssize_categories:- n<1K5 unmodified lines data_files: data/articles.parquet---
# Laws of Cyprus# Laws of Cyprus (GPO gazette)
Research snapshot of official legislation collected from **GPO mof.gov.cy**.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 | catalog-backed incomplete || Source | GPO mof.gov.cy || 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 | 302 || Articles | 4398 || Laws / instruments | 341 || Articles | 111 || Language | el || Jurisdiction | Cyprus || License | `cyprus-gpo-gazette` || License | `cyprus-gpo-official` |
## Contents
15 unmodified lines
## Notes
Deepen: GPO gazette PDFs via Wayback CDX (no cylaw) + cy_extract_articles. Not legal advice.Method: cdx_parallel_expand + archive_fallbacks. Not complete. Official source prevails. Not legal advice.12323version https://git-lfs.github.com/spec/v1oid sha256:92692042d7ead4a887d448971284ebbdc9927cde1e2053650a5821d371b805f4size 9669073oid sha256:345b8cd23246bb4d09a81a6b3e8c62b966ae747ca501be9ffec34303a17d9dc2size 27929212323version https://git-lfs.github.com/spec/v1oid sha256:0869c92729d15d1bbb3fae32f3feead651fdacecd7aa141a070073539dcd89cfsize 13048112oid sha256:97e6df2b84f3ca611e23d8e91d8c942f1741c84307148d19faad09b5bfce6212size 968759712234567891011121341415161718192021226232425892627282930311232333435363738394016414243444546474849505152535455565758596061626364656667686970717273747576777879212223808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219327282930311941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744753347647735478479480383940414243481482483484485486487488489490491492493494495496497498499500501502503474849505045055065075085095105115125135145253545556575851551651751851952052152252352452552652752852953053153253353453553653753853954054161626354254354465666768697071727374757677545546798054754854955082838485868788899091929355155295965535545555569899100101102103104105106107108109110111112113114115116117118119120121122123124557558559560561126127128129130131132133134135136137138139140141562563143144145146147148149150151152153154155156157158159160161162163164165166167168169170171564565566567568569570571572573574575576577578579580581582583584585586587588173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205589590207208209210211212213214215216217218219220221222223224225226227591592593594595596597598599600601602603604230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270605606607608609610611612272613614615616275276617618619620621622278279280623624282283625626285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682#!/usr/bin/env python3"""Cyprus: official GPO gazette (mof.gov.cy). PDF body extraction. Not cylaw.org.""""""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 attachments 4) 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 io, json, logging, os, re, sys, time
import html as htmlmodimport jsonimport loggingimport reimport sysimport timeimport warningsfrom pathlib import Pathfrom urllib.parse import urljoin, unquotefrom urllib.parse import urljoin, unquote, quote
sys.path.insert(0, str(Path(__file__).resolve().parent))from common import *import archive_fallbacks as affrom common import * # noqa: F401,F403from archive_fallbacks import search_wayback_machine, get_wayback_content
warnings.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."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")
ASSET_RE = re.compile(r"\.(css|js|png|jpe?g|gif|svg|ico|woff2?|ttf|map)(\?|$)", re.I)# 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.35
def setup(): ensure_dirs(CC) logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", 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)]) 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 = None for 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, verify last = r if r.status_code in (404, 410): return r, verify except Exception as exc: last = exc return last, None
def is_official(url: str) -> bool: if not url or CYLAW_RE.search(url): return False u = 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): continue if SKIP_PATH_RE.search(full): continue if full.lower() in seen: continue seen.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 out
def 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: continue num = 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: break return docs
def 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 header for 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 url
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():def 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 None
def 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 links seeds = [ 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}") continue notes.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: continue html = 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): continue r, _ = try_get(url) if not hasattr(r, "status_code") or r.status_code != 200 or not r.content: continue found = extract_unids(r.text or "") before = len(unids) unids.update(found) # Only paginate when the view clearly has a large batch if 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 = url if "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: break more = extract_unids(r2.text or "") new_n = len(set(more) - unids) unids.update(more) if new_n == 0: break log.info("section +%s total_unids=%s url=%s", len(unids) - before, len(unids), url[-80:]) return unids
def 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 indices r, _ = 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: continue found = extract_unids(r.text or "") # Sometimes need deeper Expand=y.m.p.q if 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 form prev = 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 unids
def 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}") continue n = 0 for rec in rows: orig = rec.get("original") or "" if not is_official(orig): continue if ".pdf" not in orig.lower() and "$file" not in orig.lower() and "$FILE" not in orig: continue if CYLAW_RE.search(orig) or SKIP_PATH_RE.search(orig): continue key = orig.lower() if key in seen: continue seen.add(key) out.append(rec) n += 1 notes.append(f"cdx {pat} pdfish={n} raw={len(rows)}") log.info("cdx %s pdfish=%s", pat, n) time.sleep(2.0) return out
def 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 first r, _ = 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 needed if " " 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" # Wayback try: 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 ts if 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: pass return 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 out for line in fp.open(encoding="utf-8"): for path in d.glob("*.json"): try: d = json.loads(line) rec = json.loads(path.read_text(encoding="utf-8")) except Exception: continue ident = 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()) for 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 out
def try_get(url, verify_first=True): last = None order = (True, False) if verify_first else (False, True) for verify in order:def 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 out seen = set() for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): line = line.strip() if not line: continue 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, verify except Exception as exc: last = exc return last, None rec = json.loads(line) except Exception: continue url = (rec.get("original") or rec.get("url") or "").strip() if not url or not is_official(url): continue low = url.lower() if ".pdf" not in low and "$file" not in low: continue key = url.split("?")[0].lower() if key in seen: continue seen.add(key) out.append((url, rec.get("timestamp"))) return out
def main(): setup() t0 = utcnow() notes: list[str] = [] done = existing_ids(CC) have_urls = existing_source_urls(CC) ok = skip = fail = 0
log.info("=== CY GPO PDF harvest start existing=%s urls=%s ===", len(done), len(have_urls))
def 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_pdf # --- Discovery: UNIDs from live site --- unids: set[str] = set() try: import pdfplumber with pdfplumber.open(io.BytesIO(data)) as pdf: parts = [] for page in pdf.pages[:120]: try: parts.append(page.extract_text() or "") except Exception: continue text = "\n".join(parts) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n{3,}", "\n\n", text).strip() if len(text) >= 40: return text unids |= discover_section_unids(notes) except Exception as exc: log.info("pdfplumber fail: %s", exc) # 2) pypdf fallback notes.append(f"section_discover ERROR {exc}") log.exception("section_discover") log.info("after sections unids=%s", len(unids)) try: from pypdf import PdfReader reader = PdfReader(io.BytesIO(data)) parts = [] for page in reader.pages[:120]: try: parts.append(page.extract_text() or "") except Exception: continue text = "\n".join(parts) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n{3,}", "\n\n", text) return text.strip() unids |= discover_archive_unids(notes) except Exception as exc: log.info("pdf extract fail: %s", exc) return "" notes.append(f"archive_discover ERROR {exc}") log.exception("archive_discover") log.info("after archive unids=%s", len(unids))
def is_gazette_pdf_url(url: str) -> bool: u = (url or "").lower() if "cylaw.org" in u: return False if ASSET_RE.search(u): return False uq = 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 True if uq.rstrip().endswith(".pdf") and "mof.gov.cy" in u and "gpo" in u: return True return False
def 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 None
def _wb(ts_in: str): # Resolve UNIDs → PDF URLs pdf_jobs: list[tuple[str, str | None]] = [] # (url, wayback_ts) seen_pdf = set() for i, unid in enumerate(sorted(unids)): try: t = ts_in u = url if 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 u if not t: return None w = 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" pdfs = issue_pdfs_from_unid(unid) 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 got return "", url, "none" for fn in (_live, _wb): got = fn(ts) if fn is _wb else _live() if got: return got return "", 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 PDFs import requests params = { "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), } log.warning("issue %s fail %s", unid, exc) fail += 1 continue for u in pdfs: key = u.lower() if key in seen_pdf: continue seen_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: continue seen_pdf.add(key) pdf_jobs.append((url, ts)) notes.append(f"after_cdx_file pdfs={len(pdf_jobs)}")
# --- CDX fallback PDFs --- try: import json q = [ ("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 = None for 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 = r if 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): continue key = unquote(orig).lower() if key in seen: continue seen.add(key) out.append((orig, ts)) log.info("cdx mime-pdf unique=%s", len(out)) break log.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)) cdx_rows = discover_cdx_pdfs(notes) except Exception as exc: log.info("cdx direct fail: %s", exc) if len(out) < 20: # fallback via helper + $file filter try: 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): continue key = unquote(u).lower() if key in seen: continue seen.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 out 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: continue seen_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}")
def 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 hrefs seeds = [ "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}") continue notes.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 = 0 known_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: break if max_seconds and (time.time() - t_start) > max_seconds: break ident = re.sub(r"^https?://", "", href) # Prefer filename as stable id when Domino $file present m = re.search(r"\$file/([^/?#]+)", href, re.I) if m: ident = "gpo-pdf-" + unquote(m.group(1)) # Persist discovery list for resume/debug disc_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) if rid in done: url_key = url.split("?")[0].lower() if rid in done or url_key in have_urls: skip += 1 continue if ident.lower() in known_fail or unquote(href).lower() in known_fail: skip += 1 try: raw, resolved, method = fetch_pdf_bytes(url, wayback_ts=ts) except Exception as exc: fail += 1 log_failure(CC, {"identifier": ident, "source_url": url, "status": "failed", "reason": repr(exc)}) continue log.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: if not raw: fail += 1 log_failure(CC, {"identifier": ident, "source_url": href, "status": "failed", "reason": f"empty_{kind}"}) log.info("fail %s kind=%s", ident[:70], kind) log_failure(CC, {"identifier": ident, "source_url": url, "status": "failed", "reason": "pdf_fetch_fail"}) continue title = unquote(m.group(1)) if m else ident for line in text.splitlines(): if len(line.strip()) > 12: title = line.strip()[:240] break rec = 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 structure extra_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) st = 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 lines234235236237238239237238239240241243242243244259 unmodified lines504505506507508509510511512513514515516517518519520521522523524525526233 unmodified lines
ARTICLE_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" 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 lines if m: return f"{m.group(3)}-{m.group(2)}-{m.group(1)}" return None
def pdf_bytes_to_text(raw: bytes, timeout: int = 180) -> str: """Extract text from PDF bytes via pdftotext. Empty on failure.""" import subprocess if 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