"""Italy Corte di Cassazione (civil sections) via the public SentenzeWeb Solr API. Endpoint and field schema discovered via the worldwidelaw/legal-sources project (AGPL-3.0). We reimplement the scraping based on this API. The SentenzeWeb index is a rolling window. As of probing in 2026 the earliest deposit-date with civil decisions (`kind:snciv`) is 2021. """ import html import logging import re from datetime import date, datetime from typing import Any from urllib.parse import urlencode import requests import urllib3 from legex.models.base import Case from legex.scrapers.base import BaseScraper log = logging.getLogger(__name__) SOLR_URL = ( "https://www.italgiure.giustizia.it/sncass/isapi/hc.dll/sn.solr/sn-collection/select" ) PAGE_SIZE = 100 FIELDS = ( "id,ocr,kind,numdec,anno,datdep,datdec,tipoprov,szdec," "presidente,relatore,materia,filename" ) urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def _first(value: Any) -> str: if isinstance(value, list): return str(value[0]) if value else "" return str(value) if value else "" def _parse_solr_date(value: Any) -> date | None: text = _first(value) if not text or len(text) < 8: return None try: if "-" in text: return date.fromisoformat(text[:10]) return datetime.strptime(text[:8], "%Y%m%d").date() except ValueError: return None _OCR_WS = re.compile(r"[ \t]+") _OCR_BLANK = re.compile(r"\n{3,}") def _clean_ocr(text: str) -> str: if not text: return "" text = html.unescape(text) text = _OCR_WS.sub(" ", text) text = _OCR_BLANK.sub("\n\n", text) return text.strip() class ITScraper(BaseScraper): country = "Italia" def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: # Iterate year by year start = start_date or date(2015, 1, 1) end = end_date or date(2025, 12, 31) session = requests.Session() session.headers.update( { "User-Agent": "legex-research (open-data, friendly)", "Accept": "application/json", } ) session.verify = False cases: list[Case] = [] seen: set[str] = set() for year in range(start.year, end.year + 1): ystart = max(date(year, 1, 1), start).strftime("%Y%m%d") yend = min(date(year, 12, 31), end).strftime("%Y%m%d") query = f"kind:snciv AND pd:[{ystart} TO {yend}]" total = self._count(session, query) log.info("IT %d hits: %d", year, total) if total == 0: continue offset = 0 while offset < total: params = { "q": query, "start": str(offset), "rows": str(PAGE_SIZE), "wt": "json", "fl": FIELDS, "sort": "pd desc", } try: resp = session.get(SOLR_URL + "?" + urlencode(params), timeout=120) resp.raise_for_status() docs = resp.json().get("response", {}).get("docs", []) except Exception as e: log.warning("IT %d offset=%d failed (%s); skipping rest of year", year, offset, e) break if not docs: break for doc in docs: case = self._to_case(doc) if case is None or case.case_id in seen: continue seen.add(case.case_id) cases.append(case) offset += len(docs) log.info("IT %d done: %d cumulative cases", year, len(cases)) cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info("Collected %d Italy civil cases", len(cases)) return cases @staticmethod def _count(session: requests.Session, query: str) -> int: params = {"q": query, "rows": "0", "wt": "json"} try: resp = session.get(SOLR_URL + "?" + urlencode(params), timeout=60) resp.raise_for_status() return int(resp.json().get("response", {}).get("numFound", 0)) except Exception as e: log.warning("IT count query failed (%s)", e) return 0 @staticmethod def _to_case(doc: dict[str, Any]) -> Case | None: doc_id = _first(doc.get("id")) numdec = _first(doc.get("numdec")) anno = _first(doc.get("anno")) if not numdec or not anno: return None case_id = f"{numdec}/{anno}" # SentenzeWeb exposes PDFs through the xway "attach" endpoint with the # filename rewritten to `.clean.pdf`. The plain `/sncass/{filename}` path # returns 404; the JS SPA constructs the URL below when a result is opened. filename = _first(doc.get("filename")) link: str | None = None if filename.endswith(".pdf"): clean_id = filename[:-4].lstrip("./") + ".clean.pdf" kind = _first(doc.get("kind")) or "snciv" link = ( "https://www.italgiure.giustizia.it/xway/application/nif/clean/hc.dll" f"?verbo=attach&db={kind}&id={clean_id}" ) decision_date = _parse_solr_date(doc.get("datdep")) or _parse_solr_date( doc.get("datdec") ) full_text = _clean_ocr(_first(doc.get("ocr"))) return Case( case_id=case_id, link=link, decision_date=decision_date, jurisdiction="it", language="it", full_text=full_text or None, metadata={ "doc_id": doc_id, "ecli": f"ECLI:IT:CASS:{anno}:{doc_id}" if doc_id and anno else "", "filename": filename, "tipoprov": _first(doc.get("tipoprov")), "szdec": _first(doc.get("szdec")), "presidente": _first(doc.get("presidente")), "relatore": _first(doc.get("relatore")), "materia": _first(doc.get("materia")), }, )