File size: 6,298 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 183 184 185 186 187 188 189 190 191 | """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")),
},
)
|