File size: 6,401 Bytes
6f5156a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | """Luxembourg Cour de cassation via data.public.lu open-data API.
Endpoint and dataset slug discovered via the worldwidelaw/legal-sources project
(AGPL-3.0). We reimplement the scraping based on the public API.
The dataset (cour-de-cassation) ships PDF files whose names encode both the
decision date (YYYYMMDD prefix) and the civil/criminal split: criminal cassation
PDFs are prefixed `penal`, civil/general cassation PDFs start with the date.
We rely on that filename flag for `civil_filter()`.
Bandwidth optimisation: the Goldenset only needs `sample_n` cases (130). We
list all metadata up front and pre-sample 130 civil candidates using the same
seed as the downstream pipeline, then download + OCR PDFs only for that
shortlist. Downstream `random_sample(seed=0)` is deterministic, so it picks the
same 130 — and those 130 are the only Cases that carry `full_text`.
"""
import logging
import random
import re
import time
from datetime import date
from pathlib import Path
import pdfplumber
import requests
from legex.config import settings
from legex.models.base import Case
from legex.scrapers.base import BaseScraper
log = logging.getLogger(__name__)
DATASET_URL = "https://data.public.lu/api/1/datasets/cour-de-cassation/"
USER_AGENT = "legex-research (open-data, friendly)"
DOWNLOAD_DELAY_SECONDS = 0.5
PDF_TIMEOUT = 90
_FILENAME_RE = re.compile(r"^(penal)?(\d{4})(\d{2})(\d{2})-")
_STRIP_SUFFIXES = (
"-pseudonymise-accessible.pdf",
"-accessible.pdf",
".pdf",
)
def _case_id_from_title(title: str) -> str:
name = title
for suffix in _STRIP_SUFFIXES:
if name.endswith(suffix):
name = name[: -len(suffix)]
break
return name
def _extract_pdf_text(path: Path) -> str | None:
try:
with pdfplumber.open(path) as pdf:
pages = [page.extract_text() or "" for page in pdf.pages]
text = "\n".join(p for p in pages if p).strip()
return text or None
except Exception as e:
log.warning("LU pdfplumber failed for %s (%s)", path.name, e)
return None
class LUScraper(BaseScraper):
country = "Luxemburg"
def scrape(
self,
start_date: date | None = None,
end_date: date | None = None,
) -> list[Case]:
session = requests.Session()
session.headers.update({"User-Agent": USER_AGENT, "Accept": "application/json"})
try:
resp = session.get(DATASET_URL, timeout=60)
resp.raise_for_status()
dataset = resp.json()
except Exception as e:
log.warning("LU dataset fetch failed (%s); returning empty", e)
return []
resources = dataset.get("resources", []) or []
log.info("LU resources listed: %d", len(resources))
cases: list[Case] = []
seen: set[str] = set()
for res in resources:
title = res.get("title") or ""
url = res.get("url") or ""
if not title or not url:
continue
m = _FILENAME_RE.match(title)
if not m:
continue
criminal = m.group(1) is not None
try:
decision_date = date(int(m.group(2)), int(m.group(3)), int(m.group(4)))
except ValueError:
continue
if start_date and decision_date < start_date:
continue
if end_date and decision_date > end_date:
continue
case_id = _case_id_from_title(title)
if case_id in seen:
continue
seen.add(case_id)
cases.append(
Case(
case_id=case_id,
link=url,
decision_date=decision_date,
jurisdiction="lu",
language="fr",
full_text=None,
metadata={
"filename": title,
"criminal_prefix": criminal,
"resource_id": res.get("id"),
},
)
)
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
# Pre-sample the civil shortlist using the same seed as the downstream
# pipeline (legex.processing.filter_and_sample). Both samples operate on
# the same ordered list, so the picks match — and we only need to
# download/OCR PDFs for this shortlist.
civil_cases = [c for c in cases if not c.metadata.get("criminal_prefix")]
n = min(settings.sample_n, len(civil_cases))
shortlist = random.Random(settings.sample_seed).sample(civil_cases, n)
shortlist_ids = {c.case_id for c in shortlist}
log.info(
"LU candidates: %d total (%d civil); downloading PDFs for %d sampled",
len(cases),
len(civil_cases),
len(shortlist_ids),
)
cache_dir = settings.data_dir / "cache" / "lu"
cache_dir.mkdir(parents=True, exist_ok=True)
downloaded = 0
for case in cases:
if case.case_id not in shortlist_ids:
continue
pdf_path = cache_dir / f"{case.case_id}.pdf"
if not pdf_path.exists():
try:
r = session.get(case.link, timeout=PDF_TIMEOUT)
r.raise_for_status()
pdf_path.write_bytes(r.content)
downloaded += 1
if downloaded % 25 == 0:
log.info("LU downloaded %d PDFs", downloaded)
time.sleep(DOWNLOAD_DELAY_SECONDS)
except Exception as e:
log.warning("LU PDF download failed %s (%s)", case.case_id, e)
continue
case.full_text = _extract_pdf_text(pdf_path)
log.info(
"Collected %d Luxembourg cases (%d with full_text, %d criminal-prefixed)",
len(cases),
sum(1 for c in cases if c.full_text),
sum(1 for c in cases if c.metadata.get("criminal_prefix")),
)
return cases
@staticmethod
def civil_filter(cases: list[Case]) -> list[Case]:
kept = [c for c in cases if not (c.metadata or {}).get("criminal_prefix")]
log.info("LU civil_filter kept %d/%d", len(kept), len(cases))
return kept
|