| from __future__ import annotations |
|
|
| import logging |
| import re |
| import threading |
| import time |
| import xml.etree.ElementTree as ET |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from datetime import date |
|
|
| import requests |
| from dateutil import parser as dateutil_parser |
|
|
| from legex.models.base import Case |
| from legex.scrapers.base import BaseScraper |
|
|
| log = logging.getLogger(__name__) |
|
|
| |
| |
| |
| |
| BASE_URL = "https://caselaw.nationalarchives.gov.uk" |
| ATOM_URL = f"{BASE_URL}/atom.xml" |
| COURTS = ["uksc", "ewca/civ"] |
| PAGE_SIZE = 50 |
| DELAY_SECONDS = 3 |
| RETRY_DELAY_SECONDS = 30 |
| XML_WORKERS = 8 |
|
|
| |
| _MIN_INTERVAL = 0.35 |
| _RATE_LOCK = threading.Lock() |
| _LAST_REQ_AT = [0.0] |
|
|
| ATOM_NS = { |
| "atom": "http://www.w3.org/2005/Atom", |
| "tna": "https://caselaw.nationalarchives.gov.uk", |
| } |
| AKN = "{http://docs.oasis-open.org/legaldocml/ns/akn/3.0}" |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| _NOT_CIVIL_RE = re.compile( |
| r"^R\s+(?:v\b|\()" |
| r"|\bR\s*\(on the application of\b" |
| r"|^(?:Director of Public Prosecutions|DPP)\s+v\b" |
| r"|^Attorney General(?:['’]s)?\s+Reference\b" |
| r"|\b(?:Her Majesty(?:['’]s)?\s+Advocate|HM\s+Advocate|Procurator Fiscal)\b", |
| re.IGNORECASE, |
| ) |
|
|
|
|
| def _throttle() -> None: |
| with _RATE_LOCK: |
| wait = _MIN_INTERVAL - (time.monotonic() - _LAST_REQ_AT[0]) |
| if wait > 0: |
| time.sleep(wait) |
| _LAST_REQ_AT[0] = time.monotonic() |
|
|
|
|
| def _parse_date(raw: str | None) -> date | None: |
| if not raw: |
| return None |
| try: |
| return date.fromisoformat(raw[:10]) |
| except ValueError: |
| pass |
| try: |
| return dateutil_parser.parse(raw, dayfirst=True).date() |
| except (ValueError, OverflowError, dateutil_parser.ParserError): |
| return None |
|
|
|
|
| def _fetch(session: requests.Session, url: str, params: dict | None = None) -> bytes | None: |
| _throttle() |
| try: |
| resp = session.get(url, params=params, timeout=30) |
| if resp.status_code == 429: |
| log.warning("HTTP 429 on %s — sleeping %ds then retrying", url, RETRY_DELAY_SECONDS) |
| time.sleep(RETRY_DELAY_SECONDS) |
| _throttle() |
| resp = session.get(url, params=params, timeout=30) |
| if not resp.ok: |
| log.warning("HTTP %d for %s", resp.status_code, url) |
| return None |
| return resp.content |
| except requests.RequestException as exc: |
| log.warning("Error fetching %s: %s", url, exc) |
| return None |
|
|
|
|
| def _extract_full_text(xml_bytes: bytes) -> str | None: |
| try: |
| root = ET.fromstring(xml_bytes) |
| except ET.ParseError: |
| return None |
| body = root.find(f".//{AKN}judgmentBody") |
| if body is None: |
| return None |
| parts: list[str] = [] |
| for el in body.iter(): |
| for t in (el.text, el.tail): |
| if t and (s := t.strip()): |
| parts.append(s) |
| return "\n".join(parts) if parts else None |
|
|
|
|
| def _entry_to_case(entry: ET.Element, court: str) -> Case | None: |
| title_el = entry.find("atom:title", ATOM_NS) |
| title = (title_el.text if title_el is not None else "") or "" |
|
|
| published_el = entry.find("atom:published", ATOM_NS) |
| decision_date = _parse_date(published_el.text if published_el is not None else None) |
|
|
| link_html = link_xml = link_pdf = None |
| for link in entry.findall("atom:link", ATOM_NS): |
| rel = link.attrib.get("rel") |
| ltype = link.attrib.get("type") |
| href = link.attrib.get("href") |
| if not href: |
| continue |
| if rel == "alternate" and ltype is None and href.startswith(BASE_URL): |
| link_html = href |
| elif ltype == "application/akn+xml": |
| link_xml = href |
| elif ltype == "application/pdf": |
| link_pdf = href |
|
|
| if not link_html: |
| return None |
|
|
| cite_el = entry.find("tna:identifier[@type='ukncn']", ATOM_NS) |
| citation = cite_el.text if cite_el is not None else None |
| slug = cite_el.attrib.get("slug") if cite_el is not None else None |
|
|
| return Case( |
| case_id=citation, |
| link=link_html, |
| decision_date=decision_date, |
| jurisdiction="uk", |
| language="en", |
| full_text=None, |
| metadata={ |
| "title": title, |
| "slug": slug, |
| "court": court, |
| "xml_url": link_xml, |
| "pdf_url": link_pdf, |
| }, |
| ) |
|
|
|
|
| class UKScraper(BaseScraper): |
| country = "United Kingdom" |
|
|
| def scrape( |
| self, |
| start_date: date | None = None, |
| end_date: date | None = None, |
| ) -> list[Case]: |
| session = requests.Session() |
| session.headers.update({"Accept": "application/atom+xml, application/xml, */*"}) |
|
|
| cases: list[Case] = [] |
| seen: set[str] = set() |
|
|
| for court in COURTS: |
| cases.extend(self._scrape_court(session, court, seen, start_date, end_date)) |
|
|
| todo = [c for c in cases if (c.metadata or {}).get("xml_url")] |
| if todo: |
| log.info("Fetching full_text for %d Akoma Ntoso XML files", len(todo)) |
| done = failed = 0 |
| with ThreadPoolExecutor(max_workers=XML_WORKERS) as pool: |
| futures = { |
| pool.submit(_fetch, session, c.metadata["xml_url"]): c for c in todo |
| } |
| for fut in as_completed(futures): |
| case = futures[fut] |
| xml_bytes = fut.result() |
| text = _extract_full_text(xml_bytes) if xml_bytes else None |
| if text: |
| case.full_text = text |
| done += 1 |
| else: |
| failed += 1 |
| if (done + failed) % 100 == 0: |
| log.info( |
| "XML progress %d/%d (failed=%d)", |
| done + failed, len(todo), failed, |
| ) |
| log.info("Hydrated %d XML files (failed=%d)", done, failed) |
|
|
| return cases |
|
|
| @staticmethod |
| def _scrape_court( |
| session: requests.Session, |
| court: str, |
| seen: set[str], |
| start_date: date | None, |
| end_date: date | None, |
| ) -> list[Case]: |
| out: list[Case] = [] |
| page = 1 |
| while True: |
| log.info("[%s] atom page %d", court, page) |
| data = _fetch(session, ATOM_URL, params={"court": court, "page": page}) |
| if not data: |
| break |
| try: |
| root = ET.fromstring(data) |
| except ET.ParseError as exc: |
| log.warning("[%s] parse error on page %d: %s", court, page, exc) |
| break |
|
|
| entries = root.findall("atom:entry", ATOM_NS) |
| if not entries: |
| log.info("[%s] no entries on page %d — stopping", court, page) |
| break |
|
|
| all_before_start = True |
| for entry in entries: |
| case = _entry_to_case(entry, court) |
| if case is None or not case.link or case.link in seen: |
| continue |
| d = case.decision_date |
| if end_date and d and d > end_date: |
| |
| all_before_start = False |
| continue |
| if start_date and d and d >= start_date: |
| all_before_start = False |
| if start_date and d and d < start_date: |
| continue |
| seen.add(case.link) |
| out.append(case) |
|
|
| if start_date and all_before_start: |
| log.info("[%s] all on page %d predate start_date — stopping early", court, page) |
| break |
| if len(entries) < PAGE_SIZE: |
| log.info("[%s] last page at %d (%d items)", court, page, len(entries)) |
| break |
|
|
| time.sleep(DELAY_SECONDS) |
| page += 1 |
|
|
| log.info("[%s] collected %d cases", court, len(out)) |
| return out |
|
|
| @staticmethod |
| def civil_filter(cases: list[Case]) -> list[Case]: |
| return [ |
| c for c in cases |
| if not _NOT_CIVIL_RE.search(((c.metadata or {}).get("title") or "").strip()) |
| ] |
|
|