"""French Cour de cassation scraper via the PISTE Judilibre API. Civil filtering happens pre-download at the API level (``CIVIL_CHAMBERS``), so the default passthrough ``BaseScraper.civil_filter`` suffices. """ import logging import os import time from datetime import date import requests from legex.models.base import Case from legex.scrapers.base import BaseScraper log = logging.getLogger(__name__) PROD_BASE_URL = "https://api.piste.gouv.fr/cassation/judilibre/v1.0" PISTE_TOKEN_URL = "https://oauth.piste.gouv.fr/api/oauth/token" DECISION_URL_TEMPLATE = "https://www.courdecassation.fr/decision/{decision_id}" CIVIL_CHAMBERS = ["civ1", "civ2", "civ3"] CHAMBER_LABELS = {"civ1": "1re civile", "civ2": "2e civile", "civ3": "3e civile"} METADATA_KEYS = ("number", "chamber", "jurisdiction", "ecli", "solution", "formation", "publication", "type") BATCH_SIZE = 1000 DELAY_SECONDS = 3 class FRScraper(BaseScraper): country = "Frankreich" def __init__( self, client_id: str = "", client_secret: str = "", base_url: str = PROD_BASE_URL, ) -> None: self.client_id = client_id or os.environ.get("JUDILIBRE_CLIENT_ID", "") self.client_secret = client_secret or os.environ.get("JUDILIBRE_CLIENT_SECRET", "") self.base_url = base_url if not self.client_id or not self.client_secret: raise ValueError( "FRScraper requires JUDILIBRE_CLIENT_ID and JUDILIBRE_CLIENT_SECRET. " "Set them in .env or pass as constructor arguments." ) self.session = requests.Session() self.session.headers.update({ "Accept": "application/json", "Authorization": f"Bearer {self._obtain_access_token()}", }) def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: # Judilibre /export caps at 10 batches × 1000 = 10 000 results per query, # so we chunk by year to stay under the cap. start_date = start_date or date(2015, 1, 1) end_date = end_date or date.today() all_cases: list[Case] = [] seen_links: set[str] = set() for year in range(start_date.year, end_date.year + 1): year_start = max(start_date, date(year, 1, 1)).isoformat() year_end = min(end_date, date(year, 12, 31)).isoformat() log.info(f"Scraping year {year} ({year_start} to {year_end})") for chamber in CIVIL_CHAMBERS: for case in self._scrape_chamber(year, chamber, year_start, year_end): if case.link not in seen_links: seen_links.add(case.link) all_cases.append(case) time.sleep(DELAY_SECONDS) return all_cases def _obtain_access_token(self) -> str: resp = requests.post( PISTE_TOKEN_URL, data={ "grant_type": "client_credentials", "client_id": self.client_id, "client_secret": self.client_secret, "scope": "openid", }, timeout=15, ) resp.raise_for_status() token = resp.json().get("access_token", "") if not token: raise ValueError(f"No access_token in response: {resp.text[:200]}") return token def _fetch_json(self, url: str, params: dict | None = None) -> dict: response = self.session.get(url, params=params, timeout=15) if response.status_code == 429: time.sleep(30) return self._fetch_json(url, params) response.raise_for_status() return response.json() def _fetch_export_batch( self, chamber: str, batch: int, date_start: str | None, date_end: str | None, ) -> dict: params: dict = { "chamber": chamber, "batch": batch, "batch_size": BATCH_SIZE, "resolve_references": "false", } if date_start: params["date_start"] = date_start if date_end: params["date_end"] = date_end return self._fetch_json(f"{self.base_url}/export", params=params) def _scrape_chamber( self, year: int, chamber: str, date_start: str | None, date_end: str | None, ) -> list[Case]: results: list[Case] = [] label = CHAMBER_LABELS.get(chamber, chamber) batch = 0 while True: data = self._fetch_export_batch(chamber, batch, date_start, date_end) decisions = data.get("results", []) log.info(f"[{year}] {label}: batch {batch} — {len(decisions)} decisions (total: {data.get('total', '?')})") for decision in decisions: case = self._decision_to_case(decision) if case is not None: results.append(case) if not decisions or data.get("next_batch") is None: log.info(f"[{year}] {label}: done at batch {batch} ({len(results)} total)") break batch += 1 time.sleep(DELAY_SECONDS) return results @staticmethod def _normalize_date(raw_date: str | None) -> date | None: if not raw_date: return None try: return date.fromisoformat(raw_date.strip()) except ValueError: return None @classmethod def _decision_to_case(cls, decision: dict) -> Case | None: decision_id = decision.get("id") if not decision_id: return None parsed_date = cls._normalize_date(decision.get("decision_date")) if parsed_date is None: return None return Case( case_id=decision.get("number") or decision.get("ecli"), link=DECISION_URL_TEMPLATE.format(decision_id=decision_id), decision_date=parsed_date, jurisdiction="fr", language="fr", full_text=decision.get("text"), metadata={k: decision.get(k) for k in METADATA_KEYS if decision.get(k)}, )