"""Austria OGH (Oberster Gerichtshof) via RIS OGD API v2.6. Endpoint and field schema discovered via the worldwidelaw/legal-sources project (AGPL-3.0). We reimplement the scraping based on the API endpoint (link below). Docs: https://data.bka.gv.at/ris/ogd/v2.6/Documents/Dokumentation_OGD-RIS_API.pdf """ import logging import re import time from datetime import date from typing import Any from xml.etree import ElementTree as ET import requests from legex.models.base import Case from legex.scrapers.base import BaseScraper log = logging.getLogger(__name__) API_URL = "https://data.bka.gv.at/ris/api/v2.6/Judikatur" RIS_DOCUMENTS_URL = "https://www.ris.bka.gv.at/Dokumente/Justiz" PAGE_SIZE = 100 RATE_DELAY_SECONDS = 1.0 ENRICH_DELAY_SECONDS = 0.4 USER_AGENT = "legex-research (open-data, friendly)" _DOC_ID_DATE_RE = re.compile(r"^JJ[RT]_(\d{8})_") _JJT_NUM_RE = re.compile(r"(JJT_\d{8}_[A-Z0-9_]+)") _WS_RE = re.compile(r"\s+") _NORM_GZ_RE = re.compile(r"\s+") def _parse_doc_id_date(doc_id: str) -> date | None: match = _DOC_ID_DATE_RE.match(doc_id or "") if not match: return None try: return date.fromisoformat( f"{match.group(1)[:4]}-{match.group(1)[4:6]}-{match.group(1)[6:8]}" ) except ValueError: return None def _as_text(obj: Any) -> str: """Flatten RIS `{"item": value}` / list / scalar into a single string.""" if obj in (None, "", {}): return "" if isinstance(obj, str): return obj if isinstance(obj, dict): item = obj.get("item", obj.get("#text", "")) return _as_text(item) if isinstance(obj, list): return " | ".join(_as_text(x) for x in obj if x) return str(obj) def _first_geschaeftszahl(value: Any) -> str: text = _as_text(value) for sep in (";", "|"): if sep in text: text = text.split(sep, 1)[0] return text.strip() class ATScraper(BaseScraper): country = "Österreich" def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: params: dict[str, str] = { "Applikation": "Justiz", "Gericht": "OGH", "DokumenteProSeite": "OneHundred", } if start_date or end_date: params["Entscheidungsdatum.SucheNachDatum"] = "true" if start_date: params["EntscheidungsdatumVon"] = start_date.isoformat() if end_date: params["EntscheidungsdatumBis"] = end_date.isoformat() cases: list[Case] = [] seen_ids: set[str] = set() page = 1 total: int | None = None session = requests.Session() session.headers.update({"User-Agent": USER_AGENT, "Accept": "application/json"}) while True: params["Seitennummer"] = str(page) try: resp = session.get(API_URL, params=params, timeout=60) resp.raise_for_status() data = resp.json() except Exception as e: log.warning("AT page %d failed (%s); stopping", page, e) break results = data.get("OgdSearchResult", {}).get("OgdDocumentResults", {}) if total is None: hits_text = results.get("Hits", {}).get("#text", "0") try: total = int(hits_text) except ValueError: total = 0 log.info("AT total OGH hits: %d", total) if total == 0: break docs = results.get("OgdDocumentReference", []) if not isinstance(docs, list): docs = [docs] if docs else [] if not docs: break for doc in docs: case = self._to_case(doc.get("Data", {})) if case is None or case.case_id in seen_ids: continue # Server filter applies to most recent citation date, so include # RS that ride along on a recent citation, drop them here. if start_date and case.decision_date and case.decision_date < start_date: continue if end_date and case.decision_date and case.decision_date > end_date: continue seen_ids.add(case.case_id) cases.append(case) fetched = page * PAGE_SIZE log.info("AT page %d: %d docs (%d/%d total)", page, len(docs), min(fetched, total), total) if fetched >= total: break page += 1 time.sleep(RATE_DELAY_SECONDS) cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info("Collected %d Austria cases", len(cases)) return cases @staticmethod def _to_case(data: dict[str, Any]) -> Case | None: meta = data.get("Metadaten", {}) tech = meta.get("Technisch", {}) allg = meta.get("Allgemein", {}) jud = meta.get("Judikatur", {}) justiz = jud.get("Justiz", {}) doc_id = tech.get("ID", "") or "" case_id = _first_geschaeftszahl(jud.get("Geschaeftszahl")) if not case_id: return None link = allg.get("DokumentUrl") or "" decision_date = _parse_doc_id_date(doc_id) latest_citation: str | None = None raw_date = jud.get("Entscheidungsdatum") if isinstance(raw_date, str) and raw_date: latest_citation = raw_date[:10] return Case( case_id=case_id, link=link, decision_date=decision_date, jurisdiction="at", language="de", full_text=None, metadata={ "doc_id": doc_id, "ecli": _as_text(jud.get("EuropeanCaseLawIdentifier")), "dokumenttyp": _as_text(jud.get("Dokumenttyp")), "rechtsgebiete": _as_text(justiz.get("Rechtsgebiete")), "rechtssatznummern": _as_text(justiz.get("Rechtssatznummern")), "gericht": _as_text(justiz.get("Gericht")), "normen": _as_text(jud.get("Normen")), "latest_citation_date": latest_citation, }, ) @staticmethod def civil_filter(cases: list[Case]) -> list[Case]: # Justiz application at the OGH classifies cases by Rechtsgebiete. "Zivilrecht" # is civil law. Some entries combine fields like "Zivilrecht | Arbeitsrecht". return [ c for c in cases if "zivilrecht" in (c.metadata or {}).get("rechtsgebiete", "").lower() ] @classmethod def enrich(cls, cases: list[Case]) -> list[Case]: """Download the JJT decision XML for each sampled case and set full_text. For each Rechtssatz we re-query the RIS API by its Dokumentnummer to recover the `Entscheidungstexte` list, pick the entry whose Geschaeftszahl matches our `case_id`, then fetch that JJT's XML and extract the plain text. """ session = requests.Session() session.headers.update({"User-Agent": USER_AGENT, "Accept": "application/json"}) enriched: list[Case] = [] for i, case in enumerate(cases, 1): if case.full_text: enriched.append(case) continue text, jjt = cls._fetch_full_text(session, case) if text: meta = dict(case.metadata or {}) if jjt: meta["text_doc_num"] = jjt enriched.append(case.model_copy(update={"full_text": text, "metadata": meta})) log.info("AT enrich %d/%d %s: %d chars", i, len(cases), case.case_id, len(text)) else: enriched.append(case) log.warning("AT enrich %d/%d %s: no text", i, len(cases), case.case_id) time.sleep(ENRICH_DELAY_SECONDS) return enriched @classmethod def _fetch_full_text( cls, session: requests.Session, case: Case ) -> tuple[str | None, str | None]: doc_id = (case.metadata or {}).get("doc_id") or "" if not doc_id: return None, None jjt = cls._lookup_jjt(session, doc_id, case.case_id or "") if not jjt: return None, None xml_url = f"{RIS_DOCUMENTS_URL}/{jjt}/{jjt}.xml" try: resp = session.get(xml_url, timeout=60) resp.raise_for_status() return _extract_text_from_xml(resp.content), jjt except Exception as e: log.warning("AT JJT %s XML fetch failed (%s)", jjt, e) return None, jjt @staticmethod def _lookup_jjt(session: requests.Session, rs_doc_id: str, case_id: str) -> str | None: # Re-query the RS to get its Entscheidungstexte list, then match to case_id. # The Suchworte free-text param actually filters, Dokumentnummer does not. params = {"Applikation": "Justiz", "Suchworte": rs_doc_id} try: resp = session.get(API_URL, params=params, timeout=60) resp.raise_for_status() data = resp.json() except Exception as e: log.warning("AT RS %s lookup failed (%s)", rs_doc_id, e) return None docs = data.get("OgdSearchResult", {}).get("OgdDocumentResults", {}).get( "OgdDocumentReference", [] ) if not isinstance(docs, list): docs = [docs] if docs else [] if not docs: return None et = ( docs[0] .get("Data", {}) .get("Metadaten", {}) .get("Judikatur", {}) .get("Justiz", {}) .get("Entscheidungstexte", {}) ) items = et.get("item", []) if isinstance(items, dict): items = [items] if not items: return None norm_case = _norm_gz(case_id) for item in items: gz = _norm_gz(item.get("Geschaeftszahl", "")) if gz == norm_case: m = _JJT_NUM_RE.search(item.get("DokumentUrl", "")) if m: return m.group(1) # Fallback: first Entscheidungstext. first = items[0] m = _JJT_NUM_RE.search(first.get("DokumentUrl", "")) return m.group(1) if m else None def _norm_gz(value: str) -> str: """RIS prints `1 Ob 108/24z` in some payloads and `1Ob108/24z` in others.""" return _NORM_GZ_RE.sub("", value or "").lower() def _extract_text_from_xml(content: bytes) -> str | None: try: root = ET.fromstring(content) except ET.ParseError as e: log.warning("AT XML parse failed (%s)", e) return None parts: list[str] = [] for elem in root.iter(): if elem.text and elem.text.strip(): parts.append(elem.text.strip()) if not parts: return None return _WS_RE.sub(" ", " ".join(parts)).strip()