anonymous commited on
Commit ·
6f5156a
1
Parent(s): 287e418
[code] Initial release of the code.
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .env.templateAdded+20
- .gitignoreAdded+226
- LICENSEAdded+21
- README.md+88
- convert_goldenset_to_jsonl.pyAdded+212
- legex/__init__.pyAdded+1
- legex/analysis.pyAdded+388
- legex/config.pyAdded+40
- legex/evaluation.pyAdded+419
- legex/extract_raw_text.pyAdded+137
- legex/harvey.pyAdded+214
- legex/inference.pyAdded+560
- legex/main.pyAdded+37
- legex/models/__init__.pyAdded
- legex/models/base.pyAdded+14
- legex/models/classification.pyAdded+64
- legex/pdf_export/__init__.pyAdded+5
- legex/pdf_export/cli.pyAdded+119
- legex/pdf_export/core.pyAdded+127
- legex/pdf_export/font_keys.pyAdded+32
- legex/pdf_export/sheet.pyAdded+74
- legex/pdf_export/urls.pyAdded+185
- legex/pdf_export/workbook.pyAdded+30
- legex/plots.pyAdded+180
- legex/processing.pyAdded+97
- legex/prompts/__init__.pyAdded+53
- legex/prompts/v1.pyAdded+113
- legex/prompts/v2.pyAdded+86
- legex/prompts/v3.pyAdded+99
- legex/quant_results.pyAdded+295
- legex/scrape_full_text.pyAdded+183
- legex/scrapers/__init__.pyAdded+46
- legex/scrapers/al.pyAdded+363
- legex/scrapers/am.pyAdded+117
- legex/scrapers/at.pyAdded+310
- legex/scrapers/au.pyAdded+84
- legex/scrapers/base.pyAdded+30
- legex/scrapers/be.pyAdded+301
- legex/scrapers/ch.pyAdded+86
- legex/scrapers/de.pyAdded+79
- legex/scrapers/fr.pyAdded+182
- legex/scrapers/ge.pyAdded+151
- legex/scrapers/gh.pyAdded+131
- legex/scrapers/in_.pyAdded+461
- legex/scrapers/it.pyAdded+190
- legex/scrapers/kr.pyAdded+115
- legex/scrapers/li.pyAdded+222
- legex/scrapers/lu.pyAdded+181
- legex/scrapers/nz.pyAdded+214
- legex/scrapers/ph.pyAdded+117
1234567891011121314151617181920# Copy to `.env` and edit.REPO_ROOT=
# France, see PISTE JudilibreJUDILIBRE_CLIENT_ID=JUDILIBRE_CLIENT_SECRET=
# Germanay, gated HF dataset openlegaldata/court-decisions-germany)HF_TOKEN=
# Korea, set a registered law.go.kr Open API OC value.LAW_GO_KR_OC=
# New Zealand, set the token from justice.govt.nzNZ_WAF_COOKIE=# See https://docs.litellm.ai/docs/providers for the full list of env var names.OPENAI_API_KEY=ANTHROPIC_API_KEY=GEMINI_API_KEY=# ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226# Byte-compiled / optimized / DLL files__pycache__/*.py[codz]*$py.class*.pdf
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py.cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# UV# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.#uv.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control#poetry.lock#poetry.toml
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.# https://pdm-project.org/en/latest/usage/project/#working-with-version-control#pdm.lock#pdm.toml.pdm-python.pdm-build/
# pixi# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.#pixi.lock# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one# in the .venv directory. It is recommended not to include this directory in version control..pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.envrc.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.#.idea/
# Abstra# Abstra is an AI-powered process automation framework.# Ignore directories containing user credentials, local state, and settings.# Learn more at https://abstra.io/docs.abstra/
# Visual Studio Code# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore# and can be added to the global gitignore or merged into this file. However, if you prefer, # you could uncomment the following to ignore the entire vscode folder# .vscode/
# Ruff stuff:.ruff_cache/
# PyPI configuration file.pypirc
# Cursor# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data# refer to https://docs.cursor.com/context/ignore-files.cursorignore.cursorindexingignore
# Marimomarimo/_static/marimo/_lsp/__marimo__/
# Project datadata/raw/*data/processed/*data/pdf/*!data/raw/.gitkeep!data/processed/.gitkeep
# Downloaded fonts for PDF export (legex-pdf)legex/pdf_export/_fonts/
# IDE.idea.claude.DS_StorePipfile/data/cache!data/raw/harvey.xlsx123456789101112131415161718192021MIT License
Copyright (c) 2026 Anonymous Authors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091---license: mitpretty_name: "LEGEX Code: Scrapers, Inference and Evaluation Pipeline"tags: - legal - benchmark - code - llm-evaluation - information-extraction---
# LEGEX Code, Scrapers, Inference and Evaluation Pipeline
Python source for the LEGEX benchmark of civil-judgment review-tableextraction. This repository contains:
- Scrapers for 19 jurisdictions (per-court HTML / API / HuggingFace pull) in [`legex/scrapers/`](legex/scrapers/).- Inference pipeline that calls Harvey, Gemini and OpenAI APIs against a schema-constrained 14-field review table ([`legex/inference.py`](legex/inference.py), [`legex/harvey.py`](legex/harvey.py), [`legex/models/classification.py`](legex/models/classification.py)).- Evaluation that compares system outputs against expert-coded gold cells ([`legex/evaluation.py`](legex/evaluation.py)), aggregates across jurisdictions ([`legex/analysis.py`](legex/analysis.py)), and renders paper tables ([`legex/quant_results.py`](legex/quant_results.py)).- Conversion script [`convert_goldenset_to_jsonl.py`](convert_goldenset_to_jsonl.py) — turns the source XLSX goldensets into the JSONL format used by [`legexbenchmark/goldensets`](https://huggingface.co/datasets/legexbenchmark/goldensets).
## Setup
```bashgit clone https://huggingface.co/datasets/legexbenchmark/code legex-codecd legex-codeuv synccp .env.template .env```
Required tokens depend on which scrapers / models you run, see[`.env.template`](.env.template).
## End-to-end workflow
```bash# Acquire raw judgments per jurisdiction.uv run legex-run
# Run inference for one system on one jurisdiction, Harvey has do be done separately as this is a commercial tooluv run legex-classify --country us --model gpt-5.4-mini --full_text
# Evaluate one system on one jurisdiction.uv run legex-evaluate --country us --system gpt
# Aggregate across all 12 evaluated jurisdictions and 3 systems.uv run legex-analysis --out data/analysis
# Render the paper-headline LaTeX table.uv run legex-quant-results \ --input data/analysis/per_country_per_column.csv \ --out data/analysis/quant_results.tex```
To evaluate against the published goldensets and inference outputs, pullthe two data repos into the expected layout:
```bashhuggingface-cli download legexbenchmark/goldensets --repo-type dataset --local-dir data --include "data/*"huggingface-cli download legexbenchmark/inference-results --repo-type dataset --local-dir data --include "data/*"# After these, data/<cc>/ contains goldenset_<cc>.jsonl + inference_*.csvuv run legex-analysis --out data/analysis```
## CLI entrypoints
| Command | Module | Purpose ||---|---|---|| `legex-run` | `legex.main:main` | Top-level scrape + filter + sample pipeline. || `legex-classify` | `legex.inference:main` | Run an LLM over the goldenset and write predictions to CSV. || `legex-harvey-ingest` | `legex.harvey:main` | Ingest a Harvey Vault Review export into the per-jurisdiction CSV format. || `legex-evaluate` | `legex.evaluation:main` | Per-country, per-field bucket counts and recall / hallucination. || `legex-analysis` | `legex.analysis:main` | Cross-jurisdiction analysis → CSV + LaTeX tables. || `legex-quant-results` | `legex.quant_results:main` | Paper-headline summary from the analysis CSV. || `legex-pdf` | `legex.pdf_export.cli:main` | Render per-row PDFs from a goldenset workbook. || `legex-plots` | `legex.plots:main` | Plot helpers used in the paper. |
## License
MIT.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212#!/usr/bin/env python3"""Convert handcrafted Goldenset XLSX files to anonymised JSONL.
For each ``Goldenset_*_final*.xlsx`` workbook under ``<data-dir>/<cc>/`` theGOLDENSET sheet is read, rows that the expert annotator did not fullyclassify are dropped (criterion: ``legal_subject_judgement`` must bepopulated, which the annotators used as the marker that a row has beensubstantively reviewed), and the remaining rows are written to``<out-dir>/<cc>/goldenset_<cc>.jsonl`` as one JSON object per line.
Each output record contains the case identifiers (``case_id``, ``link``,``full_text``) followed by the 14 schema fields defined in``legex/models/classification.py``. ``full_text`` falls back to``<data-dir>/<cc>/full_text.jsonl`` when the XLSX cell is empty, mirroring thebehaviour of ``legex.inference._read_goldenset_cases``.
Usage----- python convert_goldenset_to_jsonl.py \ --data-dir ../data \ --out-dir ./data
Without arguments the script assumes ``./data`` for both inputs and outputs andprocesses the 19 jurisdictions of the paper."""
from __future__ import annotations
import argparseimport jsonimport sysfrom datetime import date, datetimefrom pathlib import Pathfrom typing import Any, Iterable
from openpyxl import load_workbook
JURISDICTIONS = ( "am", "au", "be", "br", "ch", "de", "es", "fr", "ge", "hk", "in", "np", "nz", "ph", "rs", "sg", "tw", "uk", "us",)
SCHEMA_FIELDS = ( "legal_subject_judgement", "trial_start_date", "trial_end_date", "dispute_value_nominal", "Currency_dispute_value_nominal", "plaintiff_loosing_share", "court_cost_awarded_nominal", "Currency_court_cost_awarded_nominal", "party_compensation_awarded_nominal", "Currency_party_compensation_awarded_nominal", "plaintiffs_all_count", "defendants_all_count", "plaintiff_no1_ISIC1_industry_category", "defendant_no1_ISIC1_industry_category",)
EMPTY_LITERALS = frozenset({"", "none", "null", "nan"})
def normalise(value: Any) -> Any: if value is None: return None if isinstance(value, datetime): return value.date().isoformat() if isinstance(value, date): return value.isoformat() if isinstance(value, float): if value != value: # NaN return None if value.is_integer(): return int(value) return value if isinstance(value, int): return value s = str(value).strip() if s.lower() in EMPTY_LITERALS: return None return s
def find_goldenset_xlsx(data_dir: Path, cc: str) -> Path | None: """Return the *_final*.xlsx workbook for a jurisdiction, if any.""" jurisdiction_dir = data_dir / cc if not jurisdiction_dir.exists(): return None matches = sorted(jurisdiction_dir.glob("*_final*.xlsx")) if not matches: matches = sorted(jurisdiction_dir.glob("*Goldenset*.xlsx")) return matches[0] if matches else None
def find_goldenset_sheet(workbook): for name in workbook.sheetnames: if name.upper().startswith("GOLDENSET"): return workbook[name] raise ValueError(f"No GOLDENSET sheet in {workbook.sheetnames}")
def load_full_text_fallback(data_dir: Path, cc: str) -> dict[str, str]: path = data_dir / cc / "full_text.jsonl" if not path.exists(): return {} fallback: dict[str, str] = {} for line in path.read_text(encoding="utf-8").splitlines(): if not line.strip(): continue record = json.loads(line) case_id = record.get("case_id") or record.get("id") text = record.get("full_text") or record.get("text") if case_id and text: fallback[str(case_id)] = str(text) return fallback
def convert_workbook(xlsx_path: Path, fallback: dict[str, str]) -> list[dict[str, Any]]: wb = load_workbook(xlsx_path, read_only=True, data_only=True) ws = find_goldenset_sheet(wb)
row_iter: Iterable[tuple] = ws.iter_rows(values_only=True) header = [str(c) if c is not None else "" for c in next(row_iter)] if "case_id" not in header: raise ValueError(f"{xlsx_path} GOLDENSET sheet missing case_id column")
records: list[dict[str, Any]] = [] for row in row_iter: if not any(row): continue cells = dict(zip(header, row)) case_id = normalise(cells.get("case_id")) if not case_id: continue labels = {field: normalise(cells.get(field)) for field in SCHEMA_FIELDS} if labels["legal_subject_judgement"] is None: continue full_text = normalise(cells.get("full_text")) if not full_text: full_text = fallback.get(str(case_id)) record: dict[str, Any] = { "case_id": str(case_id), "link": normalise(cells.get("link")), "full_text": full_text, } record.update(labels) records.append(record) return records
def write_jsonl(records: list[dict[str, Any]], out_path: Path) -> None: out_path.parent.mkdir(parents=True, exist_ok=True) with out_path.open("w", encoding="utf-8") as f: for record in records: f.write(json.dumps(record, ensure_ascii=False) + "\n")
def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument( "--data-dir", type=Path, default=Path("data"), help="Directory containing <cc>/Goldenset_*_final*.xlsx workbooks.", ) parser.add_argument( "--out-dir", type=Path, default=Path("data"), help="Directory to write goldenset_<cc>.jsonl files into (per jurisdiction).", ) parser.add_argument( "--jurisdictions", nargs="+", default=list(JURISDICTIONS), help="ISO codes to process (default: the 19 jurisdictions of the paper).", ) parser.add_argument( "--dry-run", action="store_true", help="Report counts without writing JSONL files.", ) args = parser.parse_args(argv)
data_dir: Path = args.data_dir.resolve() out_dir: Path = args.out_dir.resolve()
total = 0 missing: list[str] = [] for cc in args.jurisdictions: xlsx = find_goldenset_xlsx(data_dir, cc) if xlsx is None: missing.append(cc) print(f"[{cc}] no Goldenset XLSX found in {data_dir / cc}", file=sys.stderr) continue fallback = load_full_text_fallback(data_dir, cc) records = convert_workbook(xlsx, fallback) out_path = out_dir / cc / f"goldenset_{cc}.jsonl" if not args.dry_run: write_jsonl(records, out_path) print(f"[{cc}] {xlsx.name} -> {out_path.relative_to(out_dir.parent)}: {len(records)} rows") total += len(records)
print(f"\nTotal: {total} rows across {len(args.jurisdictions) - len(missing)} jurisdictions.") if missing: print(f"Missing XLSX for: {', '.join(missing)}", file=sys.stderr) return 1 return 0
if __name__ == "__main__": raise SystemExit(main())1"""legex — Extract structured data from legal decisions with LLMs."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388"""Cross-jurisdiction analysis of Goldenset vs prediction CSVs.
Builds on `legex.evaluation.score_country`: reuses the (tp, mismatch, missed,hallucinated, tn) per-cell buckets and exposes paper-headline aggregates —hallucination rate, recall-when-filled, miss rate — across countries, fields,models, legal traditions, and language families.
Outputs CSV + LaTeX tables under ``--out`` (default ``data/analysis``)."""
import argparseimport csvimport loggingimport reimport sysfrom collections import defaultdictfrom pathlib import Path
from legex.config import settingsfrom legex.evaluation import SYSTEMS, _BUCKETS, _derived, score_countryfrom legex.utils import evaluable_countries
log = logging.getLogger(__name__)
# Paper §A. Static maps — adding a jurisdiction = adding two entries.LEGAL_TRADITION: dict[str, str] = { "au": "common", "hk": "common", "in": "common", "nz": "common", "sg": "common", "uk": "common", "us": "common", "gh": "common", "ph": "common", "am": "civil", "at": "civil", "be": "civil", "br": "civil", "ch": "civil", "de": "civil", "es": "civil", "fr": "civil", "ge": "civil", "it": "civil", "li": "civil", "lu": "civil", "np": "civil", "rs": "civil", "tw": "civil", "xk": "civil", "al": "civil",}
LANGUAGE_FAMILY: dict[str, str] = { "au": "en-latin", "hk": "en-latin", "in": "en-latin", "nz": "en-latin", "sg": "en-latin", "uk": "en-latin", "us": "en-latin", "gh": "en-latin", "ph": "en-latin", "at": "eu-latin", "be": "eu-latin", "br": "eu-latin", "ch": "eu-latin", "de": "eu-latin", "es": "eu-latin", "fr": "eu-latin", "it": "eu-latin", "li": "eu-latin", "lu": "eu-latin", "rs": "eu-latin", "al": "eu-latin", "xk": "eu-latin", "am": "non-latin", "ge": "non-latin", "np": "non-latin", "tw": "non-latin",}
COST_BLOCK: tuple[str, ...] = ( "dispute_value_nominal", "plaintiff_loosing_share", "court_cost_awarded_nominal", "party_compensation_awarded_nominal",)
DERIVED_KEYS = ( "accuracy", "recall_when_filled", "precision_when_emitted", "hallucination_rate", "miss_rate", "wrong_when_both_filled", "f1",)
def derived_metrics(c: dict[str, int]) -> dict[str, float]: """Seven paper-headline metrics from a single bucket counter.""" tp, mism, miss, hallu, tn = c["tp"], c["mismatch"], c["missed"], c["hallucinated"], c["tn"] total = tp + mism + miss + hallu + tn filled_gold = tp + mism + miss emitted = tp + mism + hallu empty_gold = hallu + tn both_filled = tp + mism p, r, f1 = _derived(c) return { "accuracy": (tp + tn) / total if total else 0.0, "recall_when_filled": r, "precision_when_emitted": p, "hallucination_rate": hallu / empty_gold if empty_gold else 0.0, "miss_rate": miss / filled_gold if filled_gold else 0.0, "wrong_when_both_filled": mism / both_filled if both_filled else 0.0, "f1": f1, }
def add_buckets(a: dict[str, int], b: dict[str, int]) -> dict[str, int]: return {k: a.get(k, 0) + b.get(k, 0) for k in _BUCKETS}
def sum_buckets(counters: dict[str, dict[str, int]], cols: tuple[str, ...] | None = None) -> dict[str, int]: """Sum bucket counts across `cols` (or all columns when None).""" out = {k: 0 for k in _BUCKETS} for col, c in counters.items(): if cols is not None and col not in cols: continue for k in _BUCKETS: out[k] += c[k] return out
_INFERENCE_CSV_RE = re.compile(r"^inference_(.+)\.csv$")
def models_present(cc: str) -> list[str]: """Which systems have an inference_<system>.csv on disk for `cc`.""" d = settings.data_dir / cc if not d.is_dir(): return [] found: set[str] = set() for p in d.glob("inference_*.csv"): m = _INFERENCE_CSV_RE.match(p.name) if m: found.add(m.group(1)) return sorted(found)
def collect( countries: list[str], models: list[str]) -> list[tuple[str, str, dict[str, dict[str, int]]]]: """Score every (country, system) pair. Returns rows of (cc, system, counters).""" rows: list[tuple[str, str, dict[str, dict[str, int]]]] = [] for cc in countries: ms = models or models_present(cc) for model in ms: result = score_country(cc, model, verbose=False) if result is None: log.info(f"[{cc}/{model}] no scoreable data, skipping") continue counters, _coverage = result rows.append((cc, model, counters)) log.info(f"[{cc}/{model}] scored {len(counters)} columns") return rows
def _fmt(v: float) -> str: return f"{v:.4f}"
def _write_csv(path: Path, header: list[str], rows: list[dict[str, object]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with open(path, "w", encoding="utf-8", newline="") as f: w = csv.DictWriter(f, fieldnames=header, extrasaction="ignore") w.writeheader() w.writerows(rows)
def write_per_country_per_column(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None: header = ["country", "model", "column", *_BUCKETS, *DERIVED_KEYS] out_rows: list[dict[str, object]] = [] for cc, model, counters in rows: for col, c in counters.items(): d = derived_metrics(c) out_rows.append({ "country": cc, "model": model, "column": col, **c, **{k: _fmt(d[k]) for k in DERIVED_KEYS}, }) _write_csv(out / "per_country_per_column.csv", header, out_rows)
def write_per_country(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None: """One row per (cc, model): summed buckets across all label columns, plus cost-block-only summed buckets. Also adds tradition / language tags.""" header = [ "country", "model", "legal_tradition", "language_family", *_BUCKETS, *DERIVED_KEYS, *(f"cost_{k}" for k in _BUCKETS), *(f"cost_{k}" for k in DERIVED_KEYS), ] out_rows: list[dict[str, object]] = [] for cc, model, counters in rows: all_b = sum_buckets(counters) cost_b = sum_buckets(counters, COST_BLOCK) d_all = derived_metrics(all_b) d_cost = derived_metrics(cost_b) out_rows.append({ "country": cc, "model": model, "legal_tradition": LEGAL_TRADITION.get(cc, ""), "language_family": LANGUAGE_FAMILY.get(cc, ""), **all_b, **{k: _fmt(d_all[k]) for k in DERIVED_KEYS}, **{f"cost_{k}": cost_b[k] for k in _BUCKETS}, **{f"cost_{k}": _fmt(d_cost[k]) for k in DERIVED_KEYS}, }) _write_csv(out / "per_country.csv", header, out_rows)
def write_per_column(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None: """One row per (model, column): summed across countries.""" agg: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: {k: 0 for k in _BUCKETS}) for _cc, model, counters in rows: for col, c in counters.items(): for k in _BUCKETS: agg[(model, col)][k] += c[k] header = ["model", "column", *_BUCKETS, *DERIVED_KEYS] out_rows: list[dict[str, object]] = [] for (model, col), c in sorted(agg.items()): d = derived_metrics(c) out_rows.append({ "model": model, "column": col, **c, **{k: _fmt(d[k]) for k in DERIVED_KEYS}, }) _write_csv(out / "per_column.csv", header, out_rows)
def _write_grouped( out: Path, name: str, group_map: dict[str, str], rows: list[tuple[str, str, dict[str, dict[str, int]]]],) -> None: agg: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: {k: 0 for k in _BUCKETS}) cost_agg: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: {k: 0 for k in _BUCKETS}) counts: dict[tuple[str, str], int] = defaultdict(int) for cc, model, counters in rows: group = group_map.get(cc) if group is None: continue key = (model, group) all_b = sum_buckets(counters) cost_b = sum_buckets(counters, COST_BLOCK) for k in _BUCKETS: agg[key][k] += all_b[k] cost_agg[key][k] += cost_b[k] counts[key] += 1 header = [ "model", "group", "n_countries", *_BUCKETS, *DERIVED_KEYS, *(f"cost_{k}" for k in _BUCKETS), *(f"cost_{k}" for k in DERIVED_KEYS), ] out_rows: list[dict[str, object]] = [] for (model, group), c in sorted(agg.items()): cost_c = cost_agg[(model, group)] d_all = derived_metrics(c) d_cost = derived_metrics(cost_c) out_rows.append({ "model": model, "group": group, "n_countries": counts[(model, group)], **c, **{k: _fmt(d_all[k]) for k in DERIVED_KEYS}, **{f"cost_{k}": cost_c[k] for k in _BUCKETS}, **{f"cost_{k}": _fmt(d_cost[k]) for k in DERIVED_KEYS}, }) _write_csv(out / f"{name}.csv", header, out_rows)
def _latex_escape(s: str) -> str: return s.replace("\\", "\\textbackslash{}").replace("&", "\\&").replace("_", "\\_").replace("%", "\\%")
def _pct(v: float) -> str: return f"{v * 100:5.1f}\\%"
def write_headline_latex(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None: """One LaTeX `tabular` per model: rows = jurisdiction, cols = headline metrics.""" by_model: dict[str, list[tuple[str, dict[str, dict[str, int]]]]] = defaultdict(list) for cc, model, counters in rows: by_model[model].append((cc, counters))
out.mkdir(parents=True, exist_ok=True) lines: list[str] = [] for model in sorted(by_model): lines.append("% Auto-generated by legex-analysis.") lines.append("\\begin{table}[h]") lines.append( "\\caption{Headline extraction metrics by jurisdiction for model \\texttt{" f"{_latex_escape(model)}" "}. Recall when filled is over the cells where the expert recorded a value. " "False-fill rate is the share of legitimately-empty cells where the model " "invented a value.}" ) lines.append("\\label{tab:headline-" + re.sub(r"[^a-zA-Z0-9]+", "-", model).strip("-") + "}") lines.append("\\centering\\small") lines.append("\\begin{tabular}{@{}lrr@{}}") lines.append("\\toprule") lines.append("Jurisdiction & Recall when filled & False-fill rate \\\\") lines.append("\\midrule") for cc, counters in sorted(by_model[model]): d_all = derived_metrics(sum_buckets(counters)) lines.append( f"{cc.upper()} & {_pct(d_all['recall_when_filled'])} " f"& {_pct(d_all['hallucination_rate'])} \\\\" ) lines.append("\\bottomrule") lines.append("\\end{tabular}") lines.append("\\end{table}") lines.append("") (out / "headline.tex").write_text("\n".join(lines), encoding="utf-8")
def write_per_field_latex(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None: """One LaTeX table per model: rows = variable, cols = headline metrics (summed across jurisdictions).""" by_model_col: dict[str, dict[str, dict[str, int]]] = defaultdict(lambda: defaultdict(lambda: {k: 0 for k in _BUCKETS})) for _cc, model, counters in rows: for col, c in counters.items(): for k in _BUCKETS: by_model_col[model][col][k] += c[k]
out.mkdir(parents=True, exist_ok=True) lines: list[str] = [] for model in sorted(by_model_col): lines.append("% Auto-generated by legex-analysis.") lines.append("\\begin{table}[h]") lines.append( "\\caption{Per-field extraction metrics, summed across jurisdictions, for model \\texttt{" f"{_latex_escape(model)}" "}. Recall when filled is over the cells where the expert recorded a value. False-fill " "rate is the share of legitimately-empty cells where the model invented a value.}" ) lines.append("\\label{tab:per-field-" + re.sub(r"[^a-zA-Z0-9]+", "-", model).strip("-") + "}") lines.append("\\centering\\small") lines.append("\\begin{tabular}{@{}lrr@{}}") lines.append("\\toprule") lines.append("Variable & Recall when filled & False-fill rate \\\\") lines.append("\\midrule") for col, c in sorted(by_model_col[model].items()): d = derived_metrics(c) lines.append( f"\\texttt{{{_latex_escape(col)}}} " f"& {_pct(d['recall_when_filled'])} & {_pct(d['hallucination_rate'])} \\\\" ) lines.append("\\bottomrule") lines.append("\\end{tabular}") lines.append("\\end{table}") lines.append("") (out / "per_field.tex").write_text("\n".join(lines), encoding="utf-8")
def analyse( countries: list[str] | None, models: list[str] | None, out_dir: Path,) -> None: targets = countries or evaluable_countries() rows = collect(targets, models or []) if not rows: log.warning("no (country, system) pairs produced results; nothing to write") return out_dir.mkdir(parents=True, exist_ok=True) write_per_country_per_column(out_dir, rows) write_per_country(out_dir, rows) write_per_column(out_dir, rows) _write_grouped(out_dir, "per_tradition", LEGAL_TRADITION, rows) _write_grouped(out_dir, "per_language", LANGUAGE_FAMILY, rows) write_headline_latex(out_dir / "tables", rows) write_per_field_latex(out_dir / "tables", rows) log.info(f"wrote analysis for {len(rows)} (country, system) pairs to {out_dir}")
def main() -> None: logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler(sys.stderr)], ) parser = argparse.ArgumentParser( prog="legex-analysis", description="Cross-jurisdiction analysis of JSONL goldensets vs system inference CSVs.", ) parser.add_argument( "--country", action="extend", nargs="+", dest="countries", help=( "Country code(s). Repeatable. " "Default: every jurisdiction with a goldenset_<cc>.jsonl minus the " "round-2 exclusion set (BE/NP/RS plus TW/BR/HK/IN)." ), ) parser.add_argument( "--system", "--model", action="extend", nargs="+", dest="models", choices=list(SYSTEMS), help=f"Inference system(s). Repeatable. Default: every system with a CSV on disk per country ({list(SYSTEMS)}).", ) parser.add_argument( "--out", type=Path, default=Path("data/analysis"), help="Output directory (default: data/analysis).", ) args = parser.parse_args() analyse( countries=args.countries, models=args.models, out_dir=args.out, )
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940"""Runtime configuration. Override via .env."""
from datetime import datefrom pathlib import Path
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings): model_config = SettingsConfigDict(env_file=".env", extra="ignore")
date_start: date = date(2015, 1, 1) date_end: date = date(2025, 12, 31)
sample_n: int = 130 sample_seed: int = 0
judilibre_client_id: str = "" judilibre_client_secret: str = "" hf_token: str = ""
data_dir: Path = Path("data") dist_dir: Path = Path("dist")
drive_folder_url: str = ""
@property def raw_dir(self) -> Path: return self.data_dir / "raw"
@property def processed_dir(self) -> Path: return self.data_dir / "processed"
@property def template(self) -> Path: return self.data_dir / "Vorlage.xlsx"
settings = Settings()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419"""Compare Goldenset gold labels against inference output.
Reads each country's goldenset_<cc>.jsonl (the human-labelled truth, producedby ``convert_goldenset_to_jsonl.py``) and the matching ``inference_<system>.csv``file from one of the evaluated systems (``harvey``, ``gemini``, ``gpt``), thenreports per-field agreement."""
import argparseimport csvimport jsonimport loggingimport reimport sysfrom datetime import date, datetimefrom pathlib import Pathfrom typing import get_args
from legex.config import settingsfrom legex.models.classification import Classificationfrom legex.utils import ( EXCLUDED_FOR_EVAL, countries_with_goldenset_jsonl, evaluable_countries, goldenset_jsonl_path, inference_csv_path,)
# Systems whose inference outputs are evaluated.SYSTEMS: tuple[str, ...] = ("harvey", "gemini", "gpt")
log = logging.getLogger(__name__)
# Columns that don't carry a label to evaluate against (matched case-insensitively)._NON_LABEL_COLUMNS = {"case_id", "link", "full_text"}
# Goldenset / inference sentinels for “no value” (non_empty as empty)._EMPTY_LITERALS = frozenset({"", "none", "null", "nan"})
# CSV columns whose Classification field is numeric (int / float). Loose# parsing (apostrophe thousand separators, leading number + trailing prose)# applies only to these._NUMERIC_COLUMNS = frozenset( (info.alias or name) for name, info in Classification.model_fields.items() if any(a is int or a is float for a in (get_args(info.annotation) or (info.annotation,))))
_NUM_TOKEN_RE = re.compile(r"-?\d[\d',. ]*")
# CSV columns whose Classification field is a date. Separator normalisation# (treat `_`, `/`, `.` as `-`) plus a small format fallback applies only here._DATE_COLUMNS = frozenset( (info.alias or name) for name, info in Classification.model_fields.items() if any(a is date for a in (get_args(info.annotation) or (info.annotation,))))
_DATE_SEP_RE = re.compile(r"[_/.\s]+")_DATE_FALLBACK_FORMATS = ("%d-%m-%Y", "%m-%d-%Y", "%Y%m%d")
def _is_label_column(name: str) -> bool: if not name or name.lower() in _NON_LABEL_COLUMNS: return False if name.startswith("Currency_"): return False return True
def _normalise(value: object) -> str: """Make gold and prediction cells comparable as strings.""" if value is None: return "" if isinstance(value, float): if value != value: # NaN return "" if value.is_integer(): return str(int(value)) s = str(value).strip() if s.lower() in _EMPTY_LITERALS: return "" return s
def _try_float(s: str) -> float | None: if not s: return None try: return float(s) except ValueError: return None
def _parse_loose_number(s: str) -> float | None: """Extract the first numeric token from `s`, tolerating apostrophe/space thousand separators (`20'000`, `20 000`), EU decimal commas (`1.000,50`), and trailing prose (`150 GEL state fee awarded …`, `0%, motion satisfied`). Returns None when no digit appears. """ if not s: return None m = _NUM_TOKEN_RE.search(s) if not m: return None tok = m.group(0).strip().rstrip(",.' ") if not tok: return None cleaned = tok.replace("'", "").replace(" ", "") if "," in cleaned and "." in cleaned: # Whichever appears last is the decimal mark. if cleaned.rfind(",") > cleaned.rfind("."): cleaned = cleaned.replace(".", "").replace(",", ".") else: cleaned = cleaned.replace(",", "") elif "," in cleaned: parts = cleaned.split(",") # Single trailing group of 1-2 digits → decimal comma; else thousands. if len(parts) == 2 and 1 <= len(parts[1]) <= 2: cleaned = parts[0] + "." + parts[1] else: cleaned = cleaned.replace(",", "") try: return float(cleaned) except ValueError: return None
def _numeric_value(s: str, column: str | None) -> float | None: """Strict float for any column, plus loose parse for numeric columns.""" n = _try_float(s) if n is not None: return n if column in _NUMERIC_COLUMNS: return _parse_loose_number(s) return None
def _parse_loose_date(s: str) -> date | None: """Parse a date string, treating `_`, `/`, `.`, whitespace as `-`.
Accepts ISO `YYYY-MM-DD` (after separator collapse), and as a fallback `DD-MM-YYYY`, `MM-DD-YYYY`, `YYYYMMDD`. """ if not s: return None t = _DATE_SEP_RE.sub("-", s.strip()).strip("-") if not t: return None try: return date.fromisoformat(t) except ValueError: pass for fmt in _DATE_FALLBACK_FORMATS: try: return datetime.strptime(t, fmt).date() except ValueError: continue return None
def _values_agree(gv: str, pv: str, column: str | None = None) -> bool: """Compare normalised gold vs prediction cell values.""" if gv == pv: return True if column in _DATE_COLUMNS: gd, pd_ = _parse_loose_date(gv), _parse_loose_date(pv) if gd is not None and pd_ is not None and gd == pd_: return True gn = _numeric_value(gv, column) if gn is not None and gn == 0: # Gold is zero: empty pred or any zero form (0, 0.0, …) counts as match. if not pv: return True pn = _numeric_value(pv, column) return pn is not None and pn == 0 if gn is not None: pn = _numeric_value(pv, column) if pn is not None: return gn == pn return False
_BUCKETS = ("tp", "mismatch", "missed", "hallucinated", "tn")
def _classify_cell(gv: str, pv: str, column: str | None) -> str: """Bucket a (gold, pred) cell. `gv`/`pv` must already be `_normalise()`-d.
tp - gold filled, values agree mismatch - gold filled, pred filled, values differ (FP_wrong) missed - gold filled, pred empty (FN) hallucinated - gold empty, pred filled (FP on a not-filled gold field) tn - both empty """ gold_filled = bool(gv) pred_filled = bool(pv) if _values_agree(gv, pv, column): return "tp" if gold_filled else "tn" if gold_filled and pred_filled: return "mismatch" if gold_filled: return "missed" return "hallucinated"
def _derived(c: dict[str, int]) -> tuple[float, float, float]: """Per-column precision, recall, F1 from a bucket counter.""" tp, mism, miss, hallu = c["tp"], c["mismatch"], c["missed"], c["hallucinated"] p_denom = tp + mism + hallu r_denom = tp + mism + miss p = tp / p_denom if p_denom else 0.0 r = tp / r_denom if r_denom else 0.0 f1 = 2 * p * r / (p + r) if (p + r) else 0.0 return p, r, f1
def _read_goldenset_rows(cc: str) -> tuple[list[str], dict[str, dict[str, str]]]: """Return (label_columns, rows_by_case_id) for a country's JSONL goldenset.""" path = goldenset_jsonl_path(cc) if not path.exists(): raise FileNotFoundError(f"{path} does not exist")
label_columns: list[str] | None = None by_id: dict[str, dict[str, str]] = {} with path.open(encoding="utf-8") as f: for line in f: if not line.strip(): continue record = json.loads(line) if label_columns is None: label_columns = [k for k in record.keys() if _is_label_column(k)] case_id = _normalise(record.get("case_id")) if not case_id: continue labels = {col: _normalise(record.get(col)) for col in label_columns} if not any(labels.values()): continue by_id[case_id] = labels return label_columns or [], by_id
def _read_predictions(cc: str, system: str) -> dict[str, dict[str, str]]: path = inference_csv_path(cc, system) by_id: dict[str, dict[str, str]] = {} with open(path, encoding="utf-8", newline="") as f: reader = csv.DictReader(f) for row in reader: case_id = _normalise(row.get("case_id")) if not case_id: continue by_id[case_id] = {k: _normalise(v) for k, v in row.items()} return by_id
def _coverage( gold: dict[str, dict[str, str]], preds: dict[str, dict[str, str]]) -> dict[str, int]: gold_ids = set(gold) pred_ids = set(preds) overlap = len(gold_ids & pred_ids) return { "gold": len(gold_ids), "pred": len(pred_ids), "overlap": overlap, "missing": len(gold_ids - pred_ids), "extra": len(pred_ids - gold_ids), }
def score_country( cc: str, system: str, verbose: bool = True) -> tuple[dict[str, dict[str, int]], dict[str, int]] | None: """Return (per-column counters, case coverage stats) for one (country, system).""" pred_path = inference_csv_path(cc, system) gs_path = goldenset_jsonl_path(cc) if not pred_path.exists(): if verbose: log.warning(f"[{cc}/{system}] missing predictions {pred_path}, skipping") return None if not gs_path.exists(): if verbose: log.warning(f"[{cc}] missing goldenset {gs_path}, skipping") return None
label_columns, gold = _read_goldenset_rows(cc) preds = _read_predictions(cc, system) stats = _coverage(gold, preds)
counters: dict[str, dict[str, int]] = { col: {b: 0 for b in _BUCKETS} for col in label_columns } overlap_ids = [cid for cid in gold if cid in preds] if verbose: print() log.info( f"[{cc}/{system}] gold={stats['gold']} pred={stats['pred']} " f"overlap={stats['overlap']} missing={stats['missing']} extra={stats['extra']}" )
for case_id in overlap_ids: g = gold[case_id] p = preds[case_id] for col in label_columns: bucket = _classify_cell(g.get(col, ""), p.get(col, ""), col) counters[col][bucket] += 1 return counters, stats
def _print_report( cc: str, counters: dict[str, dict[str, int]], coverage: dict[str, int] | None = None) -> None: name_width = max((len(c) for c in counters), default=0) name_width = max(name_width, len("column")) print(f"=== {cc} ===") if coverage is not None: print( f"cases: gold={coverage['gold']} pred={coverage['pred']} " f"overlap={coverage['overlap']} missing={coverage['missing']} " f"extra={coverage['extra']}" ) print( f"{'column'.ljust(name_width)} " f"{'TP':>5} {'Mism':>5} {'Miss':>5} {'Hallu':>5} {'TN':>5} " f"{'P':>7} {'R':>7} {'F1':>5}" ) for col, c in counters.items(): p, r, f1 = _derived(c) f1_s = f"{f1:.2f}" if (p + r) else " - " print( f"{col.ljust(name_width)} " f"{c['tp']:>5} {c['mismatch']:>5} {c['missed']:>5} " f"{c['hallucinated']:>5} {c['tn']:>5} " f"{p:>7.2%} {r:>7.2%} {f1_s:>5}" )
def _schema_label_columns() -> list[str]: """The 14 label columns derived from the Classification pydantic model.""" return [ (info.alias or name) for name, info in Classification.model_fields.items() if _is_label_column(info.alias or name) ]
def evaluate( countries: list[str] | None, systems: list[str] | None,) -> None: overall: dict[str, dict[str, int]] = { col: {b: 0 for b in _BUCKETS} for col in _schema_label_columns() } overall_coverage = {"gold": 0, "pred": 0, "overlap": 0, "missing": 0, "extra": 0}
targets = countries or evaluable_countries() chosen_systems = systems or list(SYSTEMS)
seen_any = False for system in chosen_systems: print(f"\n########## SYSTEM: {system} ##########") for cc in targets: result = score_country(cc, system) if result is None: continue counters, coverage = result seen_any = True _print_report(f"{cc} / {system}", counters, coverage) for key in overall_coverage: overall_coverage[key] += coverage[key] for col, c in counters.items(): if col not in overall: overall[col] = {b: 0 for b in _BUCKETS} for b in _BUCKETS: overall[col][b] += c[b]
if seen_any: _print_report("ALL", overall, overall_coverage)
def main() -> None: logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler(sys.stderr)], )
parser = argparse.ArgumentParser( prog="legex-evaluate", description="Compare Goldenset JSONL labels against system inference CSV outputs.", ) parser.add_argument( "--country", action="extend", nargs="+", dest="countries", help=( "Country code(s). Repeatable and/or space-separated. " f"Defaults to the {len(SYSTEMS)}-system evaluation set " "(all jurisdictions with a goldenset JSONL minus " f"{sorted(EXCLUDED_FOR_EVAL)})." ), ) parser.add_argument( "--system", action="extend", nargs="+", dest="systems", choices=list(SYSTEMS), help=f"Inference system(s). Repeatable. Default: all of {list(SYSTEMS)}.", ) args = parser.parse_args() evaluate( countries=args.countries, systems=args.systems, )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""Extract full text from goldenset PDFs in data/raw/drive-download-*/<Country>/.
Writes data/<cc>/full_text.jsonl with fields: case_id, full_text.Text is whitespace-normalized (no newlines, runs of whitespace collapsed to one space).
Usage: uv run python -m legex.extract_raw_text uv run python -m legex.extract_raw_text --country kr"""
from __future__ import annotations
import argparseimport jsonimport loggingimport reimport sysfrom pathlib import Path
from pypdf import PdfReader
log = logging.getLogger("legex.extract_raw_text")
REPO_ROOT = Path(__file__).resolve().parent.parentRAW_DIR = REPO_ROOT / "data" / "raw"DATA_DIR = REPO_ROOT / "data"
FOLDER_TO_CC: dict[str, str] = { "Armenia": "am", "Belgium": "be", "China": "cn", "Dominican_Republic": "do", "Georgia": "ge", "Hong_Kong": "hk", "India": "in", "Nepal": "np", "New_Zealand": "nz", "Philippines": "ph", "Russia": "ru", "Singapore": "sg", "South_Korea fixed": "kr", "South_Korea": "kr", "Spain": "es", "Taiwan": "tw", "Ukraine": "ua", "United_States": "us",}
_WS_RE = re.compile(r"\s+")
def normalize_ws(text: str) -> str: return _WS_RE.sub(" ", text).strip()
def extract_pdf_text(pdf: Path) -> str: try: reader = PdfReader(str(pdf)) text = " ".join((page.extract_text() or "") for page in reader.pages) except Exception as e: log.warning(f"failed to read {pdf}: {type(e).__name__}: {e}") return "" return normalize_ws(text)
def find_country_folders() -> dict[str, list[Path]]: """Map country code -> list of PDFs found across all drive-download-* folders.""" by_cc: dict[str, list[Path]] = {} unknown: list[str] = [] for drive_dir in sorted(RAW_DIR.glob("drive-download-*")): if not drive_dir.is_dir(): continue for sub in sorted(drive_dir.iterdir()): if not sub.is_dir(): continue cc = FOLDER_TO_CC.get(sub.name) if cc is None: unknown.append(str(sub)) continue pdfs = sorted(sub.glob("*.pdf")) by_cc.setdefault(cc, []).extend(pdfs) if unknown: log.warning("unmapped folders (skipped): %s", ", ".join(unknown)) return by_cc
def write_jsonl(cc: str, pdfs: list[Path]) -> Path: out_dir = DATA_DIR / cc out_dir.mkdir(parents=True, exist_ok=True) out_path = out_dir / "full_text.jsonl" with out_path.open("w", encoding="utf-8") as f: for pdf in pdfs: text = extract_pdf_text(pdf) f.write(json.dumps({"case_id": pdf.stem, "full_text": text}, ensure_ascii=False)) f.write("\n") return out_path
def main() -> int: logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") ap = argparse.ArgumentParser(description=__doc__) ap.add_argument( "--country", "-c", action="append", help="Only process the given country code (repeatable). Default: all.", ) args = ap.parse_args()
if not RAW_DIR.exists(): log.error("raw dir not found: %s", RAW_DIR) return 1
by_cc = find_country_folders() if args.country: wanted = {c.lower() for c in args.country} by_cc = {cc: pdfs for cc, pdfs in by_cc.items() if cc in wanted} missing = wanted - set(by_cc) if missing: log.error("no PDFs found for: %s", ", ".join(sorted(missing))) return 1
if not by_cc: log.error("no country folders matched") return 1
for cc in sorted(by_cc): pdfs = by_cc[cc] log.info("[%s] extracting %d PDFs", cc, len(pdfs)) out = write_jsonl(cc, pdfs) log.info("[%s] wrote %s", cc, out) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214"""Ingest Harvey-AI extractions from a single xlsx into per-country CSVs.
`data/raw/harvey.xlsx` (Sheet1) holds Harvey's outputs for 23 jurisdictionswith 4 columns per question (Value / Reasoning / Citations / Comments). Wekeep only the Value columns, clean them, match each row to a Goldensetcase_id via the PDF filename, and write a CSV that looks exactly like theoutput of `legex.inference` — so `legex-evaluate`, `legex-analysis`, and`legex-plots` treat Harvey as just another model."""
import argparseimport csvimport loggingimport reimport sysfrom collections import defaultdictfrom pathlib import Path
from openpyxl import load_workbook
from legex.config import settingsfrom legex.inference import _output_columnsfrom legex.utils import ( classified_csv_path, goldenset_path, goldenset_sheet, norm_case_id,)
log = logging.getLogger(__name__)
HARVEY_FOLDER_TO_CC: dict[str, str] = { "Armenia": "am", "Australia": "au", "Belgium": "be", "Brazil": "br", "China": "cn", "Dominican_Republic": "do", "France": "fr", "Georgia": "ge", "Germany": "de", "Hong_Kong": "hk", "India": "in", "Nepal": "np", "New_Zealand": "nz", "Philippines": "ph", "Russia": "ru", "Schweiz_final": "ch", "Singapore": "sg", "South_Korea fixed": "kr", "Spain": "es", "Taiwan": "tw", "Ukraine": "ua", "United_Kingdom": "uk", "United_States": "us",}
# Harvey Sheet1 value-column index → Goldenset header name.HARVEY_COL_TO_GOLD: dict[int, str] = { 7: "legal_subject_judgement", 11: "trial_start_date", 15: "trial_end_date", 19: "dispute_value_nominal", 23: "plaintiff_loosing_share", 27: "court_cost_awarded_nominal", 31: "party_compensation_awarded_nominal", 35: "plaintiffs_all_count", 39: "defendants_all_count", 43: "plaintiff_no1_ISIC1_industry_category", 47: "defendant_no1_ISIC1_industry_category",}
_CITATION_RE = re.compile(r"\s*(?:\[\d+\])+\s*$")_EMPTY_LITERALS = {"", "—"}
def _clean(value: object) -> str: if value is None: return "" s = str(value).strip() if s in _EMPTY_LITERALS: return "" s = _CITATION_RE.sub("", s).strip() if s.lower() == "nonpecuniary": return "nonpecuniary" return s
def _gold_case_id_index(cc: str) -> dict[str, str] | None: """{ norm_case_id(gold) → gold case_id } for one country, or None if no Goldenset.""" gs = goldenset_path(cc) if not gs.exists(): return None wb = load_workbook(gs, read_only=True, data_only=True) ws = goldenset_sheet(wb) rows = ws.iter_rows(values_only=True) header = [str(c) if c is not None else "" for c in next(rows)] try: cid_idx = header.index("case_id") except ValueError as e: raise ValueError(f"{gs}: GOLDENSET sheet has no case_id column") from e index: dict[str, str] = {} for row in rows: if not any(row): continue raw = row[cid_idx] if raw is None: continue gold = str(raw).strip() if not gold: continue index.setdefault(norm_case_id(gold), gold) return index
def ingest( xlsx: Path, prompt_version: str = "v3", source: str = "full_text", model: str = "harvey",) -> None: columns = _output_columns() wb = load_workbook(xlsx, read_only=True, data_only=True) if "Sheet1" not in wb.sheetnames: raise ValueError(f"{xlsx} missing Sheet1 (found {wb.sheetnames})") ws = wb["Sheet1"] rows_iter = ws.iter_rows(values_only=True) next(rows_iter) # skip header
by_folder: dict[str, list[tuple]] = defaultdict(list) for row in rows_iter: if not row or row[0] is None: continue folder = row[1] if folder is None: continue by_folder[str(folder)].append(row)
for folder, rows in by_folder.items(): cc = HARVEY_FOLDER_TO_CC.get(folder) if cc is None: log.warning(f"unknown folder {folder!r}, skipping {len(rows)} row(s)") continue index = _gold_case_id_index(cc) if index is None: log.info(f"[{cc}] no Goldenset on disk, skipping {len(rows)} Harvey row(s)") continue
out = classified_csv_path(cc, prompt_version, source, model) out.parent.mkdir(parents=True, exist_ok=True)
matched = 0 unmatched = 0 with open(out, "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=columns, extrasaction="ignore") writer.writeheader() for row in rows: stem = Path(str(row[0])).stem gold = index.get(norm_case_id(stem)) if gold is None: unmatched += 1 log.info(f"[{cc}] no Goldenset match for {row[0]!r}") continue out_row = {col: "" for col in columns} out_row["case_id"] = gold out_row["model"] = model for harvey_idx, gold_col in HARVEY_COL_TO_GOLD.items(): if harvey_idx < len(row): out_row[gold_col] = _clean(row[harvey_idx]) writer.writerow(out_row) matched += 1 log.info( f"[{cc}] wrote {matched} Harvey row(s) → {out} " f"({unmatched} unmatched, {len(rows)} total)" )
def main() -> None: logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler(sys.stderr)], ) parser = argparse.ArgumentParser( prog="legex-harvey-ingest", description="Convert data/raw/harvey.xlsx into per-country Goldenset_*_harvey.csv files.", ) parser.add_argument( "--xlsx", type=Path, default=settings.raw_dir / "harvey.xlsx", help="Path to harvey.xlsx (default: data/raw/harvey.xlsx).", ) parser.add_argument("--prompt_version", default="v3") parser.add_argument( "--source", choices=("full_text", "pdf"), default="full_text", help="Source bucket label used in the CSV filename (default: full_text).", ) parser.add_argument("--model", default="harvey", help="Model slug for the CSV filename.") args = parser.parse_args() ingest( xlsx=args.xlsx, prompt_version=args.prompt_version, source=args.source, model=args.model, )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560"""LLM inference over Goldenset full_text or per-country PDFs.
For each registered country, reads case inputs from either:- the `full_text` column of `data/<cc>/Goldenset_*.xlsx`, or- the PDFs at `data/<cc>/*.pdf`
runs an LLM with the Vorlage coding rules, and appends a CSV of predictionsto `data/<cc>/Goldenset_{country}_{prompt_version}_{full_text|pdf}_{model}.csv`.Successful rows (by case_id) are skipped; rows with a non-empty `error`column are retried on the next run."""
import argparseimport asyncioimport csvimport jsonimport loggingimport osimport sysimport threadingimport timefrom collections.abc import Callablefrom datetime import datefrom pathlib import Path
from dotenv import load_dotenvfrom openpyxl import load_workbook
from legex.config import settingsfrom legex.models.base import Casefrom legex.models.classification import Classificationfrom legex.prompts import PromptPlan, load_planfrom legex.scrapers import SCRAPERSfrom legex.utils import ( classified_csv_path, countries_with_goldenset, goldenset_path, goldenset_sheet, load_coding_rules, load_goldenset_columns, load_isic_categories, norm_case_id, pdf_paths, read_full_text_jsonl,)
log = logging.getLogger(__name__)
_DATE_FIELD_KEYS: frozenset[str] = frozenset( name for name, info in Classification.model_fields.items() if date in getattr(info.annotation, "__args__", (info.annotation,)))
def _coerce_json_dates(data: dict) -> None: """JSON has no date type; convert strings before pydantic validation.""" for key in _DATE_FIELD_KEYS: if key not in data: continue val = data[key] if isinstance(val, str) and val: data[key] = date.fromisoformat(val)
def _parse_classification(content: str) -> Classification: """Parse LLM JSON; accept a one-element array when the model returns a list.""" data = json.loads(content) if isinstance(data, list): if len(data) != 1 or not isinstance(data[0], dict): raise ValueError("expected a JSON object or a one-element array of objects") data = data[0] _coerce_json_dates(data) return Classification.model_validate(data)
class _RequestRateLimiter: """Minimum spacing between LLM calls (60 / rpm seconds). None rpm = no limit."""
def __init__(self, rpm: int | None) -> None: self._min_interval = 60.0 / rpm if rpm else 0.0 self._last_at = 0.0 self._sync_lock = threading.Lock() self._async_lock: asyncio.Lock | None = None
def acquire(self) -> None: if self._min_interval <= 0: return with self._sync_lock: now = time.monotonic() wait = self._min_interval - (now - self._last_at) if wait > 0: time.sleep(wait) self._last_at = time.monotonic()
async def acquire_async(self) -> None: if self._min_interval <= 0: return if self._async_lock is None: self._async_lock = asyncio.Lock() async with self._async_lock: now = time.monotonic() wait = self._min_interval - (now - self._last_at) if wait > 0: await asyncio.sleep(wait) self._last_at = time.monotonic()
def inference_output_path(cc: str, prompt_version: str, source: str, model: str) -> Path: return classified_csv_path(cc, prompt_version, source, model)
# CSV columns (and GOLDENSET headers) use the alias when one is set,# e.g. `Currency_dispute_value_nominal` (capital C). The Python attribute# is the lowercase model field name. These maps move between the two._FIELD_TO_COL: dict[str, str] = { name: (info.alias or name) for name, info in Classification.model_fields.items()}_COL_TO_FIELD: dict[str, str] = {col: field for field, col in _FIELD_TO_COL.items()}
def _output_columns() -> list[str]: headers = load_goldenset_columns(settings.template) return [h for h in headers if h != "full_text"] + ["model", "error"]
def _read_goldenset_cases(cc: str) -> list[Case]: """Pull case_id / link / full_text rows from the GOLDENSET sheet.
Falls back to data/<cc>/full_text.jsonl (keyed by case_id) when the xlsx full_text column is empty or absent, so jurisdictions whose text doesn't fit in Excel can still be classified. """ path = goldenset_path(cc) wb = load_workbook(path, read_only=True, data_only=True) ws = goldenset_sheet(wb) rows = ws.iter_rows(values_only=True) header = [str(c) if c is not None else "" for c in next(rows)] idx = {h.strip().lower(): i for i, h in enumerate(header) if h} for required in ("case_id", "link"): if required not in idx: raise ValueError(f"{path} GOLDENSET sheet missing column {required!r}") full_text_idx = idx.get("full_text") fallback = read_full_text_jsonl(cc) if full_text_idx is None and not fallback: raise ValueError( f"{path} GOLDENSET sheet has no full_text column and no " f"data/{cc}/full_text.jsonl fallback" )
cases: list[Case] = [] n_from_jsonl = 0 for row in rows: if not any(row): continue case_id = row[idx["case_id"]] link = row[idx["link"]] full_text = row[full_text_idx] if full_text_idx is not None else None if not full_text and case_id is not None: cid_s = str(case_id) fb = fallback.get(cid_s) or fallback.get(norm_case_id(cid_s)) if fb: full_text = fb n_from_jsonl += 1 cases.append( Case( case_id=str(case_id) if case_id is not None else None, link=str(link) if link is not None else None, jurisdiction=cc, full_text=str(full_text) if full_text is not None else None, ) ) if n_from_jsonl: log.info(f"[{cc}] using full_text from full_text.jsonl for {n_from_jsonl} case(s)") return cases
def _read_pdf_cases(cc: str) -> list[Case]: """One Case per PDF at data/<cc>/*.pdf; case_id = file stem.""" from pypdf import PdfReader
cases: list[Case] = [] for pdf in pdf_paths(cc): try: reader = PdfReader(str(pdf)) text = "\n".join((page.extract_text() or "") for page in reader.pages) except Exception as e: log.warning(f"[{cc}] failed to read {pdf.name}: {type(e).__name__}: {e}") text = "" cases.append( Case( case_id=pdf.stem, link=str(pdf), jurisdiction=cc, full_text=text or None, ) ) return cases
def _read_cases(cc: str, source: str) -> list[Case]: if source == "full_text": return _read_goldenset_cases(cc) return _read_pdf_cases(cc)
def _empty_row(case: Case, model: str, columns: list[str]) -> dict[str, str]: row: dict[str, str] = {col: "" for col in columns} row["case_id"] = case.case_id or "" row["link"] = case.link or "" row["model"] = model return row
async def _classify_case_single( case: Case, system_prompt: str, model: str, columns: list[str], limiter: _RequestRateLimiter,) -> dict[str, str]: import litellm
row = _empty_row(case, model, columns) if not case.full_text: row["error"] = "no full_text" return row
try: await limiter.acquire_async() resp = await litellm.acompletion( model=model, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": case.full_text}, ], response_format=Classification, ) content = resp["choices"][0]["message"]["content"] parsed = _parse_classification(content) except Exception as e: row["error"] = f"{type(e).__name__}: {e}" return row
extras = [col for col in _FIELD_TO_COL.values() if col not in row] if extras: row["error"] = f"Classification fields not in GOLDENSET header: {extras}" return row for field, col in _FIELD_TO_COL.items(): value = getattr(parsed, field) row[col] = "" if value is None else str(value) return row
async def _classify_one_column( column: str, system_prompt: str, full_text: str, model: str, limiter: _RequestRateLimiter,) -> tuple[str, object | None, str | None]: """Return (CSV column, value, error). `column` is the CSV header name (alias-aware); we read the corresponding Python attribute off the parsed Classification.""" import litellm
try: await limiter.acquire_async() resp = await litellm.acompletion( model=model, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": full_text}, ], response_format={"type": "json_object"}, ) content = resp["choices"][0]["message"]["content"] parsed = _parse_classification(content) field = _COL_TO_FIELD.get(column, column) return column, getattr(parsed, field), None except Exception as e: return column, None, f"{column}: {type(e).__name__}: {e}"
async def _classify_case_per_column( case: Case, column_systems: dict[str, str], model: str, columns: list[str], limiter: _RequestRateLimiter,) -> dict[str, str]: row = _empty_row(case, model, columns) if not case.full_text: row["error"] = "no full_text" return row
extras = [c for c in column_systems if c not in row] if extras: row["error"] = f"Per-column prompts target fields not in GOLDENSET header: {extras}" return row
results = await asyncio.gather( *( _classify_one_column(col, sys_prompt, case.full_text, model, limiter) for col, sys_prompt in column_systems.items() ) ) errors: list[str] = [] for col, value, err in results: if err is not None: errors.append(err) elif value is not None: row[col] = str(value) if errors: row["error"] = "; ".join(errors) return row
class _CsvRowWriter: """Append rows to a CSV, flushing after each write."""
def __init__(self, path: Path, columns: list[str]) -> None: path.parent.mkdir(parents=True, exist_ok=True) write_header = not path.exists() self._file = open(path, "a", encoding="utf-8", newline="") self._writer = csv.DictWriter(self._file, fieldnames=columns) if write_header: self._writer.writeheader()
def write_row(self, row: dict[str, str]) -> None: self._writer.writerow(row) self._file.flush()
def close(self) -> None: self._file.close()
def __enter__(self) -> "_CsvRowWriter": return self
def __exit__(self, *args: object) -> None: self.close()
def _classify_cases( cases: list[Case], plan: PromptPlan, model: str, columns: list[str], limiter: _RequestRateLimiter, write_row: Callable[[dict[str, str]], None], concurrency: int = 1,) -> int: """Classify cases and stream each result via write_row. Returns success count.
With concurrency > 1, up to N cases are processed in parallel; the rate limiter still gates total request throughput. Rows are written as each case finishes, so output order is non-deterministic when concurrency > 1. """
async def run_all() -> int: sem = asyncio.Semaphore(max(1, concurrency))
async def process(case: Case) -> dict[str, str]: async with sem: if plan.mode == "single": return await _classify_case_single( case, plan.system or "", model, columns, limiter ) return await _classify_case_per_column( case, plan.column_systems or {}, model, columns, limiter )
ok = 0 for coro in asyncio.as_completed([process(c) for c in cases]): row = await coro write_row(row) if not row["error"]: ok += 1 return ok
return asyncio.run(run_all())
def _successful_case_ids(path: Path) -> set[str]: if not path.exists(): return set() ids: set[str] = set() with open(path, encoding="utf-8", newline="") as f: for r in csv.DictReader(f): if (r.get("error") or "").strip(): continue cid = (r.get("case_id") or "").strip() if cid: ids.add(cid) return ids
def _drop_case_ids(path: Path, columns: list[str], case_ids: set[str]) -> int: """Remove rows for the given case_ids. Returns number of rows removed.""" if not path.exists() or not case_ids: return 0 with open(path, encoding="utf-8", newline="") as f: rows = list(csv.DictReader(f)) kept = [r for r in rows if (r.get("case_id") or "").strip() not in case_ids] removed = len(rows) - len(kept) if removed == 0: return 0 with open(path, "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=columns, extrasaction="ignore") writer.writeheader() writer.writerows(kept) return removed
def classify( countries: list[str] | None, model: str, source: str, prompt_version: str, limit: int | None, rpm: int | None = None, concurrency: int = 1,) -> None: rules = load_coding_rules(settings.template) isic = load_isic_categories(settings.template) columns = _output_columns() plan = load_plan(prompt_version, rules, isic) limiter = _RequestRateLimiter(rpm) if rpm: log.info(f"Rate limit: {rpm} requests/min ({limiter._min_interval:.2f}s between calls)") if concurrency > 1: log.info(f"Concurrency: up to {concurrency} cases in parallel")
targets = countries or countries_with_goldenset() or list(SCRAPERS) for cc in targets: if source == "full_text": gs = goldenset_path(cc) if not gs.exists(): log.warning(f"[{cc}] missing {gs}, skipping") continue else: if not pdf_paths(cc): log.warning(f"[{cc}] no PDFs at {settings.data_dir / cc}/*.pdf, skipping") continue
cases = _read_cases(cc, source) if not cases: log.info(f"[{cc}] no cases found, skipping") continue
out = inference_output_path(cc, prompt_version, source, model) done = _successful_case_ids(out) todo = [c for c in cases if (c.case_id or "") not in done] if limit is not None: todo = todo[:limit] if not todo: log.info(f"[{cc}] all {len(cases)} cases already classified in {out}, skipping") continue
retry_ids = {c.case_id for c in todo if c.case_id} n_removed = _drop_case_ids(out, columns, retry_ids) n_new = len(todo) - n_removed if n_removed: log.info(f"[{cc}] retrying {n_removed} failed case(s), {n_new} new")
log.info( f"[{cc}] classifying {len(todo)} cases ({len(done)} already done) " f"in {plan.mode} mode → {out}" ) with _CsvRowWriter(out, columns) as writer: n_ok = _classify_cases( todo, plan, model, columns, limiter, writer.write_row, concurrency ) log.info(f"[{cc}] classified {n_ok}/{len(todo)} → {out}")
def main() -> None: logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler(sys.stderr)], ) load_dotenv(override=True) print(f"gemini key {os.environ.get('GEMINI_API_KEY')}") # sanity check for env var
parser = argparse.ArgumentParser( prog="legex-classify", description="Run LLM inference over Goldenset full_text or per-country PDFs.", ) parser.add_argument( "--country", action="extend", nargs="+", dest="countries", help="Country code (repeatable). Defaults to all registered scrapers.", ) parser.add_argument( "--model", default="gpt-4o-mini", help="litellm model id (e.g. gpt-4o-mini, anthropic/claude-opus-4-7).", ) parser.add_argument( "--prompt_version", default="v1", help="Prompt version under legex/prompts/ (default: v1).", ) parser.add_argument( "--limit", type=int, default=None, help="Cap NEW cases per country (useful for cheap dry runs).", ) parser.add_argument( "--rpm", type=int, default=None, metavar="N", help="Max LLM requests per minute (applies to every completion call).", ) parser.add_argument( "--concurrency", type=int, default=1, metavar="N", help="Process up to N cases in parallel (default: 1).", ) source = parser.add_mutually_exclusive_group(required=True) source.add_argument( "--full_text", dest="source", action="store_const", const="full_text", help="Read input from the full_text column of data/<cc>/Goldenset_*.xlsx.", ) source.add_argument( "--pdf", dest="source", action="store_const", const="pdf", help="Read input from data/<cc>/*.pdf.", ) args = parser.parse_args() if args.rpm is not None and args.rpm <= 0: parser.error("--rpm must be a positive integer") if args.concurrency <= 0: parser.error("--concurrency must be a positive integer")
classify( countries=args.countries, model=args.model, source=args.source, prompt_version=args.prompt_version, limit=args.limit, rpm=args.rpm, concurrency=args.concurrency, )
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637"""Run the full pipeline: scrape → filter_and_sample → fill_goldenset → dist."""
import argparseimport loggingimport sysfrom dotenv import load_dotenv
from legex.processing import dist, fill_goldenset, filter_and_sample, scrape
def main() -> None: logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler(sys.stderr)], ) load_dotenv()
parser = argparse.ArgumentParser( prog="legex-run", description="Run the legex pipeline (scrape → filter_and_sample → fill_goldenset → dist).", ) parser.add_argument( "-f", "--force", action="store_true", help="Recreate all artefacts, overwriting cached outputs at every stage.", ) args = parser.parse_args()
scrape(force=args.force) filter_and_sample(force=args.force) fill_goldenset(force=args.force) dist(force=args.force)
if __name__ == "__main__": main()1234567891011121314from datetime import datefrom typing import Any
from pydantic import BaseModel
class Case(BaseModel): case_id: str | None = None link: str | None = None decision_date: date | None = None jurisdiction: str # ISO country code: "ch", "fr", etc. language: str | None = None # ISO 639-1: "de", "fr", "it", "en" full_text: str | None = None # populated in jsonl mode only metadata: dict[str, Any] = {} # jurisdiction-specific extra fields12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364from datetime import datefrom typing import Literal
from pydantic import BaseModel, ConfigDict, Field
class Classification(BaseModel): """LLM-extracted variables for a single legal case.
Strict typing: numbers are numbers, dates are dates. The LLM must return native JSON types — no string-wrapped numerics. """
model_config = ConfigDict(strict=True, populate_by_name=True)
legal_subject_judgement: str | None = Field( default=None, description="Legal subject of the case (English, formatted)." ) trial_start_date: date | None = Field( default=None, description="Trial start date (YYYY-MM-DD)." ) trial_end_date: date | None = Field( default=None, description="Trial end (decision) date (YYYY-MM-DD)." ) dispute_value_nominal: float | Literal["nonpecuniary"] | None = Field( default=None, description="Amount in dispute as a number, or the literal string 'nonpecuniary'.", ) currency_dispute_value_nominal: str | None = Field( default=None, alias="Currency_dispute_value_nominal", description="ISO-4217 currency code for the dispute value (e.g. CHF).", ) plaintiff_loosing_share: float | None = Field( default=None, description="Plaintiff's losing share between 0.0 and 1.0." ) court_cost_awarded_nominal: float | None = Field( default=None, description="Total court fees as a number." ) currency_court_cost_awarded_nominal: str | None = Field( default=None, alias="Currency_court_cost_awarded_nominal", description="ISO-4217 currency code for the court fees.", ) party_compensation_awarded_nominal: float | None = Field( default=None, description="Total party compensation as a number." ) currency_party_compensation_awarded_nominal: str | None = Field( default=None, alias="Currency_party_compensation_awarded_nominal", description="ISO-4217 currency code for party compensation.", ) plaintiffs_all_count: int | None = Field( default=None, description="Number of plaintiffs." ) defendants_all_count: int | None = Field( default=None, description="Number of defendants." ) plaintiff_no1_ISIC1_industry_category: str | None = Field( default=None, description="ISIC sector for the first plaintiff." ) defendant_no1_ISIC1_industry_category: str | None = Field( default=None, description="ISIC sector for the first defendant." )12345"""Export goldenset rows to PDF (sheet text or fetched from URLs)."""
__all__ = ["ensure_fonts"]
from legex.pdf_export.core import ensure_fonts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""CLI: ``legex-pdf sheet`` (table only) and ``legex-pdf urls`` (HTTP + fallback)."""
from __future__ import annotations
import argparseimport sysfrom pathlib import Path
from dotenv import load_dotenv
from legex.config import settingsfrom legex.pdf_export.core import ensure_fontsfrom legex.pdf_export.sheet import export_workbook as export_sheet_workbookfrom legex.pdf_export.urls import collect_workbooks, export_workbook as export_urls_workbookfrom legex.pdf_export.workbook import discover_goldensets
def _data_dir(ns: argparse.Namespace) -> Path: if getattr(ns, "data_dir", None): return Path(ns.data_dir).expanduser().resolve() return settings.data_dir.expanduser().resolve()
def _cmd_sheet(ns: argparse.Namespace) -> int: data_dir = _data_dir(ns) files = discover_goldensets(data_dir) if not ns.input_dir else _files_from_input_dirs(ns.input_dir) if not files: print("Keine Goldenset_*.xlsx gefunden.", file=sys.stderr) return 1 out = data_dir / "pdf" / "from_sheet" out.mkdir(parents=True, exist_ok=True) ensure_fonts() print(f"→ {len(files)} Workbooks → {out}\n", flush=True) total = 0 for xlsx in files: print(xlsx, flush=True) total += export_sheet_workbook(xlsx, out, limit=ns.limit) print(f"Insgesamt PDFs: {total}") return 0
def _cmd_urls(ns: argparse.Namespace) -> int: data_dir = _data_dir(ns) input_dirs = [Path(p).expanduser().resolve() for p in ns.input_dir] if ns.input_dir else None files = collect_workbooks(data_dir, input_dirs) if not files: print("Keine Goldenset_*.xlsx gefunden.", file=sys.stderr) return 1 out = data_dir / "pdf" / "from_urls" out.mkdir(parents=True, exist_ok=True) ensure_fonts() mode = "explizite --input-dir" if input_dirs else f"unter {data_dir}" print(f"→ {len(files)} Workbooks ({mode}) → {out}\n", flush=True) total = 0 for xlsx in files: print(xlsx, flush=True) total += export_urls_workbook( xlsx, out, pause_s=ns.pause, limit=ns.limit, req_timeout=ns.timeout, resume=ns.resume, ) print(f"Insgesamt PDFs: {total}") return 0
def _files_from_input_dirs(paths: list[str]) -> list[Path]: files: list[Path] = [] for raw in paths: d = Path(raw).expanduser().resolve() if not d.is_dir(): print("Ordner fehlt:", d, file=sys.stderr) continue files.extend(sorted(d.glob("Goldenset_*.xlsx"))) return sorted(files, key=lambda p: (p.stem.lower(), str(p)))
def main() -> None: load_dotenv() ap = argparse.ArgumentParser(prog="legex-pdf") ap.add_argument( "--data-dir", type=Path, default=None, help="Daten-Root (Default: settings.data_dir, per .env z. B. DATA_DIR)", ) sub = ap.add_subparsers(dest="command", required=True)
p_sheet = sub.add_parser("sheet", help="PDF aus Spalte full_text (ohne HTTP)") p_sheet.add_argument("--limit", type=int, default=None, help="Max. PDFs pro Workbook") p_sheet.add_argument( "--input-dir", action="append", dest="input_dir", help="Ordner mit Goldenset_*.xlsx (mehrfach möglich); sonst data_dir/*/Goldenset_*.xlsx", ) p_sheet.set_defaults(_run=_cmd_sheet)
p_urls = sub.add_parser("urls", help="PDF aus URL-Fetch, Fallback full_text") p_urls.add_argument("--timeout", type=float, default=28.0, help="HTTP-Timeout (Sek.)") p_urls.add_argument("--pause", type=float, default=0.25, help="Pause zwischen Requests (Sek.)") p_urls.add_argument("--limit", type=int, default=None, help="Max. PDFs pro Workbook (inkl. Resume)") p_urls.add_argument("--resume", action="store_true", help="Vorhandene PDFs nicht überschreiben") p_urls.add_argument( "--input-dir", action="append", dest="input_dir", help="Ordner mit Goldenset_*.xlsx; sonst data_dir/*/Goldenset_*.xlsx", ) p_urls.set_defaults(_run=_cmd_urls)
ns = ap.parse_args() raise SystemExit(ns._run(ns))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""Font download, sanitization, and FPDF writing."""
from __future__ import annotations
import hashlibimport reimport urllib.requestfrom pathlib import Path
from fpdf import FPDFfrom fpdf.enums import Align, WrapMode
FONT_DIR = Path(__file__).resolve().parent / "_fonts"
FONT_URLS = { "NotoSans-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf", "SourceHanSansSC-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/SimplifiedChinese/SourceHanSansSC-Regular.otf", "SourceHanSansK-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/Korean/SourceHanSansK-Regular.otf",}
EXTRA_FONT_URLS = { "SourceHanSansTC-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/TraditionalChinese/SourceHanSansTC-Regular.otf", "NotoSansDevanagari-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansDevanagari/NotoSansDevanagari-Regular.ttf", "NotoSansArmenian-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansArmenian/NotoSansArmenian-Regular.ttf", "NotoSansGeorgian-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansGeorgian/NotoSansGeorgian-Regular.ttf",}
def ensure_fonts() -> None: FONT_DIR.mkdir(parents=True, exist_ok=True) all_fonts = {**FONT_URLS, **EXTRA_FONT_URLS} for name, url in all_fonts.items(): dest = FONT_DIR / name if dest.exists() and dest.stat().st_size > 1000: continue print(f"Downloading font {name} …", flush=True) req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) with urllib.request.urlopen(req, timeout=600) as r, open(dest, "wb") as f: f.write(r.read())
def sanitize_pdf_text(s: str) -> str: s = str(s).replace("\t", " ").replace("\r\n", "\n").replace("\r", "\n") s = s.replace("\uf0b7", "•").replace("\uf0a7", "•").replace("\uf0d8", "•") s = s.replace("\uf02d", "–") return s
def safe_slug(case_id: str | None, link: str | None, row_idx: int) -> str: raw = (case_id or "").strip() if not raw: h = hashlib.sha256(((link or "") + str(row_idx)).encode("utf-8")).hexdigest()[:12] raw = f"decision_{row_idx}_{h}" raw = raw.replace("\n", " ").strip() raw = re.sub(r'[\x00-\x1f<>:"/\\|?*]', "_", raw) raw = re.sub(r"\s+", "_", raw) raw = raw.strip("._") or f"row_{row_idx}" if len(raw) > 120: raw = raw[:120].rstrip("_") return raw
class UnicodePDF(FPDF): pass
def pdf_font_setup(pdf: FPDF, key: str) -> str: if key == "han_sc": pdf.add_font("HanSC", "", str(FONT_DIR / "SourceHanSansSC-Regular.otf")) return "HanSC" if key == "han_tc": pdf.add_font("HanTC", "", str(FONT_DIR / "SourceHanSansTC-Regular.otf")) return "HanTC" if key == "han_k": pdf.add_font("HanK", "", str(FONT_DIR / "SourceHanSansK-Regular.otf")) return "HanK" if key == "deva": pdf.add_font("Deva", "", str(FONT_DIR / "NotoSansDevanagari-Regular.ttf")) return "Deva" if key == "arm": pdf.add_font("Arm", "", str(FONT_DIR / "NotoSansArmenian-Regular.ttf")) return "Arm" if key == "geo": pdf.add_font("Geo", "", str(FONT_DIR / "NotoSansGeorgian-Regular.ttf")) return "Geo" pdf.add_font("NotoSans", "", str(FONT_DIR / "NotoSans-Regular.ttf")) return "NotoSans"
def write_one_pdf( path: Path, case_id: str, link: str, body: str, font_key: str, *, text_source: str | None = None,) -> None: path.parent.mkdir(parents=True, exist_ok=True) pdf = UnicodePDF() pdf.set_auto_page_break(auto=True, margin=14) pdf.set_left_margin(14) pdf.set_right_margin(14) pdf.add_page() # Use one font for meta + body when the script is non-Latin: case_id often # contains Hangul etc., and NotoSans would miss those glyphs in the header. if font_key == "default": text_family = pdf_font_setup(pdf, "default") else: text_family = pdf_font_setup(pdf, font_key) pdf.set_font(text_family, size=11) head = [f"case_id: {case_id}", f"link: {link}"] if text_source: head.append(f"Quelle Text: {text_source}") head.append("") meta = sanitize_pdf_text("\n".join(head)) # Latin header: WORD wrap; CJK header lines are short — WORD is fine with LEFT. pdf.multi_cell(0, 6, meta, align=Align.L, wrapmode=WrapMode.WORD) pdf.ln(2) pdf.set_font(text_family, size=10) text = body if (body and str(body).strip()) else "(kein Volltext in der Quelle)" body_txt = sanitize_pdf_text(text) if font_key == "default": pdf.multi_cell(0, 5, body_txt, align=Align.L, wrapmode=WrapMode.WORD) else: pdf.multi_cell(0, 5, body_txt, align=Align.L, wrapmode=WrapMode.CHAR) pdf.output(str(path))1234567891011121314151617181920212223242526272829303132"""Map workbook location / stem label to body-text font preset."""
from __future__ import annotations
from pathlib import Path
# data/<cc>/… — two-letter folder names from legex scrapersFONT_BY_CC: dict[str, str] = { "kr": "han_k", "in": "deva", "am": "arm", "ge": "geo",}
# Goldenset_* stem label (ohne Präfix), z. B. aus älteren Drive-LayoutsFOLDER_FONT_BY_STEM: dict[str, str] = { "China": "han_sc", "South_Korea": "han_k", "Taiwan": "han_tc", "Hong_Kong": "han_tc", "India": "deva", "Armenia": "arm", "Georgia": "geo",}
def font_key_for_workbook(xlsx: Path) -> str: cc = xlsx.parent.name if cc in FONT_BY_CC: return FONT_BY_CC[cc] stem_label = xlsx.stem.removeprefix("Goldenset_") return FOLDER_FONT_BY_STEM.get(stem_label, "default")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Write PDFs from the ``full_text`` column only (no HTTP)."""
from __future__ import annotations
from pathlib import Path
import openpyxl
from legex.pdf_export.core import safe_slug, write_one_pdffrom legex.pdf_export.font_keys import font_key_for_workbookfrom legex.pdf_export.workbook import cell, header_map
def export_workbook( xlsx: Path, out_root: Path, *, limit: int | None = None,) -> int: wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True) if "GOLDENSET" not in wb.sheetnames: wb.close() print(f" skip {xlsx.name}: kein Sheet GOLDENSET", flush=True) return 0 ws = wb["GOLDENSET"] rows = ws.iter_rows(min_row=1, max_row=ws.max_row, values_only=True) header_row = next(rows, None) if not header_row: wb.close() return 0 h = header_map(header_row) idx_case = h.get("case_id") idx_link = h.get("link") idx_text = h.get("full_text") if idx_text is None: wb.close() print(f" skip {xlsx.name}: keine Spalte 'full_text'", flush=True) return 0
label = xlsx.parent.name out_dir = out_root / label font_key = font_key_for_workbook(xlsx)
used_names: dict[str, int] = {} count = 0 row_idx = 1 for row in rows: row_idx += 1 if not row: continue full = cell(row, idx_text) or "" case_id = cell(row, idx_case) link_val = cell(row, idx_link) or "" if not str(case_id or "").strip() and not link_val.strip() and not full.strip(): continue base = safe_slug(case_id, link_val or None, row_idx) used_names[base] = used_names.get(base, 0) + 1 fname = f"{base}_{used_names[base]}.pdf" if used_names[base] > 1 else f"{base}.pdf" write_one_pdf( out_dir / fname, str(case_id or ""), link_val, full, font_key, text_source="full_text (Sheet)", ) count += 1 if count % 25 == 0: print(f" {label}: {count} …", flush=True) if limit is not None and count >= limit: break wb.close() print(f" {label}: fertig, {count} PDFs", flush=True) return count123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185"""Fetch document bodies from ``link`` and write PDFs (fallback: ``full_text``)."""
from __future__ import annotations
import ioimport sysimport timefrom pathlib import Path
import openpyxlimport requestsfrom bs4 import BeautifulSoupfrom pypdf import PdfReader
from legex.pdf_export.core import safe_slug, write_one_pdffrom legex.pdf_export.font_keys import font_key_for_workbookfrom legex.pdf_export.workbook import cell, discover_goldensets, header_map
UA = "Mozilla/5.0 (compatible; LegexPDFExport/1.0)"
def is_hf_dataset_stub_url(url: str) -> bool: u = url.lower() return "huggingface.co" in u and "/datasets/" in u
def effective_timeout(url: str, configured: float) -> float: u = url.lower() if "hcourt.gov.au" in u: return min(configured, 10.0) if "openlegaldata.io" in u: return min(configured, 12.0) return configured
def fetch_document_text(url: str, timeout: float = 28.0) -> str: url = (url or "").strip() if not url or not url.startswith("http"): return "" last_err: str | None = None for attempt in range(2): try: r = requests.get( url, timeout=timeout, headers={"User-Agent": UA, "Accept": "text/html,application/pdf;q=0.9,*/*;q=0.8"}, allow_redirects=True, ) r.raise_for_status() data = r.content if len(data) >= 4 and data[:4] == b"%PDF": reader = PdfReader(io.BytesIO(data)) return "\n\n".join((p.extract_text() or "") for p in reader.pages) enc = r.encoding or "utf-8" try: html = data.decode(enc, errors="replace") except LookupError: html = data.decode("utf-8", errors="replace") soup = BeautifulSoup(html, "lxml") for tag in soup(["script", "style", "noscript"]): tag.decompose() text = soup.get_text("\n") lines = [ln.strip() for ln in text.splitlines()] return "\n".join(ln for ln in lines if ln) except Exception as e: last_err = str(e) if attempt < 1: time.sleep(1.2 * (attempt + 1)) if last_err: return f"[Abruf fehlgeschlagen: {last_err}]\n" return ""
def pick_body( link_val: str, sheet_full: str | None, pause_s: float, req_timeout: float,) -> tuple[str, str]: time.sleep(pause_s) link_val = (link_val or "").strip() sheet = (sheet_full or "").strip()
if link_val and is_hf_dataset_stub_url(link_val): if sheet: return sheet, "full_text (HF-Dataset-Link)" return "(kein Volltext in der Zeile trotz HF-Link)", "leer"
fetched = ( fetch_document_text(link_val, timeout=effective_timeout(link_val, req_timeout)) if link_val else "" ) if fetched and not fetched.startswith("[Abruf fehlgeschlagen"): return fetched.strip(), "URL" if sheet: return sheet, "full_text (Fallback)" if fetched: return fetched.strip(), "URL (Fehlermeldung)" return "(kein Volltext — weder URL noch Tabellenfeld)", "leer"
def export_workbook( xlsx: Path, out_root: Path, *, pause_s: float, limit: int | None, req_timeout: float, resume: bool,) -> int: label = xlsx.parent.name out_dir = out_root / label font_key = font_key_for_workbook(xlsx)
wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True) if "GOLDENSET" not in wb.sheetnames: wb.close() print(f" skip {xlsx.name}: kein Sheet GOLDENSET", flush=True) return 0 ws = wb["GOLDENSET"] rows = ws.iter_rows(min_row=1, max_row=ws.max_row, values_only=True) header_row = next(rows, None) if not header_row: wb.close() return 0 h = header_map(header_row) idx_case = h.get("case_id") idx_link = h.get("link") idx_text = h.get("full_text") if idx_link is None: wb.close() print(f" skip {xlsx.name}: keine Spalte 'link'", flush=True) return 0
used_names: dict[str, int] = {} count = 0 row_idx = 1 for row in rows: row_idx += 1 if not row: continue link_val = cell(row, idx_link) or "" case_id = cell(row, idx_case) sheet_full = cell(row, idx_text) if idx_text is not None else None if ( not str(case_id or "").strip() and not link_val.strip() and not (sheet_full or "").strip() ): continue base = safe_slug(case_id, link_val or None, row_idx) used_names[base] = used_names.get(base, 0) + 1 fname = f"{base}_{used_names[base]}.pdf" if used_names[base] > 1 else f"{base}.pdf" out_path = out_dir / fname if resume and out_path.exists() and out_path.stat().st_size > 80: count += 1 if count % 25 == 0: print(f" {label}: {count} (Bestand übersprungen) …", flush=True) if limit is not None and count >= limit: break continue
body, prov = pick_body(link_val, sheet_full, pause_s, req_timeout) write_one_pdf(out_path, str(case_id or ""), link_val, body, font_key, text_source=prov) count += 1 if count % 10 == 0: print(f" {label}: {count} …", flush=True) if limit is not None and count >= limit: break wb.close() print(f" {label}: fertig, {count} PDFs", flush=True) return count
def collect_workbooks(data_dir: Path, input_dirs: list[Path] | None) -> list[Path]: if input_dirs: files: list[Path] = [] for d in input_dirs: if not d.is_dir(): print("Ordner fehlt:", d, file=sys.stderr) continue files.extend(sorted(d.glob("Goldenset_*.xlsx"))) return sorted(files, key=lambda p: (p.stem.lower(), str(p))) return discover_goldensets(data_dir)123456789101112131415161718192021222324252627282930"""Goldenset workbook helpers."""
from __future__ import annotations
from pathlib import Path
def discover_goldensets(data_dir: Path) -> list[Path]: """Workbooks under ``data/<anything>/Goldenset_*.xlsx``.""" return sorted(data_dir.glob("*/Goldenset_*.xlsx"))
def header_map(header_row: tuple) -> dict[str, int]: m: dict[str, int] = {} for i, h in enumerate(header_row): if h is None: continue m[str(h).strip().lower()] = i return m
def cell(row: tuple, idx: int | None) -> str | None: if idx is None: return None if idx < 0 or idx >= len(row): return None v = row[idx] if v is None: return None return str(v)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180"""Paper-ready figures from `data/analysis/*.csv`.
Reads the CSVs that `legex.analysis` emits and writes four PNGs into``data/analysis/figures/``:
- ``hallucination_by_country.png`` — grouped bar, models side-by-side. - ``recall_by_country.png`` — grouped bar, models side-by-side. - ``per_variable_heatmap.png`` — variable × {accuracy, recall, hallu., F1}, one panel per model. - ``hallu_vs_recall.png`` — scatter on the cost block, one marker per (cc, model)."""
import argparseimport csvimport loggingimport sysfrom collections import defaultdictfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as np
log = logging.getLogger(__name__)
def _read_csv(path: Path) -> list[dict[str, str]]: with open(path, encoding="utf-8", newline="") as f: return list(csv.DictReader(f))
def _models_in(rows: list[dict[str, str]]) -> list[str]: return sorted({r["model"] for r in rows})
def _short_model(m: str) -> str: return m.split("/")[-1]
def _grouped_bar( rows: list[dict[str, str]], metric: str, title: str, ylabel: str, out: Path,) -> None: """Grouped-bar chart: one bar per (country, model) pair.""" countries = sorted({r["country"] for r in rows}) models = _models_in(rows) values: dict[str, dict[str, float]] = defaultdict(dict) for r in rows: values[r["country"]][r["model"]] = float(r[metric])
x = np.arange(len(countries)) width = 0.8 / max(1, len(models)) fig, ax = plt.subplots(figsize=(max(10, 0.55 * len(countries)), 4.5)) for i, model in enumerate(models): ys = [values[cc].get(model, np.nan) * 100 for cc in countries] ax.bar(x + (i - (len(models) - 1) / 2) * width, ys, width, label=_short_model(model)) ax.set_xticks(x) ax.set_xticklabels([cc.upper() for cc in countries], rotation=45, ha="right") ax.set_ylabel(ylabel) ax.set_title(title) ax.set_ylim(0, 100) ax.grid(axis="y", alpha=0.3) ax.legend(frameon=False) fig.tight_layout() fig.savefig(out, dpi=150) plt.close(fig) log.info(f"wrote {out}")
def _heatmap( rows: list[dict[str, str]], out: Path,) -> None: """Variable × {accuracy, recall_when_filled, hallucination_rate, f1} for each model.""" metrics = [ ("accuracy", "Accuracy"), ("recall_when_filled", "Recall$_{filled}$"), ("hallucination_rate", "Hallu. rate"), ("f1", "F1"), ] models = _models_in(rows) columns = sorted({r["column"] for r in rows})
fig, axes = plt.subplots(1, len(models), figsize=(5 * len(models), max(5, 0.32 * len(columns)))) if len(models) == 1: axes = [axes] for ax, model in zip(axes, models): grid = np.full((len(columns), len(metrics)), np.nan) for r in rows: if r["model"] != model: continue i = columns.index(r["column"]) for j, (key, _label) in enumerate(metrics): grid[i, j] = float(r[key]) im = ax.imshow(grid, aspect="auto", cmap="RdYlGn", vmin=0, vmax=1) ax.set_xticks(range(len(metrics))) ax.set_xticklabels([m[1] for m in metrics], rotation=30, ha="right") ax.set_yticks(range(len(columns))) ax.set_yticklabels(columns, fontsize=8) ax.set_title(_short_model(model), fontsize=10) for i in range(len(columns)): for j in range(len(metrics)): v = grid[i, j] if not np.isnan(v): ax.text(j, i, f"{v:.2f}", ha="center", va="center", fontsize=7, color="black" if 0.25 < v < 0.75 else "white") fig.colorbar(im, ax=axes, shrink=0.8, label="value") fig.suptitle("Per-variable metrics (summed across jurisdictions)") fig.savefig(out, dpi=150, bbox_inches="tight") plt.close(fig) log.info(f"wrote {out}")
def _scatter(rows: list[dict[str, str]], out: Path) -> None: """Hallucination vs recall on the cost block. One marker per (cc, model).""" models = _models_in(rows) markers = {models[0]: "o"} if len(models) == 1 else {models[0]: "o", models[1]: "s"} colors = plt.cm.tab20.colors
fig, ax = plt.subplots(figsize=(7, 6)) for r in rows: m = r["model"] x = float(r["cost_hallucination_rate"]) * 100 y = float(r["cost_recall_when_filled"]) * 100 cc = r["country"] c = colors[hash(cc) % len(colors)] ax.scatter(x, y, marker=markers.get(m, "o"), color=c, s=70, alpha=0.85, edgecolor="black", linewidth=0.4) ax.annotate(cc.upper(), (x, y), fontsize=7, xytext=(3, 3), textcoords="offset points") ax.set_xlabel("Cost-block hallucination rate (%)") ax.set_ylabel("Cost-block recall when filled (%)") ax.set_title("Cost extraction: recall vs hallucination, by jurisdiction × model") ax.set_xlim(-2, 100) ax.set_ylim(-2, 100) ax.grid(alpha=0.3) handles = [ plt.Line2D([], [], marker=mk, linestyle="", color="grey", label=_short_model(m)) for m, mk in markers.items() ] ax.legend(handles=handles, frameon=False, loc="lower right") fig.tight_layout() fig.savefig(out, dpi=150) plt.close(fig) log.info(f"wrote {out}")
def make_all(analysis_dir: Path, out_dir: Path) -> None: out_dir.mkdir(parents=True, exist_ok=True) per_country = _read_csv(analysis_dir / "per_country.csv") per_column = _read_csv(analysis_dir / "per_column.csv")
_grouped_bar( per_country, "hallucination_rate", "Hallucination rate by jurisdiction (cells where the expert recorded nothing)", "Hallucination rate (%)", out_dir / "hallucination_by_country.png", ) _grouped_bar( per_country, "recall_when_filled", "Accuracy when the expert recorded a value", "Accuracy (%)", out_dir / "recall_by_country.png", ) _heatmap(per_column, out_dir / "per_variable_heatmap.png") _scatter(per_country, out_dir / "hallu_vs_recall.png")
def main() -> None: logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler(sys.stderr)], ) parser = argparse.ArgumentParser( prog="legex-plots", description="Render paper-ready figures from data/analysis/*.csv.", ) parser.add_argument("--in", dest="in_dir", type=Path, default=Path("data/analysis")) parser.add_argument("--out", dest="out_dir", type=Path, default=Path("data/analysis/figures")) args = parser.parse_args() make_all(args.in_dir, args.out_dir)
if __name__ == "__main__": main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import loggingimport zipfilefrom pathlib import Path
from legex.config import settingsfrom legex.scrapers import SCRAPERSfrom legex.utils import ( filtered_path, goldenset_path, random_sample, raw_path, read_jsonl, sampled_path, write_goldenset_xlsx, write_jsonl,)
log = logging.getLogger(__name__)
def scrape(force: bool = False) -> None: for cc, cls in SCRAPERS.items(): out = raw_path(cc) if out.exists() and not force: log.info(f"[{cc}] {out} exists, skipping") continue try: cases = cls().scrape(settings.date_start, settings.date_end) except Exception as e: log.warning(f"[{cc}] scrape failed ({e}), skipping") continue write_jsonl(cases, out) log.info(f"[{cc}] {len(cases)} → {out}")
def filter_and_sample(force: bool = False) -> None: for cc, cls in SCRAPERS.items(): sampled = sampled_path(cc) if sampled.exists() and not force: log.info(f"[{cc}] {sampled} exists, skipping") continue raw = raw_path(cc) if not raw.exists(): log.warning(f"[{cc}] missing {raw}, skipping") continue
cases = read_jsonl(raw) filtered = cls.civil_filter(cases) write_jsonl(filtered, filtered_path(cc)) log.info(f"[{cc}] filtered {len(cases)} → {len(filtered)}")
sample = random_sample(filtered, settings.sample_n, settings.sample_seed) write_jsonl(sample, sampled) log.info(f"[{cc}] sampled {len(sample)} → {sampled}")
def fill_goldenset() -> None: for cc, cls in SCRAPERS.items(): out = goldenset_path(cc) if out.exists() and not force: log.info(f"[{cc}] {out} exists, skipping") continue sampled = sampled_path(cc) if not sampled.exists(): log.warning(f"[{cc}] missing {sampled}, skipping") continue cases = read_jsonl(sampled) enriched = cls.enrich(cases) if any(e.full_text != c.full_text for e, c in zip(enriched, cases)): write_jsonl(enriched, sampled) log.info(f"[{cc}] enriched {len(enriched)} cases → {sampled}") write_goldenset_xlsx(enriched, settings.template, out) log.info(f"[{cc}] → {out}")
def dist(force: bool = False) -> None: settings.dist_dir.mkdir(parents=True, exist_ok=True) produced: list[Path] = [] for cc in SCRAPERS: xlsx = goldenset_path(cc) zip_path = settings.dist_dir / f"{cc}.zip" if zip_path.exists() and not force: log.info(f"[{cc}] {zip_path} exists, skipping") produced.append(zip_path) continue if not xlsx.exists(): log.warning(f"[{cc}] missing {xlsx}, skipping") continue with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: zf.write(xlsx, arcname=xlsx.name) log.info(f"[{cc}] → {zip_path}") produced.append(zip_path)
if produced: log.info(f"Upload to {settings.drive_folder_url}:") for p in produced: log.info(f" {p}")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253"""Versioned system prompts for `legex-classify`.
Each version lives in `legex/prompts/{version}.py` and exposes one of:
# single-call mode (one LLM call per case) PROMPT: str — template with {rules_block}/{isic_block} build(rules, isic) -> str — returns the filled prompt
# per-column mode (one LLM call per Classification field per case) MODE = "per_column" build_columns(rules, isic) -> dict[column_name, system_prompt]
`load_plan(...)` normalises both shapes into a `PromptPlan`."""
from dataclasses import dataclassfrom importlib import import_module
@dataclassclass PromptPlan: mode: str # "single" or "per_column" system: str | None = None column_systems: dict[str, str] | None = None
def load_plan( version: str, rules: list[tuple[str, str]], isic: list[tuple[str, str, str]],) -> PromptPlan: try: mod = import_module(f"legex.prompts.{version}") except ImportError as e: raise ValueError(f"Unknown prompt version: {version!r}") from e mode = getattr(mod, "MODE", "single") if mode == "per_column": return PromptPlan(mode="per_column", column_systems=mod.build_columns(rules, isic)) return PromptPlan(mode="single", system=mod.build(rules, isic))
def build_prompt( version: str, rules: list[tuple[str, str]], isic: list[tuple[str, str, str]],) -> str: """Single-mode shortcut. Raises if the version is per-column.""" plan = load_plan(version, rules, isic) if plan.mode != "single" or plan.system is None: raise ValueError( f"build_prompt() is single-mode only; prompt version {version!r} is {plan.mode}" ) return plan.system123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""System prompt v1 for legal-case structured extraction."""
PROMPT = """You extract structured data from a single court judgment. Read the judgment text the user provides and return a JSON object whose keys are exactly the variable names defined below. Follow each variable's coding rule precisely (formatting, allowed values, fallbacks). When a value cannot be determined from the judgment, return JSON null (not the string "None"). Do not invent information that is not in the text.
Use native JSON types — a number is a number, not a string:- Money amounts (*_nominal): JSON number, e.g. 150000 or 4000.50. Use 0 when the court explicitly waives or denies the amount. The single exception is dispute_value_nominal, which may also be the string "nonpecuniary" for non-monetary disputes.- plaintiff_loosing_share: JSON number between 0 and 1, e.g. 0.6.- *_count variables: JSON integer, e.g. 2.- Date variables: JSON string in YYYY-MM-DD format, e.g. "2022-07-15".- All other text fields (legal_subject_judgement, currencies, ISIC categories): JSON string.
## Variable coding rules
{rules_block}
## Allowed ISIC industry categories (for *_industry_category variables)
{isic_block}
## Currency variables
For each *_nominal variable that is a money amount, also return the matching Currency_<variable> field as the ISO-4217 code of the local currency of the proceedings (e.g. CHF for Switzerland, EUR for France/Germany/Belgium, GBP for the UK, AUD for Australia, NZD for New Zealand). Return null if the corresponding amount is null."""
def build( rules: list[tuple[str, str]], isic: list[tuple[str, str, str]],) -> str: rules_block = "\n\n".join(f"### {name}\n{explanation}" for name, explanation in rules) isic_block = "\n".join( f"- {coded_value} — {category}: {description}" for coded_value, category, description in isic ) return PROMPT.format(rules_block=rules_block, isic_block=isic_block)
# case_id The official case reference number of the judgment, exactly as printed on the first page of the judgment. Copy it character-for-character, including any prefix letters, underscores, and slashes. If the judgment shows more than one reference number, use the main docket number assigned when the case was first registered at the court (not internal file numbers or cross-references to lower-instance decisions). Enter None if the judgment does not contain a case reference number.# legal_subject_judgement The area of law the case is about, translated into English. This is usually stated on the first page just before the factual summary. Formatting rules: (1) replace every space with the underscore character '_'; (2) capitalise the first letter of each word; (3) if the case covers several legal areas, join them with a forward slash '/'; (4) if the original term has brackets, remove the brackets but keep the text inside. Examples: 'Persönlicher Verkehr' → 'Personal_Contact', 'Werkvertrag' → 'Contract_for_Work', 'Forderung' → 'Claim', 'Claim (IP)' → 'Claim_IP'. Enter None if the judgment does not indicate a subject matter.# trial_start_date The date on which the proceedings BEFORE THE DECIDING COURT were formally started, NOT the date of the original lawsuit at a lower instance. Format: YYYY-MM-DD (four-digit year, two-digit month, two-digit day, separated by hyphens). Example: '2022-07-15' means 15 July 2022. If the judgment mentions both the date the appeal was drafted AND the date it was received by the court, use the date of receipt by the court. Enter None if the date is not mentioned or cannot be clearly determined.# trial_end_date The date on which the judgment was DECIDED (rendered) by the court, NOT the date it was sent out or served on the parties. Format: YYYY-MM-DD. Example: '2023-01-23' means 23 January 2023. Enter None if the judgment date cannot be clearly determined.# dispute_value_nominal The amount in dispute entered as a plain number. Formatting rules: (1) use a period '.' as the decimal separator, NEVER a comma; (2) do NOT use any thousands separator, no apostrophes, no commas, no spaces; (3) do NOT include the currency symbol or 'CHF'. Correct: '150000.00'. Wrong: '150\'000.00', '150,000.00', 'CHF 150000'. Use the local currency of the proceedings. If there is a counterclaim with its own separate value in dispute, record ONLY the main claim's value here. Enter 'nonpecuniary' (without quotes) for non-monetary disputes (for example custody, building permit, personal rights). Enter None if the amount in dispute cannot be determined from the judgment.# plaintiff_loosing_share The share of the claim that the plaintiff LOST, expressed as a decimal number between 0.0 (plaintiff won fully) and 1.0 (plaintiff lost fully). Use a period '.' as decimal separator and at most four decimal places. Rules: fully dismissed → 1.0; fully granted → 0.0; declared inadmissible → 1.0; partially granted → derive the ratio from the cost allocation in the dispositif (e.g. court allocates costs 60/40 against appellant → 0.6); plaintiff claimed 100000 and was awarded 60000 → 0.4; court states 'plaintiff prevails to 70%' → 0.3. Enter None if the judgment defers the cost decision to a later ruling or the win/loss ratio cannot be determined.# court_cost_awarded_nominal The TOTAL court fees as stated in the operative part of the judgment. Record the TOTAL amount of court fees regardless of how they are allocated between the parties. This is ONLY the court's own fee, do NOT include party compensation or attorney fees here. Formatting: plain number, period '.' as decimal separator, NO thousands separator, NO currency symbol. Example: '4000' or '4000.00'. Enter 0 if the court explicitly waives court fees. Enter None if the judgment defers the cost decision to a later ruling or the amount cannot be determined.# party_compensation_awarded_nominal The TOTAL party compensation, the attorney fee reimbursement awarded by the court, as stated in the operative part. Record the total amount exactly as stated by the court, INCLUDING VAT if the court includes it in the stated figure. Formatting: plain number, period '.' as decimal separator, NO thousands separator, NO currency symbol. Example: '5000' or '5000.00'. Enter 0 if the court explicitly denies any party compensation. Enter None if party compensation is offset between the parties, not addressed in the judgment at all, or deferred to a later decision.# plaintiffs_all_count The total number of plaintiffs (claimants / appellants) listed in the heading of the judgment, entered as a whole number. Plaintiffs usually appear in the party designation block on the first page. Counting rules: (1) count each distinct plaintiff entity separately; (2) do NOT count attorneys or legal representatives; (3) for minors represented by their parents, count the MINOR, not the parent as representative; (4) a married couple listed as 'A.__ und B.__' counts as 2 separate entities; (5) collective designations count as ONE entity UNLESS each heir is individually named in the heading. Enter None if the number of plaintiffs cannot be determined from the judgment.# defendants_all_count The total number of defendants (respondents) listed in the heading of the judgment, entered as a whole number. Defendants usually appear in the party designation block on the first page. Counting rules: (1) count each distinct defendant entity separately; (2) do NOT count attorneys or legal representatives; (3) for minors represented by their parents, count the MINOR, not the parent as representative; (4) a married couple listed as 'A.__ und B.__' counts as 2 separate entities; (5) collective designations count as ONE entity UNLESS each heir is individually named in the heading. Enter None if the number of defendants cannot be determined from the judgment.# plaintiff_no1_ISIC1_industry_category "The industry sector of the FIRST plaintiff listed in the heading, according to the international ISIC classification (an internationally standardised list of 22 industry sectors A–V).
# Step-by-step: # (1) identify what the first plaintiff does for a living or what its main business is, look at the party designation in the heading and, if needed, at the factual summary (Sachverhalt), # (2) find the category from the ISIC categories below if any and copy the value exactly as written, all lowercase with underscores. Examples: a bank → 'l_financial_insurance'; a pharmaceutical company → 'c_manufacturing'.# (3) If judgment DOES describe the plaintiff's occupation or activity, but that description cannot be mapped to any ISIC sector, enter 'no_allocation_possible'. Example cases: non-commercial natural persons whose role is mentioned ('Rentner/in', 'Student/in).' # (4) If the judgements contains no information at all about the plaintiff's economic activity, enter the literal 'None'. # ISIC Categories:# • 'a_agriculture_forestry_fishing': Agriculture, forestry and fishing# • 'b_mining_quarrying': Mining and quarrying# • 'c_manufacturing': Manufacturing# • 'd_electricity_gas_steam_ac': Electricity, gas, steam and air conditioning supply# • 'e_water_sewerage_waste_remediation': Water supply; sewerage, waste management and remediation# • 'f_construction': Construction# • 'g_wholesale_retail_trade': Wholesale and retail trade; repair of motor vehicles# • 'h_transportation_storage': Transportation and storage# • 'i_accommodation_food_service': Accommodation and food service activities# • 'j_publishing_broadcasting_content': Publishing, broadcasting and content production# • 'k_telecom_it_info_services': Telecommunications, IT and other information services# • 'l_financial_insurance': Financial and insurance activities# • 'm_real_estate': Real estate activities# • 'n_professional_scientific_technical': Professional, scientific and technical activities# • 'o_administrative_support': Administrative and support service activities# • 'p_public_admin_defence': Public administration and defence; compulsory social security# • 'q_education': Education# • 'r_human_health_social_work': Human health and social work activities# • 's_arts_entertainment_recreation': Arts, entertainment and recreation# • 't_other_service_activities': Other service activities# • 'u_households_as_employers': Activities of households as employers# • 'v_extraterritorial_organisations': Activities of extraterritorial organisations and bodies# Fallbacks:# • 'no_allocation_possible'# • 'None'"# defendant_no1_ISIC1_industry_category "The industry sector of the FIRST defendant listed in the heading, according to the international ISIC classification (an internationally standardised list of 22 industry sectors A–V).
# Step-by-step: # (1) identify what the first defendant does for a living or what its main business is, look at the party designation in the heading and, if needed, at the factual summary (Sachverhalt), # (2) find the category from the ISIC categories below if any and copy the value exactly as written, all lowercase with underscores. Examples: a bank → 'l_financial_insurance'; a pharmaceutical company → 'c_manufacturing'.# (3) If judgment DOES describe the defendant 's occupation or activity, but that description cannot be mapped to any ISIC sector, enter 'no_allocation_possible'. Example cases: non-commercial natural persons whose role is mentioned ('Rentner/in', 'Student/in).' # (4) If the judgements contains no information at all about the defendant 's economic activity, enter the literal 'None'. # ISIC Categories:# • 'a_agriculture_forestry_fishing': Agriculture, forestry and fishing# • 'b_mining_quarrying': Mining and quarrying# • 'c_manufacturing': Manufacturing# • 'd_electricity_gas_steam_ac': Electricity, gas, steam and air conditioning supply# • 'e_water_sewerage_waste_remediation': Water supply; sewerage, waste management and remediation# • 'f_construction': Construction# • 'g_wholesale_retail_trade': Wholesale and retail trade; repair of motor vehicles# • 'h_transportation_storage': Transportation and storage# • 'i_accommodation_food_service': Accommodation and food service activities# • 'j_publishing_broadcasting_content': Publishing, broadcasting and content production# • 'k_telecom_it_info_services': Telecommunications, IT and other information services# • 'l_financial_insurance': Financial and insurance activities# • 'm_real_estate': Real estate activities# • 'n_professional_scientific_technical': Professional, scientific and technical activities# • 'o_administrative_support': Administrative and support service activities# • 'p_public_admin_defence': Public administration and defence; compulsory social security# • 'q_education': Education# • 'r_human_health_social_work': Human health and social work activities# • 's_arts_entertainment_recreation': Arts, entertainment and recreation# • 't_other_service_activities': Other service activities# • 'u_households_as_employers': Activities of households as employers# • 'v_extraterritorial_organisations': Activities of extraterritorial organisations and bodies# Fallbacks:# • 'no_allocation_possible'# • 'None'" 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586"""Per-column system prompts: one focused LLM call per Classification field.
Each prompt is built from the column's coding rule (Vorlage`Variables_Coding_Rules` sheet) plus the small targeted instructions itneeds (ISIC list for industry fields, currency hint for the `currency_*`fields, the "nonpecuniary" exception for `dispute_value_nominal`).
The LLM is told to return JSON `{"<column>": <value>}` so the responsecan be validated by the same `Classification` model used in v1 — we justlook at the one field we asked for."""
from legex.models.classification import Classification
MODE = "per_column"
_PREAMBLE = ( "You extract a single variable from a court judgment. Read the " "judgment text the user provides and return a JSON object with " "exactly one key: the variable name below. The value must be the " "typed answer or JSON null. Do not invent information that is not " "in the text. Use native JSON types — a number is a number, not a " "string. Money amounts are JSON numbers; dates are JSON strings in " "YYYY-MM-DD format; counts are JSON integers.")
_DISPUTE_TAIL = 'The value may also be the literal string "nonpecuniary" for non-monetary disputes.'
_ISIC_TAIL = ( "The value must be one of the coded values listed below.\n\n" "## Allowed ISIC industry categories\n\n{isic_block}")
_CURRENCY_TAIL = ( "Return the ISO-4217 currency code of the local currency of the " "proceedings (e.g. CHF for Switzerland, EUR for France/Germany/" "Belgium, GBP for the UK, AUD for Australia, NZD for New Zealand). " "Return null if the corresponding amount in the judgment is null.")
_ISIC_COLUMNS = { "plaintiff_no1_ISIC1_industry_category", "defendant_no1_ISIC1_industry_category",}
_CURRENCY_COLUMNS = { "Currency_dispute_value_nominal", "Currency_court_cost_awarded_nominal", "Currency_party_compensation_awarded_nominal",}
def build_columns( rules: list[tuple[str, str]], isic: list[tuple[str, str, str]],) -> dict[str, str]: """Returns {csv_column_name: system_prompt}.
Keys use the field's alias when set (e.g. `Currency_*` capital C) so they line up with the GOLDENSET header. Python attribute names stay lowercase on the `Classification` model. """ rules_by_name = {name: explanation for name, explanation in rules} isic_block = "\n".join( f"- {coded_value} — {category}: {description}" for coded_value, category, description in isic )
out: dict[str, str] = {} for field, info in Classification.model_fields.items(): col = info.alias or field rule = rules_by_name.get(col) or rules_by_name.get(field, "") body = ( f"{_PREAMBLE}\n\n" f"## Variable: {col}\n\n" f"{rule}\n\n" f'Return JSON in the form: {{"{col}": <value>}}' ) if col == "dispute_value_nominal": body += f"\n\n{_DISPUTE_TAIL}" if col in _ISIC_COLUMNS: body += "\n\n" + _ISIC_TAIL.format(isic_block=isic_block) if col in _CURRENCY_COLUMNS: body += f"\n\n{_CURRENCY_TAIL}" out[col] = body return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"""System prompt v3 for legal-case structured extraction."""
PROMPT = """You extract structured data from a single court judgment. Read the judgment text the user provides and return a JSON object whose keys are exactly the variable names defined below. Follow each variable's coding rule precisely (formatting, allowed values, fallbacks). When a value cannot be determined from the judgment, return JSON null (not the string "None"). Do not invent information that is not in the text.
Use native JSON types — a number is a number, not a string:- Money amounts (*_nominal): JSON number, e.g. 150000 or 4000.50. Use 0 when the court explicitly waives or denies the amount. The single exception is dispute_value_nominal, which may also be the string "nonpecuniary" for non-monetary disputes.- plaintiff_loosing_share: JSON number between 0 and 1, e.g. 0.6.- *_count variables: JSON integer, e.g. 2.- Date variables: JSON string in YYYY-MM-DD format, e.g. "2022-07-15".- All other text fields (legal_subject_judgement, currencies, ISIC categories): JSON string.
## Variable coding rules
### case_idThe official case reference number of the judgment, exactly as printed on the first page of the judgment. Copy it character-for-character, including any prefix letters, underscores, and slashes. If the judgment shows more than one reference number, use the main docket number assigned when the case was first registered at the court (not internal file numbers or cross-references to lower-instance decisions). Enter None if the judgment does not contain a case reference number.
### legal_subject_judgementThe area of law the case is about, translated into English. This is usually stated on the first page just before the factual summary. Formatting rules: (1) replace every space with the underscore character '_'; (2) capitalise the first letter of each word; (3) if the case covers several legal areas, join them with a forward slash '/'; (4) if the original term has brackets, remove the brackets but keep the text inside. Examples: 'Persönlicher Verkehr' → 'Personal_Contact', 'Werkvertrag' → 'Contract_for_Work', 'Forderung' → 'Claim', 'Claim (IP)' → 'Claim_IP'. Enter None if the judgment does not indicate a subject matter.
### trial_start_dateThe date on which the proceedings BEFORE THE DECIDING COURT were formally started, NOT the date of the original lawsuit at a lower instance. Format: YYYY-MM-DD (four-digit year, two-digit month, two-digit day, separated by hyphens). Example: '2022-07-15' means 15 July 2022. If the judgment mentions both the date the appeal was drafted AND the date it was received by the court, use the date of receipt by the court. Enter None if the date is not mentioned or cannot be clearly determined.
### trial_end_dateThe date on which the judgment was DECIDED (rendered) by the court, NOT the date it was sent out or served on the parties. Format: YYYY-MM-DD. Example: '2023-01-23' means 23 January 2023. Enter None if the judgment date cannot be clearly determined.
### dispute_value_nominalThe amount in dispute entered as a plain number. Formatting rules: (1) use a period '.' as the decimal separator, NEVER a comma; (2) do NOT use any thousands separator, no apostrophes, no commas, no spaces; (3) do NOT include the currency symbol or 'CHF'. Correct: '150000.00'. Wrong: '150\\'000.00', '150,000.00', 'CHF 150000'. Use the local currency of the proceedings. If there is a counterclaim with its own separate value in dispute, record ONLY the main claim's value here. Enter 'nonpecuniary' (without quotes) for non-monetary disputes (for example custody, building permit, personal rights). Enter None if the amount in dispute cannot be determined from the judgment.
### plaintiff_loosing_shareThe share of the claim that the plaintiff LOST, expressed as a decimal number between 0.0 (plaintiff won fully) and 1.0 (plaintiff lost fully). Use a period '.' as decimal separator and at most four decimal places. Rules: fully dismissed → 1.0; fully granted → 0.0; declared inadmissible → 1.0; partially granted → derive the ratio from the cost allocation in the dispositif (e.g. court allocates costs 60/40 against appellant → 0.6); plaintiff claimed 100000 and was awarded 60000 → 0.4; court states 'plaintiff prevails to 70%' → 0.3. Enter None if the judgment defers the cost decision to a later ruling or the win/loss ratio cannot be determined.
### court_cost_awarded_nominalThe TOTAL court fees as stated in the operative part of the judgment. Record the TOTAL amount of court fees regardless of how they are allocated between the parties. This is ONLY the court's own fee, do NOT include party compensation or attorney fees here. Formatting: plain number, period '.' as decimal separator, NO thousands separator, NO currency symbol. Example: '4000' or '4000.00'. Enter 0 if the court explicitly waives court fees. Enter None if the judgment defers the cost decision to a later ruling or the amount cannot be determined.
### party_compensation_awarded_nominalThe TOTAL party compensation, the attorney fee reimbursement awarded by the court, as stated in the operative part. Record the total amount exactly as stated by the court, INCLUDING VAT if the court includes it in the stated figure. Formatting: plain number, period '.' as decimal separator, NO thousands separator, NO currency symbol. Example: '5000' or '5000.00'. Enter 0 if the court explicitly denies any party compensation. Enter None if party compensation is offset between the parties, not addressed in the judgment at all, or deferred to a later decision.
### plaintiffs_all_countThe total number of plaintiffs (claimants / appellants) listed in the heading of the judgment, entered as a whole number. Plaintiffs usually appear in the party designation block on the first page. Counting rules: (1) count each distinct plaintiff entity separately; (2) do NOT count attorneys or legal representatives; (3) for minors represented by their parents, count the MINOR, not the parent as representative; (4) a married couple listed as 'A.__ und B.__' counts as 2 separate entities; (5) collective designations count as ONE entity UNLESS each heir is individually named in the heading. Enter None if the number of plaintiffs cannot be determined from the judgment.
### defendants_all_countThe total number of defendants (respondents) listed in the heading of the judgment, entered as a whole number. Defendants usually appear in the party designation block on the first page. Counting rules: (1) count each distinct defendant entity separately; (2) do NOT count attorneys or legal representatives; (3) for minors represented by their parents, count the MINOR, not the parent as representative; (4) a married couple listed as 'A.__ und B.__' counts as 2 separate entities; (5) collective designations count as ONE entity UNLESS each heir is individually named in the heading. Enter None if the number of defendants cannot be determined from the judgment.
### plaintiff_no1_ISIC1_industry_categoryThe industry sector of the FIRST plaintiff listed in the heading, according to the international ISIC classification (an internationally standardised list of 22 industry sectors A–V).
Step-by-step:(1) identify what the first plaintiff does for a living or what its main business is, look at the party designation in the heading and, if needed, at the factual summary (Sachverhalt),(2) find the category from the ISIC categories below if any and copy the value exactly as written, all lowercase with underscores. Examples: a bank → 'l_financial_insurance'; a pharmaceutical company → 'c_manufacturing'.(3) If judgment DOES describe the plaintiff's occupation or activity, but that description cannot be mapped to any ISIC sector, enter 'no_allocation_possible'. Example cases: non-commercial natural persons whose role is mentioned ('Rentner/in', 'Student/in').(4) If the judgements contains no information at all about the plaintiff's economic activity, enter the literal 'None'.
### defendant_no1_ISIC1_industry_categoryThe industry sector of the FIRST defendant listed in the heading, according to the international ISIC classification (an internationally standardised list of 22 industry sectors A–V).
Step-by-step:(1) identify what the first defendant does for a living or what its main business is, look at the party designation in the heading and, if needed, at the factual summary (Sachverhalt),(2) find the category from the ISIC categories below if any and copy the value exactly as written, all lowercase with underscores. Examples: a bank → 'l_financial_insurance'; a pharmaceutical company → 'c_manufacturing'.(3) If judgment DOES describe the defendant's occupation or activity, but that description cannot be mapped to any ISIC sector, enter 'no_allocation_possible'. Example cases: non-commercial natural persons whose role is mentioned ('Rentner/in', 'Student/in').(4) If the judgements contains no information at all about the defendant's economic activity, enter the literal 'None'.
## Allowed ISIC industry categories (for *_industry_category variables)
- a_agriculture_forestry_fishing — Agriculture, forestry and fishing- b_mining_quarrying — Mining and quarrying- c_manufacturing — Manufacturing- d_electricity_gas_steam_ac — Electricity, gas, steam and air conditioning supply- e_water_sewerage_waste_remediation — Water supply; sewerage, waste management and remediation- f_construction — Construction- g_wholesale_retail_trade — Wholesale and retail trade; repair of motor vehicles- h_transportation_storage — Transportation and storage- i_accommodation_food_service — Accommodation and food service activities- j_publishing_broadcasting_content — Publishing, broadcasting and content production- k_telecom_it_info_services — Telecommunications, IT and other information services- l_financial_insurance — Financial and insurance activities- m_real_estate — Real estate activities- n_professional_scientific_technical — Professional, scientific and technical activities- o_administrative_support — Administrative and support service activities- p_public_admin_defence — Public administration and defence; compulsory social security- q_education — Education- r_human_health_social_work — Human health and social work activities- s_arts_entertainment_recreation — Arts, entertainment and recreation- t_other_service_activities — Other service activities- u_households_as_employers — Activities of households as employers- v_extraterritorial_organisations — Activities of extraterritorial organisations and bodies
Fallbacks for the *_industry_category variables: 'no_allocation_possible' or 'None'.
## Currency variables
For each *_nominal variable that is a money amount, also return the matching Currency_<variable> field as the ISO-4217 code of the local currency of the proceedings (e.g. CHF for Switzerland, EUR for France/Germany/Belgium, GBP for the UK, AUD for Australia, NZD for New Zealand). Return null if the corresponding amount is null."""
def build( rules: list[tuple[str, str]] | None = None, isic: list[tuple[str, str, str]] | None = None,) -> str: return PROMPT123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295"""Render the `Quantitative Results` LaTeX section.
Reads `data/analysis/per_country_per_column.csv` (produced by`legex-analysis`), restricts it to the twelve evaluated jurisdictionsand the fourteen evaluated fields, then prints the section preamble plusthe headline table that compares the three systems on Acc / Recall /Hallucination / F1, both over all fields and over the four-field costblock."""
import argparseimport csvimport loggingimport sysfrom collections import defaultdictfrom pathlib import Path
log = logging.getLogger(__name__)
# Jurisdictions that survive the round-2 PDF audit (TW/BR/HK/IN excluded# because their source PDFs were incomplete; BE/NP/RS excluded because# inference was intentionally skipped for them).EVALUATED_COUNTRIES: tuple[str, ...] = ( "am", "au", "ch", "de", "es", "fr", "ge", "nz", "ph", "sg", "uk", "us",)H2H_COUNTRIES = EVALUATED_COUNTRIES # backwards-compat alias
EVAL_FIELDS: tuple[str, ...] = ( "legal_subject_judgement", "trial_start_date", "trial_end_date", "dispute_value_nominal", "plaintiff_loosing_share", "court_cost_awarded_nominal", "party_compensation_awarded_nominal", "plaintiffs_all_count", "defendants_all_count", "plaintiff_no1_ISIC1_industry_category", "defendant_no1_ISIC1_industry_category",)
COST_BLOCK: tuple[str, ...] = ( "dispute_value_nominal", "plaintiff_loosing_share", "court_cost_awarded_nominal", "party_compensation_awarded_nominal",)
# (system slug as written by legex-analysis, LaTeX label). Order = row order# in the headline table.SYSTEMS: tuple[tuple[str, str], ...] = ( ("gemini", r"\texttt{gemini-3.1-flash-lite}"), ("gpt", r"\texttt{gpt-5.4-mini} "), ("harvey", r"\textsc{Harvey} "),)
_BUCKETS = ("tp", "mismatch", "missed", "hallucinated", "tn")
def _empty() -> dict[str, int]: return {k: 0 for k in _BUCKETS}
def _metrics(c: dict[str, int]) -> dict[str, float]: tp, mism, miss, hallu, tn = c["tp"], c["mismatch"], c["missed"], c["hallucinated"], c["tn"] total = tp + mism + miss + hallu + tn filled_gold = tp + mism + miss empty_gold = hallu + tn p_denom = tp + mism + hallu p = tp / p_denom if p_denom else 0.0 r = tp / filled_gold if filled_gold else 0.0 f1 = 2 * p * r / (p + r) if (p + r) else 0.0 return { "accuracy": (tp + tn) / total if total else 0.0, "recall_when_filled": r, "hallucination_rate": hallu / empty_gold if empty_gold else 0.0, "f1": f1, }
def _aggregate( csv_path: Path,) -> dict[str, dict[str, dict[str, int]]]: """{ model -> { 'all' | 'cost' -> bucket counter } }.""" out: dict[str, dict[str, dict[str, int]]] = { m: {"all": _empty(), "cost": _empty()} for m, _ in SYSTEMS } h2h = set(H2H_COUNTRIES) eval_fields = set(EVAL_FIELDS) cost_fields = set(COST_BLOCK) models = {m for m, _ in SYSTEMS}
with open(csv_path, encoding="utf-8", newline="") as f: for row in csv.DictReader(f): if row["country"] not in h2h or row["model"] not in models: continue col = row["column"] if col not in eval_fields: continue counts = {k: int(row[k]) for k in _BUCKETS} for k in _BUCKETS: out[row["model"]]["all"][k] += counts[k] if col in cost_fields: for k in _BUCKETS: out[row["model"]]["cost"][k] += counts[k] return out
def _fmt_pct(v: float) -> str: return f"{v * 100:.1f}\\%"
def _fmt_f1(v: float) -> str: return f"{v:.3f}"
def _bold_best(values: list[float], formatter, higher_is_better: bool = True) -> list[str]: best = max(values) if higher_is_better else min(values) return [ rf"\textbf{{{formatter(v)}}}" if v == best else formatter(v) for v in values ]
def render_section(agg: dict[str, dict[str, dict[str, int]]]) -> str: lines: list[str] = [] lines.append(r"% Auto-generated by legex-quant-results — do not edit by hand.") lines.append(r"\section{Quantitative Results}") lines.append("") lines.append( r"We score the three systems against the human coded dataset: a commercial" ) lines.append( r"review-table product by \textsc{Harvey} and two schema-constrained LLM" ) lines.append( r"pipelines (\texttt{gpt-5.4-mini} and \texttt{gemini-3.1-flash-lite})." ) lines.append( r"Since the dataset contains missing fields, e.g.\ where a court judgement" ) lines.append( r"does not issue costs we evaluate our systems against two metrics:" ) lines.append(r"\begin{itemize}") lines.append( r" \item \textbf{Accuracy when filled}: how often the system extracts the" r" correct value given that the human expert has classified it." ) lines.append( r" \item \textbf{Hallucination rate}: how often the system extracts a" r" value given that the human expert has left the field empty." ) lines.append(r"\end{itemize}") lines.append("")
metrics_all = {m: _metrics(agg[m]["all"]) for m, _ in SYSTEMS} metrics_cost = {m: _metrics(agg[m]["cost"]) for m, _ in SYSTEMS}
def _p(model: str, panel: str, key: str) -> str: src = metrics_all if panel == "all" else metrics_cost return f"{src[model][key] * 100:.1f}"
lines.append( r"\Cref{tab:overall} shows the same trade-off on both panels: the two" r" LLM pipelines are more eager extractors, while \textsc{Harvey} is" r" more conservative. Across all " + str(len(EVAL_FIELDS)) + r" evaluated" r" fields \texttt{gpt-5.4-mini} and \texttt{gemini-3.1-flash-lite}" r" reach accuracy when filled of " + _p("gpt", "all", "recall_when_filled") + r"\,\% and " + _p("gemini", "all", "recall_when_filled") + r"\,\%, alongside \textsc{Harvey} at " + _p("harvey", "all", "recall_when_filled") + r"\,\%, but the LLM" r" pipelines pay for that recall with hallucination rates of " + _p("gpt", "all", "hallucination_rate") + r"\,\% and " + _p("gemini", "all", "hallucination_rate") + r"\,\% against \textsc{Harvey}'s " + _p("harvey", "all", "hallucination_rate") + r"\,\%." r" Narrowing to the four cost-block variables, the three systems" r" converge on accuracy (" + _p("harvey", "cost", "recall_when_filled") + r"--" + _p("gemini", "cost", "recall_when_filled") + r"\,\%), and the" r" hallucination rates land at " + _p("gemini", "cost", "hallucination_rate") + r"\,\% (Gemini), " + _p("harvey", "cost", "hallucination_rate") + r"\,\% (Harvey), and " + _p("gpt", "cost", "hallucination_rate") + r"\,\% (GPT)." r" No single system dominates: the LLM pipelines are preferable when" r" the downstream task tolerates noisy extractions in exchange for" r" coverage, whereas \textsc{Harvey} is preferable when emitted values" r" must be trusted on the non-cost variables." ) lines.append("")
acc_all = [metrics_all[m]["recall_when_filled"] for m, _ in SYSTEMS] hal_all = [metrics_all[m]["hallucination_rate"] for m, _ in SYSTEMS] acc_cost = [metrics_cost[m]["recall_when_filled"] for m, _ in SYSTEMS] hal_cost = [metrics_cost[m]["hallucination_rate"] for m, _ in SYSTEMS]
acc_all_s = _bold_best(acc_all, _fmt_pct, True) hal_all_s = _bold_best(hal_all, _fmt_pct, False) acc_cost_s = _bold_best(acc_cost, _fmt_pct, True) hal_cost_s = _bold_best(hal_cost, _fmt_pct, False)
lines.append(r"\begin{table}[h]") lines.append( r"\caption{Overall metrics on the " + str(len(EVALUATED_COUNTRIES)) + r" head-to-head jurisdictions, golden-set rows with no" r" expert-filled field excluded." r" \emph{Acc.\ when filled} is the share of expert-filled cells the" r" system extracts correctly; \emph{Hallu.\ rate} is the share of" r" expert-empty cells where the system invented a value." r" The right block restricts the same metrics to the four cost-block" r" variables. Best per column in \textbf{bold} (lower is better for" r" Hallu.\ rate)." r"}" ) lines.append(r"\label{tab:overall}") lines.append(r"\centering\small") lines.append(r"\begin{tabular}{@{}lrr@{\hskip 12pt}rr@{}}") lines.append(r"\toprule") lines.append( r" & \multicolumn{2}{c}{All " + str(len(EVAL_FIELDS)) + r" evaluated fields} & \multicolumn{2}{c}{Cost block (" + str(len(COST_BLOCK)) + r" fields)} \\" ) lines.append(r"\cmidrule(lr){2-3}\cmidrule(l){4-5}") lines.append( r"System & Acc.\ when filled & Hallu.\ rate" r" & Acc.\ when filled & Hallu.\ rate \\" ) lines.append(r"\midrule") for i, (_, label) in enumerate(SYSTEMS): lines.append( f"{label} & {acc_all_s[i]} & {hal_all_s[i]}" f" & {acc_cost_s[i]} & {hal_cost_s[i]} \\\\" ) lines.append(r"\bottomrule") lines.append(r"\end{tabular}") lines.append(r"\end{table}") lines.append("") return "\n".join(lines)
def _print_console_summary(agg: dict[str, dict[str, dict[str, int]]]) -> None: """Quick human-readable echo so the user sees the numbers in the terminal too.""" print(f"{'system':<28} {'set':<5} {'Acc.filled':>11} {'Hallu':>6}") for model, _ in SYSTEMS: for tag in ("all", "cost"): m = _metrics(agg[model][tag]) print( f"{model:<28} {tag:<5} " f"{m['recall_when_filled']:>11.1%} {m['hallucination_rate']:>6.1%}" )
def main() -> None: logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[logging.StreamHandler(sys.stderr)], ) parser = argparse.ArgumentParser( prog="legex-quant-results", description="Render the Quantitative Results section + headline table.", ) parser.add_argument( "--input", type=Path, default=Path("data/analysis/per_country_per_column.csv"), help="per_country_per_column.csv produced by legex-analysis.", ) parser.add_argument( "--out", type=Path, default=Path("data/analysis/quant_results.tex"), help="Where to write the rendered LaTeX section.", ) args = parser.parse_args()
if not args.input.exists(): raise SystemExit( f"{args.input} not found — run `legex-analysis` first to generate it." ) agg = _aggregate(args.input) tex = render_section(agg) args.out.parent.mkdir(parents=True, exist_ok=True) args.out.write_text(tex, encoding="utf-8") log.info(f"wrote {args.out}") _print_console_summary(agg)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183"""Scrape full text from a goldenset xlsx's GOLDENSET sheet into a JSONL file.
For each row of the GOLDENSET sheet, fetches the URL in the ``link`` column(HTML or PDF), extracts text, and writes one JSON line in the same shape as``data/am/full_text.jsonl``:
{"case_id": "<slug>", "full_text": "case_id: <orig> link: <url> Quelle Text: <source> <body>"}
``case_id`` (key) is the filesystem-safe slug of the workbook's case_id;the body keeps the original case_id and link verbatim. Whitespace in thebody is collapsed to single spaces so each record stays on one line.
Usage: uv run python -m legex.scrape_full_text data/am/Goldenset_Armenia_final.xlsx uv run python -m legex.scrape_full_text data/gh/Goldenset_Ghana.xlsx --resume"""
from __future__ import annotations
import argparseimport jsonimport loggingimport reimport sysfrom pathlib import Path
import openpyxl
from legex.pdf_export.core import safe_slugfrom legex.pdf_export.urls import pick_bodyfrom legex.pdf_export.workbook import cell, header_map
log = logging.getLogger("legex.scrape_full_text")
_WS_RE = re.compile(r"\s+")
def normalize_ws(text: str) -> str: return _WS_RE.sub(" ", text).strip()
def build_full_text(case_id: str, link: str, source: str, body: str) -> str: return normalize_ws( f"case_id: {case_id} link: {link} Quelle Text: {source} {body}" )
def _load_existing_case_ids(out_path: Path) -> set[str]: seen: set[str] = set() with out_path.open("r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue try: rec = json.loads(line) except json.JSONDecodeError: continue cid = rec.get("case_id") if cid: seen.add(cid) return seen
def scrape_xlsx( xlsx: Path, out_path: Path, *, pause_s: float, req_timeout: float, limit: int | None, resume: bool,) -> int: wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True) if "GOLDENSET" not in wb.sheetnames: wb.close() log.error("no GOLDENSET sheet in %s", xlsx) return 0 ws = wb["GOLDENSET"] rows = ws.iter_rows(values_only=True) header_row = next(rows, None) if not header_row: wb.close() return 0 h = header_map(header_row) idx_case = h.get("case_id") idx_link = h.get("link") idx_text = h.get("full_text") if idx_link is None: wb.close() log.error("no 'link' column in %s", xlsx) return 0
existing: set[str] = set() mode = "w" if resume and out_path.exists(): existing = _load_existing_case_ids(out_path) mode = "a" log.info("resume: %d existing case_ids in %s", len(existing), out_path)
out_path.parent.mkdir(parents=True, exist_ok=True) written = 0 row_idx = 1 label = xlsx.parent.name with out_path.open(mode, encoding="utf-8") as out: for row in rows: row_idx += 1 if not row: continue link_val = (cell(row, idx_link) or "").strip() case_id_raw = cell(row, idx_case) sheet_full = cell(row, idx_text) if idx_text is not None else None if ( not str(case_id_raw or "").strip() and not link_val and not (sheet_full or "").strip() ): continue slug = safe_slug(case_id_raw, link_val or None, row_idx) if slug in existing: continue body, source = pick_body(link_val, sheet_full, pause_s, req_timeout) full = build_full_text( str(case_id_raw or "").strip(), link_val, source, body ) out.write( json.dumps({"case_id": slug, "full_text": full}, ensure_ascii=False) ) out.write("\n") out.flush() existing.add(slug) written += 1 if written % 10 == 0: log.info("[%s] %d written", label, written) if limit is not None and written >= limit: break wb.close() log.info("[%s] done: %d written -> %s", label, written, out_path) return written
def main() -> int: logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("xlsx", type=Path, help="Path to Goldenset_*.xlsx") ap.add_argument( "--out", type=Path, default=None, help="Output jsonl path (default: <xlsx.parent>/full_text.jsonl)", ) ap.add_argument( "--pause", type=float, default=0.5, help="Seconds between requests (default: 0.5)" ) ap.add_argument( "--timeout", type=float, default=28.0, help="Request timeout in seconds (default: 28)" ) ap.add_argument("--limit", type=int, default=None, help="Max rows to scrape") ap.add_argument( "--resume", action="store_true", help="Append to existing jsonl, skipping case_ids already present", ) args = ap.parse_args()
if not args.xlsx.is_file(): log.error("xlsx not found: %s", args.xlsx) return 1
out_path = args.out or (args.xlsx.parent / "full_text.jsonl") scrape_xlsx( args.xlsx, out_path, pause_s=args.pause, req_timeout=args.timeout, limit=args.limit, resume=args.resume, ) return 0
if __name__ == "__main__": sys.exit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Register new scrapers here."""
from legex.scrapers.al import ALScraperfrom legex.scrapers.am import AMScraperfrom legex.scrapers.at import ATScraperfrom legex.scrapers.au import AUScraperfrom legex.scrapers.base import BaseScraperfrom legex.scrapers.be import BEScraperfrom legex.scrapers.ch import CHScraperfrom legex.scrapers.de import DEScraperfrom legex.scrapers.fr import FRScraperfrom legex.scrapers.ge import GEScraperfrom legex.scrapers.gh import GHScraperfrom legex.scrapers.in_ import INScraperfrom legex.scrapers.it import ITScraperfrom legex.scrapers.kr import KRScraperfrom legex.scrapers.li import LIScraperfrom legex.scrapers.lu import LUScraperfrom legex.scrapers.nz import NZScraperfrom legex.scrapers.ph import PHScraperfrom legex.scrapers.rs import RSScraperfrom legex.scrapers.sg import SGScraperfrom legex.scrapers.xk import XKScraper
SCRAPERS: dict[str, type[BaseScraper]] = { "al": ALScraper, "am": AMScraper, "at": ATScraper, "au": AUScraper, "ch": CHScraper, "de": DEScraper, "fr": FRScraper, "ge": GEScraper, "gh": GHScraper, "in": INScraper, "it": ITScraper, "kr": KRScraper, "li": LIScraper, "lu": LUScraper, "nz": NZScraper, "ph": PHScraper, "rs": RSScraper, "sg": SGScraper, "xk": XKScraper,}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363"""Albanian Supreme Court (Gjykata e Lartë) via the Gatsby page-data JSON API.
Decisions are published as periodic and thematic bulletins under`/sq/lajme/buletini/`. Each bulletin's detail page exposes its decisionsinline as HTML strings inside `result.data.api.newsArticle.body[].content[].text_sq`,so we can extract full text without touching the pre-2020 .doc archive.
Civil filter: keep decisions tagged "Kolegji Civil" (Civil College) or"Kolegjet e Bashkuara" (United Colleges, mixed civil/penal)."""
import htmlimport loggingimport reimport timefrom datetime import datefrom typing import Any
import requests
from legex.models.base import Casefrom legex.scrapers.base import BaseScraper
log = logging.getLogger(__name__)
API_BASE = "https://www.gjykataelarte.gov.al/page-data"PUBLIC_BASE = "https://www.gjykataelarte.gov.al"USER_AGENT = "legex-research (open-data, friendly)"DELAY_SECONDS = 1.0MAX_LIST_PAGES = 15
# New-format header (periodik/tematik bulletins 2024+) — standalone line:# Vendimi nr. 00-2025-1613 (255), datë 21.10.2025 i Kolegjit Penal# Followed by Maksima / Fjalë kyçe / Përmbledhje sections._DECISION_HEADER_RE = re.compile( r"(Vendimi?\s+nr\.?\s*[\w\-\(\)\s]+?,?\s*dat[ëe]\s+\d{1,2}\.\d{1,2}\.\d{4}\s+i\s+Kolegj[a-zëÇçë ]+)", re.IGNORECASE,)
# Old-format mention (informativ/tematik bulletins 2022-2023) — appears inline:# Në vendimin nr.00-2022-635, datë 01.04.2022, ...# College is set by a section heading above ("Kolegji Civil i Gjykatës së Lartë")._OLD_DECISION_RE = re.compile( r"N[ëe]\s+vendim(?:in)?\s+nr[\.\s]*([\d\(\)\s\-––]+?)\s*,?\s*dat[ëe]\s+(\d{1,2})[\.,](\d{1,2})[\.,](\d{4})", re.IGNORECASE,)_COLLEGE_HEADING_RE = re.compile( r"Kolegj[i]?\s+(Civil|Penal|Administrativ|Administrative|Tregtar|" r"Bashkuar)[a-zëçÇË]*\s+(?:i\s+)?Gjykat", re.IGNORECASE,)# Short aliases used inline (KCGJL = Kolegji Civil, KPGJL = Kolegji Penal, KAGJL = Kolegji Administrativ)_INLINE_COLLEGE_RE = re.compile(r"\bK(C|P|A)GJL\b")_DOC_LINK_RE = re.compile( r"https?://gjykata-media\.s3\.eu-central-1\.amazonaws\.com/[\w\-\.\/]+\.doc", re.IGNORECASE,)
_DECISION_NUM_RE = re.compile(r"nr\.?\s*([\d\-\(\)\s]+?)\s*,", re.IGNORECASE)_DATE_RE = re.compile(r"dat[ëe]\s+(\d{1,2})\.(\d{1,2})\.(\d{4})")_KEYWORD_RE = re.compile( r"Fjal[ëe]\s*ky[çc]e\s*[-–—]\s*(.+?)(?=P[ëe]rmbledhje|Maksima|$)", re.DOTALL | re.IGNORECASE,)_MAXIMA_RE = re.compile( r"Maksima\s*[-–—]\s*(.+?)(?=Fjal[ëe]\s*ky[çc]e|P[ëe]rmbledhje|$)", re.DOTALL | re.IGNORECASE,)
def _strip_html(raw: str) -> str: """Remove HTML tags, decode entities, collapse whitespace.""" text = re.sub(r"<[^>]+>", "\n", raw) text = html.unescape(text) text = re.sub(r"\n{3,}", "\n\n", text) return text.strip()
def _detect_college(header: str) -> str: h = header.lower() if "civil" in h: return "civil" if "penal" in h: return "penal" if "administrat" in h: return "administrative" if "bashk" in h: return "united" return "unknown"
def _parse_iso_date(header: str) -> str | None: m = _DATE_RE.search(header) if not m: return None return f"{m.group(3)}-{m.group(2).zfill(2)}-{m.group(1).zfill(2)}"
def _parse_decision_number(header: str) -> str | None: m = _DECISION_NUM_RE.search(header) if not m: return None return re.sub(r"\s+", "", m.group(1))
def _fetch_json(session: requests.Session, url: str) -> dict[str, Any] | None: try: resp = session.get(url, timeout=30) except requests.RequestException as e: log.warning("AL request error %s: %s", url, e) return None if resp.status_code == 404: return None if resp.status_code != 200: log.warning("AL HTTP %d for %s", resp.status_code, url) return None try: return resp.json() except ValueError: log.warning("AL non-JSON response from %s", url) return None
def _list_bulletin_slugs(session: requests.Session) -> list[dict[str, Any]]: slugs: list[dict[str, Any]] = [] for page in range(1, MAX_LIST_PAGES + 1): url = ( f"{API_BASE}/sq/lajme/buletini/page-data.json" if page == 1 else f"{API_BASE}/sq/lajme/buletini/{page}/page-data.json" ) data = _fetch_json(session, url) if not data: break articles = ( data.get("result", {}).get("pageContext", {}).get("articles", []) ) if not articles: break for a in articles: slug = a.get("slug") if not slug: continue title_obj = a.get("title") if isinstance(title_obj, dict): title = title_obj.get("text_sq", "") or title_obj.get("text_en", "") else: title = title_obj or "" slugs.append( { "slug": slug, "publish_date": a.get("publishDate"), "title": title, } ) log.info("AL list page %d: %d bulletins (cumulative %d)", page, len(articles), len(slugs)) time.sleep(DELAY_SECONDS) return slugs
def _fetch_bulletin_html(session: requests.Session, slug: str) -> str: url = f"{API_BASE}/sq/lajme/buletini/{slug}/page-data.json" data = _fetch_json(session, url) if not data: return "" try: body = data["result"]["data"]["api"]["newsArticle"]["body"] except (KeyError, TypeError): return "" chunks: list[str] = [] for block in body: if "Paragraph" not in block.get("__typename", ""): continue for content in block.get("content", []) or []: txt = content.get("text_sq") or content.get("text_en") or "" if txt: chunks.append(txt) return "".join(chunks)
def _parse_decisions( bulletin_html: str, slug: str, bulletin_title: str) -> list[dict[str, Any]]: plain = _strip_html(bulletin_html) parts = _DECISION_HEADER_RE.split(plain) if len(parts) < 3: # Fall back to the older bulletin layout where decisions are # introduced inline by "Në vendimin nr. X, datë Y" mentions. return _parse_old_format(plain, slug, bulletin_title) decisions: list[dict[str, Any]] = [] i = 1 while i < len(parts) - 1: header = parts[i].strip() body = parts[i + 1].strip() i += 2 if len(body) < 200: continue decisions.append( { "header": header, "body": body, "decision_number": _parse_decision_number(header), "iso_date": _parse_iso_date(header), "college": _detect_college(header), "maxima": (m.group(1).strip() if (m := _MAXIMA_RE.search(body)) else None), "keywords": ( [k.strip() for k in re.split(r"[,;]", km.group(1)) if k.strip()] if (km := _KEYWORD_RE.search(body)) else [] ), "bulletin_slug": slug, "bulletin_title": bulletin_title, "doc_link": None, "format": "new", } ) return decisions
def _section_college_at(plain: str, pos: int) -> str: """Return the most recent college heading before pos in plain text.""" head = plain[:pos] last: str = "unknown" for m in _COLLEGE_HEADING_RE.finditer(head): last = _detect_college(m.group(0)) return last
def _inline_college_at(snippet: str) -> str: m = _INLINE_COLLEGE_RE.search(snippet) if not m: return "unknown" return {"C": "civil", "P": "penal", "A": "administrative"}.get(m.group(1), "unknown")
def _parse_old_format( plain: str, slug: str, bulletin_title: str) -> list[dict[str, Any]]: matches = list(_OLD_DECISION_RE.finditer(plain)) if not matches: return []
decisions: list[dict[str, Any]] = [] for idx, m in enumerate(matches): # body spans from this match to the next, capped at ~3000 chars. body_end = matches[idx + 1].start() if idx + 1 < len(matches) else m.end() + 3000 body = plain[m.start():body_end].strip() if len(body) < 150: continue
decision_num = re.sub(r"\s+", "", m.group(1)) iso_date = f"{m.group(4)}-{m.group(3).zfill(2)}-{m.group(2).zfill(2)}"
# Prefer a college signalled inline (KCGJL / KPGJL / KAGJL inside the # summary itself) over the section heading, since some bulletins mix # multiple colleges in a single section. college = _inline_college_at(body) if college == "unknown": college = _section_college_at(plain, m.start())
doc_link_m = _DOC_LINK_RE.search(body) doc_link = doc_link_m.group(0) if doc_link_m else None
decisions.append( { "header": body[:200], "body": body, "decision_number": decision_num, "iso_date": iso_date, "college": college, "maxima": None, "keywords": [], "bulletin_slug": slug, "bulletin_title": bulletin_title, "doc_link": doc_link, "format": "old", } ) return decisions
class ALScraper(BaseScraper): country = "Albanien"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: session = requests.Session() session.headers.update( {"User-Agent": USER_AGENT, "Accept": "application/json"} )
slugs = _list_bulletin_slugs(session) log.info("AL discovered %d bulletins", len(slugs))
seen: set[str] = set() cases: list[Case] = [] for info in slugs: raw_html = _fetch_bulletin_html(session, info["slug"]) time.sleep(DELAY_SECONDS) if not raw_html: continue decisions = _parse_decisions(raw_html, info["slug"], info["title"]) log.info("AL %s: %d decisions", info["slug"], len(decisions))
for d in decisions: decision_date: date | None = None if d["iso_date"]: try: decision_date = date.fromisoformat(d["iso_date"]) except ValueError: decision_date = None if start_date and decision_date and decision_date < start_date: continue if end_date and decision_date and decision_date > end_date: continue
case_id = d["decision_number"] or f"AL-{info['slug']}-{len(cases)}" if case_id in seen: continue seen.add(case_id)
full_text = f"{d['header']}\n\n{d['body']}" if d["format"] == "new" else d["body"] # Prefer the direct .doc URL on S3 (old-format bulletins expose # it); fall back to the bulletin page for new-format entries. link = d.get("doc_link") or f"{PUBLIC_BASE}/sq/lajme/buletini/{info['slug']}"
cases.append( Case( case_id=case_id, link=link, decision_date=decision_date, jurisdiction="al", language="sq", full_text=full_text, metadata={ "college": d["college"], "decision_number": d["decision_number"], "bulletin_slug": d["bulletin_slug"], "bulletin_title": d["bulletin_title"], "maxima": d["maxima"], "keywords": d["keywords"], "format": d["format"], "doc_link": d.get("doc_link"), }, ) )
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info("Collected %d Albania cases", len(cases)) return cases
@staticmethod def civil_filter(cases: list[Case]) -> list[Case]: kept = [ c for c in cases if (c.metadata or {}).get("college") in {"civil", "united"} ] log.info("AL civil_filter kept %d/%d", len(kept), len(cases)) return kept123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import loggingimport reimport sysimport timeimport urllib.requestfrom datetime import date, datetime
from legex.models.base import Casefrom legex.scrapers.base import BaseScraper
log = logging.getLogger(__name__)
BASE = "https://www.cassationcourt.am/en/decisions/?chamber=2&page="USER_AGENT = "FriendlyResearcher"MAX_PAGES = 30DELAY_SECONDS = 0.5CIVIL_CHAMBER_LABEL = "Քաղաքացիական"EMPTY_PAGE_MARKER = "Գրառումներ չկան"
_DATE_FMT_RE = re.compile(r"^\d{2}\.\d{2}\.\d{4}$")_DIV_RE = re.compile(r"<div>(.*?)</div>", re.DOTALL)
def _fetch_page(page: int) -> str | None: url = BASE + str(page) req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) try: with urllib.request.urlopen(req, timeout=30) as resp: return resp.read().decode("utf-8") except Exception as e: print(f" ERROR page {page}: {e}", file=sys.stderr) return None
def _parse_decisions(html: str) -> list[tuple[str, str, str]]: """Extract (iso_date, link, case_number) triples from a listing page.""" results: list[tuple[str, str, str]] = [] for block in html.split("resultListBody")[1:]: divs = _DIV_RE.findall(block) if len(divs) >= 3 and divs[2].strip() == CIVIL_CHAMBER_LABEL: date_str = divs[0].strip() case_num = divs[1].strip() if not _DATE_FMT_RE.match(date_str): continue try: iso_date = datetime.strptime(date_str, "%d.%m.%Y").strftime("%Y-%m-%d") except ValueError: iso_date = date_str case_anchor = case_num.replace("/", "-") link = f"https://www.cassationcourt.am/en/decisions/?chamber=2&page=1#case-{case_anchor}" results.append((iso_date, link, case_num)) return results
class AMScraper(BaseScraper): country = "Armenien"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: all_decisions: list[tuple[str, str, str]] = [] for page in range(1, MAX_PAGES + 1): log.info("AM fetching page %d", page) html = _fetch_page(page) if html is None: log.warning("AM page %d failed; stopping", page) break decisions = _parse_decisions(html) if not decisions: if EMPTY_PAGE_MARKER in html: log.info("AM no records on page %d; stopping", page) break log.info("AM no decisions parsed on page %d; continuing", page) continue log.info("AM page %d: %d decisions", page, len(decisions)) all_decisions.extend(decisions) time.sleep(DELAY_SECONDS)
# Dedupe by case number, preserving first occurrence (newest first). seen: set[str] = set() unique: list[tuple[str, str, str]] = [] for entry in all_decisions: _, _, case_num = entry if case_num in seen: continue seen.add(case_num) unique.append(entry) log.info("AM total unique civil decisions: %d", len(unique))
cases: list[Case] = [] for iso_date, link, case_num in unique: decision_date: date | None = None try: decision_date = date.fromisoformat(iso_date) except ValueError: decision_date = None
if start_date and decision_date and decision_date < start_date: continue if end_date and decision_date and decision_date > end_date: continue
cases.append(Case( case_id=case_num, link=link, decision_date=decision_date, jurisdiction="am", language="hy", full_text=None, metadata={"chamber": "civil"}, ))
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info("Collected %d Armenia cases", len(cases)) return cases123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310"""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 loggingimport reimport timefrom datetime import datefrom typing import Anyfrom xml.etree import ElementTree as ET
import requests
from legex.models.base import Casefrom 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 = 100RATE_DELAY_SECONDS = 1.0ENRICH_DELAY_SECONDS = 0.4USER_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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384import loggingimport refrom datetime import date
from datasets import load_dataset
from legex.models.base import Casefrom legex.scrapers.base import BaseScraper
DATASET_NAME = "isaacus/high-court-of-australia-cases"log = logging.getLogger(__name__)
_RE_CITATION = re.compile(r"\[(\d{4})\]\s*HCA\s*(\d+)")# HCA docket, for example"S94/2025", "P7/2024", "B15/2024". Registry letters seen: S/B/C/P/M/H/D._RE_DOCKET = re.compile(r"\b([SBCPMHD])(\d+)/(\d{4})\b")HCOURT_URL_TEMPLATE = "https://www.hcourt.gov.au/cases-and-judgments/cases/decided/case-{letter}{num}{year}"
class AUScraper(BaseScraper): country = "Australia"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: log.info(f"Loading {DATASET_NAME} …") dataset = load_dataset(DATASET_NAME, split="corpus") cases = [self._row_to_case(row) for row in dataset] cases = [c for c in cases if c is not None]
if start_date or end_date: cases = [ c for c in cases if (start_date is None or c.decision_date >= start_date) and (end_date is None or c.decision_date <= end_date) ] cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info(f"{len(cases)} cases after filtering") return cases
@staticmethod def _row_to_case(row: dict) -> Case | None: raw_date = row.get("date") if not raw_date: return None citation = row.get("citation") or "" m = _RE_CITATION.search(citation) case_id = f"[{m.group(1)}] HCA {m.group(2)}" if m else citation or None decision_date = raw_date.date() if hasattr(raw_date, "date") else date.fromisoformat(str(raw_date)[:10])
# We prefer the authoritative hcourt.gov.au per-case URL, built from the docket # number found in the first 2000 chars of the decision text. This gives around 95% hit rate. # For the remaining ~5% with no docket match we fall back to the dataset URL. text = row.get("text") or "" d = _RE_DOCKET.search(text[:2000]) if d: docket = f"{d.group(1)}{d.group(2)}/{d.group(3)}" link = HCOURT_URL_TEMPLATE.format( letter=d.group(1).lower(), num=d.group(2), year=d.group(3) ) else: docket = "" link = row.get("url")
return Case( case_id=case_id, link=link, decision_date=decision_date, jurisdiction="au", language="en", full_text=text or None, metadata={"citation": citation, "docket": docket}, )
@staticmethod def civil_filter(cases: list[Case]) -> list[Case]: # HCA is mixed civil/criminal/constitutional. Exclude the explicit criminal # pattern "v The King" / "v The Queen", everything else we treat as civil. return [ c for c in cases if " v The King" not in (c.metadata or {}).get("citation", "") and " v The Queen" not in (c.metadata or {}).get("citation", "") ]123456789101112131415161718192021222324252627282930from abc import ABC, abstractmethodfrom datetime import date
from legex.models.base import Case
class BaseScraper(ABC): country: str
@abstractmethod def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: pass
@staticmethod def civil_filter(cases: list[Case]) -> list[Case]: return list(cases)
@staticmethod def enrich(cases: list[Case]) -> list[Case]: """Post-sampling enrichment hook — runs on the 130 sampled cases only.
Default is a no-op. Scrapers that need expensive per-case work (e.g. downloading PDFs and extracting text) override this so the cost is paid only for the sampled set, not the full corpus. """ return list(cases)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301from __future__ import annotations
import loggingimport reimport timefrom datetime import datefrom html import unescapefrom urllib.parse import urljoin
import requestsfrom dateutil import parser as dateutil_parser
from legex.models.base import Casefrom legex.scrapers.base import BaseScraper
# Data source: https://juportal.be/zoekmachine/zoekformulier# We submit the official search form with civil case-number prefix "C." and# page through server-side "next_page" form actions.
log = logging.getLogger(__name__)
BASE_URL = "https://juportal.be"SEARCH_FORM_URL = f"{BASE_URL}/zoekmachine/zoekformulier"SEARCH_RESULTS_URL = f"{BASE_URL}/zoekmachine/zoekresultaten"DELAY_SECONDS = 3RETRY_DELAY_SECONDS = 30MAX_PAGES_PER_QUERY = 300
_RE_FORM_TOKEN = re.compile(r'name=["\']TOKEN["\'][^>]*value=["\']([^"\']*)', re.IGNORECASE)_RE_ACTION_VALUE = re.compile( r'<button[^>]*name=["\']action["\'][^>]*value=["\']([^"\']*)', re.IGNORECASE,)_RE_NEXT_VALUE = re.compile( r'<button[^>]*name=["\']next_page["\'][^>]*value=["\']([^"\']*)', re.IGNORECASE,)_RE_CONTENT_LINK = re.compile(r'href=["\'](/content/ECLI:BE:CASS:[^"\']+)["\']', re.IGNORECASE)_RE_ROLE = re.compile(r"Rolnummer:\s*([A-Z]\.[0-9]{2}\.[0-9]{4}\.[A-Z])", re.IGNORECASE)_RE_DATE = re.compile(r"Vonnis/arrest van\s+([0-9]{1,2}\s+[A-Za-z]+\s+[0-9]{4})", re.IGNORECASE)_RE_ECLI = re.compile(r"(ECLI:BE:CASS:[A-Z0-9:.]+)")_RE_RESULT_ROW_META = re.compile( r"Hof van Cassatie\s*-\s*([0-9]{1,2}\s+[A-Za-z]+\s+[0-9]{4})\s*-\s*([A-Z]\.[0-9]{2}\.[0-9]{4}\.[A-Z])", re.IGNORECASE,)
def _parse_date(text: str | None) -> date | None: if not text: return None cleaned = text.strip() try: return date.fromisoformat(cleaned) except ValueError: pass try: return dateutil_parser.parse(cleaned, dayfirst=True).date() except (ValueError, OverflowError, dateutil_parser.ParserError): return None
def _extract_token(html: str) -> str | None: match = _RE_FORM_TOKEN.search(html) return match.group(1) if match else None
def _extract_action_value(html: str) -> str | None: match = _RE_ACTION_VALUE.search(html) return match.group(1) if match else None
def _extract_next_value(html: str) -> str | None: match = _RE_NEXT_VALUE.search(html) return match.group(1) if match else None
def _extract_result_links(html: str) -> list[str]: links = [] seen: set[str] = set() for raw_link in _RE_CONTENT_LINK.findall(html): clean = raw_link.split("#", 1)[0] if ":ARR." not in clean: continue if clean in seen: continue seen.add(clean) links.append(urljoin(BASE_URL, clean)) return links
def _extract_result_cases(html: str) -> list[Case]: cases: list[Case] = [] seen: set[str] = set() chunks = html.split("<tr>") for chunk in chunks: link_match = _RE_CONTENT_LINK.search(chunk) if not link_match: continue rel = link_match.group(1).split("#", 1)[0] if ":ARR." not in rel: continue link = urljoin(BASE_URL, rel) if link in seen: continue seen.add(link)
ecli_match = _RE_ECLI.search(chunk) meta_match = _RE_RESULT_ROW_META.search(unescape(re.sub(r"<[^>]+>", " ", chunk))) if not meta_match: continue decision_date = _parse_date(meta_match.group(1)) case_id = meta_match.group(2).upper() if not case_id.startswith("C."): continue
cases.append( Case( case_id=case_id, link=link, decision_date=decision_date, jurisdiction="be", language="nl", full_text=None, metadata={ "ecli": (ecli_match.group(1).upper() if ecli_match else None), "source": "juportal.be", }, ) ) return cases
def _extract_case_id(page_text: str) -> str | None: match = _RE_ROLE.search(page_text) return match.group(1).upper() if match else None
def _extract_ecli(page_text: str) -> str | None: match = _RE_ECLI.search(page_text) return match.group(1).upper() if match else None
def _extract_decision_date(page_text: str) -> date | None: match = _RE_DATE.search(page_text) return _parse_date(match.group(1) if match else None)
def _extract_text(page_html: str) -> str | None: text = unescape(re.sub(r"<[^>]+>", "\n", page_html)) lines = [line.strip() for line in text.splitlines()] cleaned = [line for line in lines if line] return "\n".join(cleaned) if cleaned else None
class BEScraper(BaseScraper): country = "Belgium"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: start = start_date or date(2015, 1, 1) end = end_date or date.today() cases: list[Case] = [] seen: set[str] = set() session = requests.Session()
for year in range(start.year, end.year + 1): year_start = max(start, date(year, 1, 1)) year_end = min(end, date(year, 12, 31)) if year_start > year_end: continue year_cases = self._scrape_year(session, year_start, year_end) for case in year_cases: if not case.link or case.link in seen: continue seen.add(case.link) cases.append(case)
return cases
def _scrape_year( self, session: requests.Session, start_date: date, end_date: date, ) -> list[Case]: log.info("Belgium %s to %s", start_date.isoformat(), end_date.isoformat()) form_html = self._fetch_text(session, SEARCH_FORM_URL) if form_html is None: return [] token = _extract_token(form_html) action_value = _extract_action_value(form_html) if not token or not action_value: return []
payload = { "TOKEN": token, "action": action_value, "TRECHNOROLE": "C.", "TRECHDECISIONDE": start_date.isoformat(), "TRECHDECISIONA": end_date.isoformat(), "TRECHNPPAGE": "50", "TRECHORDER": "DATEDEC", "TRECHDESCASC": "DESC", "TRECHOPER": "AND", "TRECHLIMIT": "25000", "TRECHMODE": "SIMPLE", "TRECHSCORE": "1", "TRECHSHOWFICHES": "fiches", } page_html = self._post_text(session, SEARCH_FORM_URL, payload) if page_html is None: return []
results: list[Case] = [] seen_links: set[str] = set() for page_idx in range(1, MAX_PAGES_PER_QUERY + 1): links = _extract_result_links(page_html) if not links: break log.info("Belgium page %d: %d decision links", page_idx, len(links)) page_cases = _extract_result_cases(page_html) for case in page_cases: if not case.link or case.link in seen_links: continue seen_links.add(case.link) results.append(case)
next_value = _extract_next_value(page_html) next_token = _extract_token(page_html) if not next_value or not next_token: break time.sleep(DELAY_SECONDS) page_html = self._post_text( session, SEARCH_RESULTS_URL, {"TOKEN": next_token, "next_page": next_value}, ) if page_html is None: break
return [ c for c in results if c.decision_date is not None and start_date <= c.decision_date <= end_date ]
def _fetch_case(self, link: str) -> Case | None: html = self._fetch_url_text(link) if html is None: return None text = _extract_text(html) if text is None: return None
case_id = _extract_case_id(text) if not case_id or not case_id.startswith("C."): return None
decision_date = _extract_decision_date(text) ecli = _extract_ecli(text) return Case( case_id=case_id, link=link, decision_date=decision_date, jurisdiction="be", language="nl", full_text=text, metadata={"ecli": ecli, "source": "juportal.be"} if ecli else {"source": "juportal.be"}, )
@staticmethod def civil_filter(cases: list[Case]) -> list[Case]: return [c for c in cases if (c.case_id or "").startswith("C.")]
def _fetch_text(self, session: requests.Session, url: str) -> str | None: try: response = session.get(url, timeout=30) if response.status_code == 429: time.sleep(RETRY_DELAY_SECONDS) response = session.get(url, timeout=30) if not response.ok: return None return response.text except requests.RequestException: return None
def _post_text(self, session: requests.Session, url: str, data: dict[str, str]) -> str | None: try: response = session.post(url, data=data, timeout=30) if response.status_code == 429: time.sleep(RETRY_DELAY_SECONDS) response = session.post(url, data=data, timeout=30) if not response.ok: return None return response.text except requests.RequestException: return None
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import loggingimport refrom datetime import datefrom typing import Anyfrom urllib.parse import unquote
from datasets import load_dataset
from legex.models.base import Casefrom legex.scrapers.base import BaseScraper
DATASET_NAME = "voilaj/swiss-caselaw"log = logging.getLogger(__name__)
_RE_JUMPCGI = re.compile(r"JumpCGI\?id=\d{2}\.\d{2}\.\d{4}_([0-9][A-Z])_(\d+)/(\d{4})")_RE_AZA = re.compile(r"aza://\d{2}-\d{2}-\d{4}-([0-9][A-Z])_(\d+)-(\d{4})")
class CHScraper(BaseScraper): country = "Schweiz"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: log.info(f"Loading bger shard from {DATASET_NAME} …") dataset = load_dataset(DATASET_NAME, data_files="data/bger.parquet", split="train") cases = self._to_cases(dataset)
if start_date or end_date: cases = [ c for c in cases if c.decision_date is not None and (start_date is None or c.decision_date >= start_date) and (end_date is None or c.decision_date <= end_date) ] cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info(f"{len(cases)} cases after filtering") return cases
def _to_cases(self, dataset: Any) -> list[Case]: results: list[Case] = [] seen: set[str] = set() for row in dataset: link = (row.get("source_url") or "").strip() if not link or link in seen: continue seen.add(link)
raw_date = row.get("decision_date") decision_date = date.fromisoformat(raw_date) if raw_date else None case_id, chamber, division = self.parse_case_id(link)
metadata: dict[str, Any] = { k: v for k, v in row.items() if k not in ("source_url", "decision_date", "language", "full_text") and v is not None } if chamber is not None: metadata["chamber"] = chamber metadata["division"] = division
results.append(Case( case_id=case_id, link=link, decision_date=decision_date, jurisdiction="ch", language=(row.get("language") or "").strip().lower() or None, full_text=row.get("full_text"), metadata=metadata, )) return results
@staticmethod def parse_case_id(link: str | None) -> tuple[str | None, str | None, str | None]: if not link: return None, None, None m = _RE_JUMPCGI.search(unquote(link)) or _RE_AZA.search(unquote(link)) if not m: return None, None, None chamber, num, year = m.group(1), m.group(2), m.group(3) return f"{chamber}_{num}/{year}", chamber, chamber[0]
@staticmethod def civil_filter(cases: list[Case]) -> list[Case]: return [c for c in cases if (c.metadata or {}).get("division") in {"4", "5"}]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import loggingimport refrom datetime import date
from datasets import load_dataset
from legex.config import settingsfrom legex.models.base import Casefrom legex.scrapers.base import BaseScraper
DATASET_PATH = "openlegaldata/court-decisions-germany"DATASET_NAME = 'dump-20221018'# OpenLegalData shifts the `date` field for anonymity. Real year is encoded in# file_number as the trailing /YY slash-suffix, for example "XII ZR 17/18" to 2018.# Civil BGH senates are numbered with Roman numerals followed by ZR/ZB/ZA._RE_YEAR = re.compile(r"/(\d{2,4})\s*$")_RE_CIVIL = re.compile(r"^([IVXLCDM]+)\s+(ZR|ZB|ZA)\b")
log = logging.getLogger(__name__)
class DEScraper(BaseScraper): country = "Deutschland"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: log.info(f"Loading {DATASET_PATH} (gated; requires HF_TOKEN) …") dataset = load_dataset(path=DATASET_PATH, name=DATASET_NAME, split="train", token=settings.hf_token or None) cases = [ self._row_to_case(row) for row in dataset if (row.get("court") or {}).get("name") == "Bundesgerichtshof" ] cases = [c for c in cases if c is not None]
if start_date or end_date: start_year = start_date.year if start_date else 0 end_year = end_date.year if end_date else 9999 cases = [ c for c in cases if start_year <= (c.decision_date.year if c.decision_date else 0) <= end_year ] cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info(f"{len(cases)} BGH cases after year filter") return cases
@staticmethod def _row_to_case(row: dict) -> Case | None: file_number = row.get("file_number") or "" m = _RE_YEAR.search(file_number) if not m: return None year = int(m.group(1)) if year < 50: year += 2000 elif year < 100: year += 1900 # Use January 1 of the inferred year, the real day/month is shifted. decision_date = date(year, 1, 1) content = row.get("markdown_content") or row.get("content") or "" return Case( case_id=file_number, link=f"https://de.openlegaldata.io/case/{row.get('id')}", decision_date=decision_date, jurisdiction="de", language="de", full_text=content, metadata={ "ecli": row.get("ecli"), "type": row.get("type"), "slug": row.get("slug"), }, )
@staticmethod def civil_filter(cases: list[Case]) -> list[Case]: return [c for c in cases if _RE_CIVIL.match(c.case_id or "")]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182"""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 loggingimport osimport timefrom datetime import date
import requests
from legex.models.base import Casefrom 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 = 1000DELAY_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)}, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151import loggingimport reimport sysimport timeimport urllib.requestfrom datetime import date
from legex.models.base import Casefrom legex.scrapers.base import BaseScraper
log = logging.getLogger(__name__)
USER_AGENT = "FriendyResearcher"DELAY_SECONDS = 0.3URL_TEMPLATE = "https://www.supremecourt.ge/ka/fullcase/{nid}/1"
# Note: the sample is not random; it was assembled from manual searches across# multiple supreme-court listings. See the paper for sampling caveats._EXISTING_29 = {75795, 76240, 76234, 76198, 76209, 76215, 76205, 76201, 76238, 76202, 76203, 76204, 76211, 76218, 76219, 76220, 76221, 76225, 76188, 76190, 76187, 76182, 76185, 76186, 76177, 76178, 76191, 76199, 76200}
_SEARCH_19 = {75596, 70414, 33102, 72758, 73910, 75109, 73341, 74047, 73589, 73919, 70283, 73640, 69240, 69940, 66739, 67977, 70199, 73785, 72004}
_PROBE_76177 = {76179, 76180, 76181, 76183, 76184, 76189, 76192, 76193, 76194, 76195, 76196, 76197, 76206, 76207, 76208, 76212, 76213, 76214, 76216, 76228, 76229, 76230, 76231, 76232, 76233, 76236, 76237, 76239}
_PROBE_75500 = {75500, 75501, 75504, 75505, 75506, 75508, 75509, 75510, 75511, 75512, 75513, 75514, 75515, 75516, 75517, 75518, 75519, 75520, 75521, 75522, 75523, 75524, 75525, 75526, 75527, 75528, 75529, 75530, 75531, 75532, 75533, 75534, 75535, 75536, 75537, 75538, 75539, 75540, 75541, 75542, 75543, 75544, 75545, 75546, 75547, 75548, 75549, 75550, 75551, 75552, 75556, 75557, 75559, 75560, 75561, 75562, 75563, 75564, 75565, 75566, 75567, 75568, 75569, 75570, 75571, 75572, 75573, 75574, 75575, 75576, 75577, 75578, 75579, 75580, 75581, 75582, 75583, 75584, 75585, 75586}
def _all_case_ids() -> list[int]: ids = _EXISTING_29 | _SEARCH_19 | _PROBE_76177 | _PROBE_75500 # 33102 historically returns 500 — drop both string and int forms defensively. ids.discard("33102") # type: ignore[arg-type] ids.discard(33102) return sorted(int(x) for x in ids)
_GEO_MONTHS = { "იანვარი": "01", "თებერვალი": "02", "მარტი": "03", "აპრილი": "04", "მაისი": "05", "ივნისი": "06", "ივლისი": "07", "აგვისტო": "08", "სექტემბერი": "09", "ოქტომბერი": "10", "ნოემბერი": "11", "დეკემბერი": "12",}
_CASE_RE_PRIMARY = re.compile(r"(?:საქმე\s*N?:?\s*|საქმე\s*№)(ას-\d+-\d+)", re.DOTALL)_CASE_RE_FALLBACK = re.compile(r"(ას-\d+-\d+)")_DATE_DMY = re.compile( r"(\d{1,2})\s*(იანვარი|თებერვალი|მარტი|აპრილი|მაისი|ივნისი|ივლისი|აგვისტო|" r"სექტემბერი|ოქტომბერი|ნოემბერი|დეკემბერი)\s*,?\s*(\d{4})")_DATE_YDM = re.compile( r"(\d{4})\s*წელი\s*[,.]?\s*(\d{1,2})\s*(იანვარი|თებერვალი|მარტი|აპრილი|მაისი|" r"ივნისი|ივლისი|აგვისტო|სექტემბერი|ოქტომბერი|ნოემბერი|დეკემბერი)")_DATE_DMY_SPACED = re.compile( r"(\d{1,2})\s+(იანვარი|თებერვალი|მარტი|აპრილი|მაისი|ივნისი|ივლისი|აგვისტო|" r"სექტემბერი|ოქტომბერი|ნოემბერი|დეკემბერი)\s*,?\s*(\d{4})")
def _fetch_case(nid: int) -> tuple[str, str] | None: """Return (iso_date, case_number) for a case page, or None on error.""" url = URL_TEMPLATE.format(nid=nid) try: req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) with urllib.request.urlopen(req, timeout=30) as resp: html = resp.read().decode("utf-8", errors="replace") except Exception as e: sys.stderr.write(f" {nid}: ERROR - {e}\n") return None
case_m = _CASE_RE_PRIMARY.search(html) or _CASE_RE_FALLBACK.search(html[:5000]) case_id = case_m.group(1) if case_m else f"case_{nid}"
iso_date = "" date_m = _DATE_DMY.search(html) if date_m: iso_date = f"{date_m.group(3)}-{_GEO_MONTHS.get(date_m.group(2), '01')}-{date_m.group(1).zfill(2)}" else: date_m = _DATE_YDM.search(html) if date_m: year = date_m.group(1) day = date_m.group(2).zfill(2) month = _GEO_MONTHS.get(date_m.group(3), "01") iso_date = f"{year}-{month}-{day}" if not iso_date: date_m = _DATE_DMY_SPACED.search(html) if date_m: iso_date = f"{date_m.group(3)}-{_GEO_MONTHS.get(date_m.group(2), '01')}-{date_m.group(1).zfill(2)}"
return iso_date, case_id
class GEScraper(BaseScraper): country = "Georgien"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: ids = _all_case_ids() log.info("GE total candidate case IDs: %d", len(ids))
cases: list[Case] = [] for nid in ids: res = _fetch_case(nid) if res is None: time.sleep(DELAY_SECONDS) continue iso_date, case_id = res
decision_date: date | None = None if iso_date: try: decision_date = date.fromisoformat(iso_date) except ValueError: decision_date = None
if start_date and decision_date and decision_date < start_date: time.sleep(DELAY_SECONDS) continue if end_date and decision_date and decision_date > end_date: time.sleep(DELAY_SECONDS) continue
cases.append(Case( case_id=case_id, link=URL_TEMPLATE.format(nid=nid), decision_date=decision_date, jurisdiction="ge", language="ka", full_text=None, metadata={"site_id": nid}, )) sys.stderr.write(f" {nid}: date={iso_date}, case={case_id}\n") time.sleep(DELAY_SECONDS)
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info("Collected %d Georgia cases", len(cases)) return cases123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131"""Ghana Supreme Court via GhaLII (https://ghalii.org).
GhaLII publishes Supreme Court judgments under `/judgments/GHASC/`. Each entry exposes itscitation and decision date in the listing markup, so we can build a Goldenset from metadata alone.Full text is PDF-only on GhaLII and not extracted here, the labelers click the link to read the judgment."""
import htmlimport loggingimport reimport timefrom datetime import datefrom typing import Iterable
import requests
from legex.models.base import Casefrom legex.scrapers.base import BaseScraper
log = logging.getLogger(__name__)
BASE_URL = "https://ghalii.org"PAGE_DELAY_SECONDS = 0.5USER_AGENT = "legex-research (open-data, friendly)"MAX_PAGES_PER_YEAR = 20
_LINK_RE = re.compile( r'href="(/akn/gh[^"]*?/judgment/ghasc/(\d{4})/(\d+)/eng@(\d{4}-\d{2}-\d{2}))"' r'[^>]*data-key-link="document"[^>]*>([^<]+)</a>')_CRIMINAL_RE = re.compile(r"^\s*(the\s+)?republic\s+v(rs?|\.)?\b", re.IGNORECASE)
class GHScraper(BaseScraper): country = "Ghana"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: session = requests.Session() session.headers.update({"User-Agent": USER_AGENT})
# Per-year URLs give much better historical coverage than the global listing start_year = (start_date or date(2015, 1, 1)).year end_year = (end_date or date(2025, 12, 31)).year
cases: list[Case] = [] seen: set[str] = set() for year in range(start_year, end_year + 1): year_cases = self._scrape_year(session, year, start_date, end_date, seen) cases.extend(year_cases)
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info("Collected %d Ghana cases", len(cases)) return cases
def _scrape_year( self, session: requests.Session, year: int, start_date: date | None, end_date: date | None, seen: set[str], ) -> list[Case]: out: list[Case] = [] for page in range(1, MAX_PAGES_PER_YEAR + 1): url = f"{BASE_URL}/judgments/GHASC/{year}/?page={page}" try: resp = session.get(url, timeout=30) except Exception as e: log.warning("GH %d page %d request failed (%s); stopping year", year, page, e) break if resp.status_code == 404: break if resp.status_code != 200: log.warning("GH %d page %d HTTP %d; stopping year", year, page, resp.status_code) break
entries = list(self._parse_listing(resp.text)) if not entries: break
new_on_page = 0 for path, ent_year, number, iso_date, title in entries: try: decision_date = date.fromisoformat(iso_date) except ValueError: continue if start_date and decision_date < start_date: continue if end_date and decision_date > end_date: continue case_id = f"[{ent_year}] GHASC {number}" if case_id in seen: continue seen.add(case_id) new_on_page += 1 out.append( Case( case_id=case_id, link=f"{BASE_URL}{path}", decision_date=decision_date, jurisdiction="gh", language="en", full_text=None, metadata={ "title": html.unescape(title).strip(), "year": ent_year, "number": number, }, ) ) log.info("GH %d page %d: %d entries (%d new)", year, page, len(entries), new_on_page) if new_on_page == 0: break time.sleep(PAGE_DELAY_SECONDS) return out
@staticmethod def _parse_listing(html_text: str) -> Iterable[tuple[str, str, str, str, str]]: for match in _LINK_RE.finditer(html_text): yield match.group(1), match.group(2), match.group(3), match.group(4), match.group(5)
@staticmethod def civil_filter(cases: list[Case]) -> list[Case]: # Heuristic: drop criminal prosecutions "(The) Republic v(rs) X". kept = [c for c in cases if not _CRIMINAL_RE.match((c.metadata or {}).get("title", ""))] log.info("GH civil_filter kept %d/%d", len(kept), len(cases)) return kept123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461import argparseimport csvimport loggingimport randomimport reimport shutilimport tarfileimport tempfileimport timeimport urllib.requestimport zipfilefrom collections import defaultdictfrom datetime import date, datetimefrom pathlib import Pathfrom typing import Any
import pandas as pd
from legex.config import settingsfrom legex.models.base import Casefrom legex.scrapers.base import BaseScraper
log = logging.getLogger(__name__)
S3_BASE = "https://indian-supreme-court-judgments.s3.amazonaws.com"S3_URI_PREFIX = "s3://indian-supreme-court-judgments/"S3_HTTP_PREFIX = "https://indian-supreme-court-judgments.s3.amazonaws.com/"
PARQUET_CACHE = settings.data_dir / "cache" / "in" / "parquet_cache"TARGET_ROWS = 130CIVIL_RATIO = 0.75RANDOM_SEED = 42
SAMPLE_YEARS = [ 1950, 1955, 1960, 1965, 1970, 1975, 1980, 1985, 1990, 1995, 2000, 2005, 2010, 2013, 2015, 2017, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026,]
USER_AGENT_METADATA = "LegEx/1.0 (legal research project; CC-BY-4.0 dataset)"USER_AGENT_EXTRACT = "LegEx/1.0 (selected AWS open-data extraction)"
_CIVIL_CASE_NO_RE = re.compile( r"CIVIL\s+APPEAL|CIVIL\s+ORIGINAL|CIVIL\s+WRIT|CIVIL\s+REVIEW|CIVIL\s+SUIT|" r"CIVIL\s+SPECIAL|CIVIL\s+TRANSFER|CIVIL\s+CONTEMPT", re.IGNORECASE,)_CRIMINAL_CASE_NO_RE = re.compile( r"CRIMINAL\s+APPEAL|CRIMINAL\s+ORIGINAL|CRIMINAL\s+WRIT|CRIMINAL\s+REVIEW|CRIMINAL\s+MISC", re.IGNORECASE,)
_CRIMINAL_KEYWORDS = ( "murder", "homicide", "rape", "narcotic", "ndps", "penal code", "ipc section 302", "ipc 302", "offence under section", "punishable under section", "conviction", "sentence of", "life imprisonment", "acquittal", "criminal conspiracy", "arms act", "explosive", "terrorist", "tada", "prevention of corruption", "pocso", "dowry death", "culpable homicide", "kidnapping", "abduction",)_CIVIL_KEYWORDS = ( "arbitration", "contract", "property", "tax", "insurance", "compensation", "damages", "negligence", "motor accident", "service matter", "land acquisition", "tenancy", "rent", "family", "divorce", "succession", "inheritance", "will", "company", "corporate", "insolvency", "bankruptcy", "consumer", "labour", "employment", "pension", "writ petition", "constitution", "administrative", "revenue", "customs", "excise", "gst", "vat", "intellectual property", "trademark", "patent", "copyright", "environment", "forest", "mining", "electricity", "telecom", "competition", "securities", "exchange", "banking", "debt recovery", "sarfaesi", "education", "admission", "examination", "election", "defamation", "motor vehicles", "mact", "accident claim", "specific performance", "injunction", "possession", "partition", "easement", "adverse possession", "specific relief", "declaration", "mandamus",)_CIVIL_DISPOSAL = ("allowed", "partly allowed", "directions issued", "reference answered", "disposed off")
def _download_parquet(year: int) -> str | None: cache_path = PARQUET_CACHE / str(year) / "metadata.parquet" if cache_path.exists(): log.info("IN %d parquet cached (%d bytes)", year, cache_path.stat().st_size) return str(cache_path)
url = f"{S3_BASE}/metadata/parquet/year={year}/metadata.parquet" req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT_METADATA})
for attempt in range(3): try: with urllib.request.urlopen(req, timeout=30) as resp: data = resp.read() cache_path.parent.mkdir(parents=True, exist_ok=True) cache_path.write_bytes(data) log.info("IN %d parquet downloaded (%d bytes)", year, len(data)) return str(cache_path) except Exception as e: log.warning("IN %d parquet attempt %d failed: %s", year, attempt + 1, e) if attempt < 2: time.sleep(2 ** attempt) return None
def _is_likely_civil(disposal_nature: str | None, raw_html: str | None, title: str | None) -> bool: raw_html = raw_html if isinstance(raw_html, str) else "" has_civil_cno = bool(_CIVIL_CASE_NO_RE.search(raw_html)) has_criminal_cno = bool(_CRIMINAL_CASE_NO_RE.search(raw_html))
if has_civil_cno and not has_criminal_cno: return True if has_criminal_cno and not has_civil_cno: return False
dn_lower = (disposal_nature or "").lower() title_lower = (title or "").lower()
is_criminal_kw = any(kw in title_lower or kw in dn_lower for kw in _CRIMINAL_KEYWORDS) is_civil_kw = any(kw in title_lower or kw in dn_lower for kw in _CIVIL_KEYWORDS)
if is_criminal_kw and not is_civil_kw: return False if is_civil_kw: return True
return any(d in dn_lower for d in _CIVIL_DISPOSAL)
def _build_link(year: str, path_str: str) -> str | None: if not path_str or pd.isna(path_str): return None path_str = str(path_str).strip() tarball_name = path_str + "_EN.pdf" return f"s3://indian-supreme-court-judgments/data/tar/year={year}/english/english.tar#{tarball_name}"
def _parse_decision_date(date_val: Any) -> str | None: if pd.isna(date_val) or not date_val: return None date_str = str(date_val).strip() for fmt in ("%d-%m-%Y", "%Y-%m-%d", "%d/%m/%Y", "%m/%d/%Y", "%d.%m.%Y"): try: return datetime.strptime(date_str, fmt).strftime("%Y-%m-%d") except ValueError: continue return date_str
def _stratified_sample(pool: list[dict[str, Any]], n: int, rng: random.Random) -> list[dict[str, Any]]: if n <= 0 or not pool: return [] if n >= len(pool): return list(pool)
decades: dict[int, list[dict[str, Any]]] = {} for item in pool: decade = (item["year"] // 10) * 10 decades.setdefault(decade, []).append(item)
total = len(pool) decades_sorted = sorted(decades.keys()) allocated: dict[int, int] = {} for decade in decades_sorted: prop = len(decades[decade]) / total alloc = max(1, round(prop * n)) allocated[decade] = min(alloc, len(decades[decade]))
diff = n - sum(allocated.values()) while diff != 0: for decade in sorted(decades_sorted, key=lambda d: len(decades[d]), reverse=True): if diff == 0: break if diff > 0 and allocated.get(decade, 0) < len(decades[decade]): allocated[decade] += 1 diff -= 1 elif diff < 0 and allocated.get(decade, 0) > 1: allocated[decade] -= 1 diff += 1
result: list[dict[str, Any]] = [] for decade in decades_sorted: count = allocated.get(decade, 0) if count > 0: rng.shuffle(decades[decade]) result.extend(decades[decade][:count])
rng.shuffle(result) return result[:n]
class INScraper(BaseScraper): country = "Indien"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: rng = random.Random(RANDOM_SEED) years = SAMPLE_YEARS if start_date is not None: years = [y for y in years if y >= start_date.year] if end_date is not None: years = [y for y in years if y <= end_date.year]
PARQUET_CACHE.mkdir(parents=True, exist_ok=True)
log.info("IN downloading metadata parquets for %d years", len(years)) parquet_paths: list[str] = [] for year in years: path = _download_parquet(year) if path: parquet_paths.append(path) time.sleep(0.3)
if not parquet_paths: log.warning("IN no parquet metadata downloaded") return []
all_dfs: list[pd.DataFrame] = [] for pp in parquet_paths: try: df = pd.read_parquet(pp) year = int(Path(pp).parent.name) if "year" not in df.columns: df["year"] = str(year) all_dfs.append(df) log.info("IN %d: %d rows", year, len(df)) except Exception as e: log.warning("IN parquet %s load failed: %s", pp, e)
if not all_dfs: return []
combined = pd.concat(all_dfs, ignore_index=True) log.info("IN total combined rows: %d", len(combined))
candidates: list[dict[str, Any]] = [] seen_paths: set[str] = set() for _, row in combined.iterrows(): path_val = row.get("path", "") path_str = str(path_val).strip() if not pd.isna(path_val) else "" if not path_str or path_str in seen_paths: continue seen_paths.add(path_str)
year_val = str(row.get("year", "")).strip() if not year_val: continue try: year_int = int(year_val) except ValueError: continue
link = _build_link(year_val, path_str) iso_date = _parse_decision_date(row.get("decision_date"))
case_id_val = row.get("case_id", "") case_id = str(case_id_val).strip() if not pd.isna(case_id_val) else "" if not case_id: case_id = path_str
disposal_nature = str(row.get("disposal_nature", "")) if not pd.isna(row.get("disposal_nature", "")) else "" raw_html = str(row.get("raw_html", "")) if not pd.isna(row.get("raw_html", "")) else "" title_val = row.get("title", "") title = str(title_val) if not pd.isna(title_val) else ""
candidates.append({ "decision_date": iso_date, "link": link, "case_id": case_id, "year": year_int, "civil": _is_likely_civil(disposal_nature, raw_html, title), "disposal_nature": disposal_nature, "title": title[:120], })
log.info("IN total candidates: %d", len(candidates))
civil_target = int(TARGET_ROWS * CIVIL_RATIO) mixed_target = TARGET_ROWS - civil_target
civil_pool = [c for c in candidates if c["civil"]] other_pool = [c for c in candidates if not c["civil"]]
if len(civil_pool) < civil_target: civil_target = min(len(civil_pool), TARGET_ROWS) mixed_target = TARGET_ROWS - civil_target mixed_target = min(mixed_target, len(other_pool)) civil_target = TARGET_ROWS - mixed_target civil_target = min(civil_target, len(civil_pool))
civil_sampled = _stratified_sample(civil_pool, civil_target, rng) other_sampled = _stratified_sample(other_pool, mixed_target, rng)
sampled = civil_sampled + other_sampled rng.shuffle(sampled) log.info("IN sampled %d (%d civil + %d other)", len(sampled), len(civil_sampled), len(other_sampled))
cases: list[Case] = [] for item in sampled: decision_date: date | None = None if item["decision_date"]: try: decision_date = date.fromisoformat(item["decision_date"]) except ValueError: decision_date = None
if start_date and decision_date and decision_date < start_date: continue if end_date and decision_date and decision_date > end_date: continue
cases.append(Case( case_id=item["case_id"], link=item["link"], decision_date=decision_date, jurisdiction="in", language="en", full_text=None, metadata={ "year": item["year"], "civil": item["civil"], "disposal_nature": item["disposal_nature"], "title": item["title"], }, ))
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info("Collected %d India cases", len(cases)) return cases
# ── PDF extraction (post-step CLI: legex-india-extract) ───────────────
def _parse_s3_link(link: str) -> tuple[str, str]: if "#" not in link: raise ValueError(f"Missing TAR member fragment: {link}") tar_uri, member = link.split("#", 1) if not tar_uri.startswith(S3_URI_PREFIX): raise ValueError(f"Unexpected S3 URI: {tar_uri}") return tar_uri[len(S3_URI_PREFIX):], member
def _safe_name(value: str) -> str: return re.sub(r"[^A-Za-z0-9_.-]+", "_", value.strip()).strip("_") or "case"
def _download(url: str, dest: Path) -> None: req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT_EXTRACT}) with urllib.request.urlopen(req, timeout=600) as response, dest.open("wb") as out: shutil.copyfileobj(response, out)
def extract_judgment_pdfs( sample_csv: Path, out_zip: Path, work_dir: Path | None = None, dry_run: bool = False,) -> int: """Extract selected judgment PDFs from year-level S3 TAR archives.
Reads a CSV with a `link` column of the form `s3://indian-supreme-court-judgments/.../english.tar#file.pdf`, downloads each unique TAR once, extracts only the requested members into `out_zip`, and writes a `manifest.csv` member alongside them.
Returns the number of PDFs written. """ out_zip.parent.mkdir(parents=True, exist_ok=True) rows = list(csv.DictReader(sample_csv.open(encoding="utf-8-sig", newline=""))) grouped: dict[str, list[dict]] = defaultdict(list) for row in rows: tar_rel, member = _parse_s3_link(row["link"]) row["_tar_rel"] = tar_rel row["_member"] = member grouped[tar_rel].append(row)
log.info("IN extract: %d judgments across %d TAR archives", len(rows), len(grouped)) for tar_rel, tar_rows in sorted(grouped.items()): log.info(" %s: %d PDFs", tar_rel, len(tar_rows)) if dry_run: return 0
work_root = work_dir if work_dir else Path(tempfile.mkdtemp(prefix="india_extract_")) work_root.mkdir(parents=True, exist_ok=True) manifest_rows: list[dict[str, str]] = []
try: with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf: for tar_rel, tar_rows in sorted(grouped.items()): tar_url = S3_HTTP_PREFIX + tar_rel tar_path = work_root / _safe_name(tar_rel) log.info("IN extract: downloading %s", tar_url) _download(tar_url, tar_path) wanted = {row["_member"]: row for row in tar_rows} extracted = 0 with tarfile.open(tar_path) as tf: members = {m.name.rsplit("/", 1)[-1]: m for m in tf.getmembers() if m.isfile()} for member_name, row in wanted.items(): member = members.get(member_name) if member is None: log.warning("IN extract: missing %s in %s", member_name, tar_rel) continue src = tf.extractfile(member) if src is None: log.warning("IN extract: cannot extract %s", member_name) continue case_id = _safe_name(row.get("case_id") or member_name.removesuffix(".pdf")) arcname = f"pdf/{case_id}.pdf" zf.writestr(arcname, src.read()) manifest_rows.append({ "case_id": row.get("case_id", ""), "decision_date": row.get("decision_date", ""), "source_tar": tar_rel, "source_member": member_name, "zip_path": arcname, }) extracted += 1 log.info("IN extract: %d/%d from %s", extracted, len(tar_rows), tar_rel) tar_path.unlink(missing_ok=True)
manifest = "case_id,decision_date,source_tar,source_member,zip_path\n" for row in manifest_rows: manifest += ",".join( '"' + str(row[k]).replace('"', '""') + '"' for k in ("case_id", "decision_date", "source_tar", "source_member", "zip_path") ) + "\n" zf.writestr("manifest.csv", manifest) finally: try: work_root.rmdir() except OSError: pass
log.info("IN extract: wrote %s with %d PDFs", out_zip, len(manifest_rows)) return len(manifest_rows)
def _extract_cli() -> None: """Entry point for the `legex-india-extract` console script.""" parser = argparse.ArgumentParser( description="Extract selected Indian Supreme Court PDFs from AWS Open Data TAR archives.", ) parser.add_argument("--sample", required=True, help="sample_links.csv") parser.add_argument("--out", required=True, help="output zip path") parser.add_argument("--work-dir", default=None, help="temporary work directory") parser.add_argument("--dry-run", action="store_true") args = parser.parse_args()
extract_judgment_pdfs( sample_csv=Path(args.sample), out_zip=Path(args.out), work_dir=Path(args.work_dir) if args.work_dir else None, dry_run=args.dry_run, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190"""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 earliestdeposit-date with civil decisions (`kind:snciv`) is 2021."""
import htmlimport loggingimport refrom datetime import date, datetimefrom typing import Anyfrom urllib.parse import urlencode
import requestsimport urllib3
from legex.models.base import Casefrom 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 = 100FIELDS = ( "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")), }, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115import jsonimport loggingimport osimport timeimport urllib.parseimport urllib.requestfrom datetime import date
from legex.models.base import Casefrom legex.scrapers.base import BaseScraper
log = logging.getLogger(__name__)
API = "https://www.law.go.kr/DRF/lawSearch.do"USER_AGENT = "LegEx/1.0 South Korea precedent API"DEFAULT_QUERY = "손해배상"DEFAULT_DISPLAY = 100MAX_RESULTS = 130DELAY_SECONDS = 0.2
def _request_json(params: dict[str, str]) -> dict: query = urllib.parse.urlencode(params) req = urllib.request.Request( f"{API}?{query}", headers={"User-Agent": USER_AGENT}, ) with urllib.request.urlopen(req, timeout=60) as response: return json.loads(response.read().decode("utf-8"))
def _normalize_date(raw: str) -> str: if len(raw) == 8 and raw.isdigit(): return f"{raw[:4]}-{raw[4:6]}-{raw[6:]}" return raw
class KRScraper(BaseScraper): country = "Südkorea"
def __init__(self) -> None: self._oc = os.environ.get("LAW_GO_KR_OC", "").strip() if not self._oc: raise ValueError("LAW_GO_KR_OC is required. Set a registered law.go.kr Open API OC value.") self._query = os.environ.get("LAW_GO_KR_QUERY", DEFAULT_QUERY)
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: cases: list[Case] = [] page = 1 while len(cases) < MAX_RESULTS: params = { "OC": self._oc, "target": "prec", "type": "JSON", "query": self._query, "display": str(DEFAULT_DISPLAY), "page": str(page), } data = _request_json(params) if "result" in data and "실패" in str(data.get("result")): raise RuntimeError(json.dumps(data, ensure_ascii=False))
prec = data.get("PrecSearch") or data.get("precSearch") or data items = prec.get("prec") or prec.get("items") or [] if isinstance(items, dict): items = [items] if not items: break
for item in items: court = str(item.get("법원명") or item.get("courtName") or "") if court and "대법원" not in court: continue
raw_date = str(item.get("선고일자") or item.get("decisionDate") or "") iso_date = _normalize_date(raw_date) decision_date: date | None = None if iso_date: try: decision_date = date.fromisoformat(iso_date) except ValueError: decision_date = None
if start_date and decision_date and decision_date < start_date: continue if end_date and decision_date and decision_date > end_date: continue
case_no = str(item.get("사건번호") or item.get("caseNo") or item.get("판례일련번호") or "") title = str(item.get("사건명") or item.get("caseName") or item.get("판례명") or "") serial = str(item.get("판례일련번호") or item.get("ID") or "") link = f"https://www.law.go.kr/precInfoP.do?precSeq={serial}" if serial else ""
cases.append(Case( case_id=case_no or serial or None, link=link or None, decision_date=decision_date, jurisdiction="kr", language="ko", full_text=None, metadata={"case_title": title} if title else {}, )) if len(cases) >= MAX_RESULTS: break
page += 1 time.sleep(DELAY_SECONDS)
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info("Collected %d South Korea Supreme Court cases", len(cases)) return cases123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222"""Liechtenstein Oberster Gerichtshof (OGH) via gerichtsentscheidungen.li.
Endpoints discovered via the worldwidelaw/legal-sources project (AGPL-3.0).We reimplement the scraping based on the public AJAX endpoints.
Flow: 1. POST /methods.aspx/getAkten {"s": "OGH.<year>"} → list of (case_number, listing_url). 2. GET <listing_url> → results page with onclick="…default.aspx?z=…" per record. 3. GET <detail_url> → metadata divs (hEIItem, aktenzeichen) and the decision text (`<div class='eintrag'>`).
The OGH hears both civil and criminal appeals; the source has no civil/criminalflag, so `civil_filter()` is a text heuristic (presence of civil-law markerslike ABGB / ZPO and absence of criminal markers like StGB / StPO)."""
import htmlimport loggingimport reimport timefrom datetime import datefrom typing import Any
import requests
from legex.models.base import Casefrom legex.scrapers.base import BaseScraper
log = logging.getLogger(__name__)
BASE_URL = "https://www.gerichtsentscheidungen.li"AKTEN_URL = f"{BASE_URL}/methods.aspx/getAkten"USER_AGENT = "legex-research (open-data, friendly)"REQUEST_DELAY_SECONDS = 1.0
_ONCLICK_RE = re.compile(r"onclick=\"window\.location='(default\.aspx\?z=[^']+)'\"")_HEI_RE = re.compile(r"<div class='fL hEIItem'>([^<]+)</div>")_AKTEN_RE = re.compile( r"<div[^>]*class=['\"][^'\"]*aktenzeichen[^'\"]*['\"][^>]*>\s*([^<]+?)\s*</div>", re.IGNORECASE,)_EINTRAG_RE = re.compile( r"<div class=['\"]eintrag['\"][^>]*>(.*?)</div>\s*</td>", re.DOTALL,)_TAG_RE = re.compile(r"<[^>]+>")_XML_DECL_RE = re.compile(r"<\?xml[^>]*\?>")_WS_RE = re.compile(r"[ \t]+")_BLANK_LINES_RE = re.compile(r"\n{3,}")_DATE_RE = re.compile(r"^(\d{1,2})\.(\d{1,2})\.(\d{4})$")
CIVIL_MARKERS = ("ABGB", "ZPO", "Zivilrechtssache", "Klagsführer", "Beklagte")CRIMINAL_MARKERS = ("StGB", "StPO", "Angeklagte", "Strafsache")
def _parse_date(text: str) -> date | None: m = _DATE_RE.match((text or "").strip()) if not m: return None try: return date(int(m.group(3)), int(m.group(2)), int(m.group(1))) except ValueError: return None
def _clean_text(raw_html: str) -> str: text = _XML_DECL_RE.sub("", raw_html) text = _TAG_RE.sub(" ", text) text = html.unescape(text) text = _WS_RE.sub(" ", text) text = re.sub(r" ?\n ?", "\n", text) text = _BLANK_LINES_RE.sub("\n\n", text) return text.strip()
class LIScraper(BaseScraper): country = "Liechtenstein"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: start = start_date or date(2015, 1, 1) end = end_date or date(2025, 12, 31)
session = requests.Session() session.headers.update({"User-Agent": USER_AGENT})
cases: list[Case] = [] seen: set[str] = set()
for year in range(start.year, end.year + 1): rows = self._get_akten(session, f"OGH.{year}") log.info("LI OGH.%d: %d rows", year, len(rows)) for row in rows: if not isinstance(row, list) or len(row) < 2: continue case_number = (row[0] or "").strip() listing_path = (row[1] or "").strip() if not case_number or not listing_path or case_number in seen: continue detail_path = self._find_detail_path(session, listing_path) if not detail_path: continue case = self._fetch_detail(session, case_number, detail_path) if case is None: continue 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.add(case_number) cases.append(case)
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info("Collected %d Liechtenstein OGH cases", len(cases)) return cases
@staticmethod def _get_akten(session: requests.Session, prefix: str) -> list[Any]: try: resp = session.post( AKTEN_URL, json={"s": prefix}, headers={"Content-Type": "application/json; charset=utf-8"}, timeout=60, ) resp.raise_for_status() data = resp.json() except Exception as e: log.warning("LI getAkten(%s) failed (%s)", prefix, e) return [] time.sleep(REQUEST_DELAY_SECONDS) return data.get("d", []) or []
@staticmethod def _find_detail_path(session: requests.Session, listing_path: str) -> str | None: url = f"{BASE_URL}/{listing_path.lstrip('/')}" try: resp = session.get(url, timeout=60) resp.raise_for_status() except Exception as e: log.warning("LI listing fetch failed %s (%s)", listing_path, e) return None time.sleep(REQUEST_DELAY_SECONDS) for m in _ONCLICK_RE.finditer(resp.text): target = m.group(1) if "z=" in target and len(target) > 30: return target return None
def _fetch_detail( self, session: requests.Session, case_number: str, detail_path: str, ) -> Case | None: url = f"{BASE_URL}/{detail_path.lstrip('/')}" try: resp = session.get(url, timeout=60) resp.raise_for_status() except Exception as e: log.warning("LI detail fetch failed %s (%s)", case_number, e) return None time.sleep(REQUEST_DELAY_SECONDS) page = resp.text
items = _HEI_RE.findall(page) decision_date: date | None = None decision_type: str | None = None court: str | None = None for item in items: item = item.strip() if decision_date is None: d = _parse_date(item) if d is not None: decision_date = d continue if item in ("OGH", "StGH", "OG", "LG", "VGH"): court = item continue if item in ("Urteil", "Beschluss", "Entscheidung", "Gutachten"): decision_type = item
# Use the OGH decision number as the unique case_id. The underlying LG # `aktenzeichen` (e.g. "09 CG. 2011.232") is the case file at first # instance — it can repeat when one underlying case spawns multiple OGH # decisions (different appellants, split rulings) on the same day. akten_match = _AKTEN_RE.search(page) aktenzeichen = akten_match.group(1).strip() if akten_match else ""
text_match = _EINTRAG_RE.search(page) full_text = _clean_text(text_match.group(1)) if text_match else None
return Case( case_id=case_number, link=url, decision_date=decision_date, jurisdiction="li", language="de", full_text=full_text or None, metadata={ "court": court or "OGH", "decision_type": decision_type or "", "aktenzeichen": aktenzeichen, }, )
@staticmethod def civil_filter(cases: list[Case]) -> list[Case]: kept: list[Case] = [] for c in cases: text = c.full_text or "" if not text: continue if any(marker in text for marker in CRIMINAL_MARKERS): continue if not any(marker in text for marker in CIVIL_MARKERS): continue kept.append(c) log.info("LI civil_filter kept %d/%d", len(kept), len(cases)) return kept123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""Luxembourg Cour de cassation via data.public.lu open-data API.
Endpoint and dataset slug discovered via the worldwidelaw/legal-sources project(AGPL-3.0). We reimplement the scraping based on the public API.
The dataset (cour-de-cassation) ships PDF files whose names encode both thedecision date (YYYYMMDD prefix) and the civil/criminal split: criminal cassationPDFs are prefixed `penal`, civil/general cassation PDFs start with the date.We rely on that filename flag for `civil_filter()`.
Bandwidth optimisation: the Goldenset only needs `sample_n` cases (130). Welist all metadata up front and pre-sample 130 civil candidates using the sameseed as the downstream pipeline, then download + OCR PDFs only for thatshortlist. Downstream `random_sample(seed=0)` is deterministic, so it picks thesame 130 — and those 130 are the only Cases that carry `full_text`."""
import loggingimport randomimport reimport timefrom datetime import datefrom pathlib import Path
import pdfplumberimport requests
from legex.config import settingsfrom legex.models.base import Casefrom legex.scrapers.base import BaseScraper
log = logging.getLogger(__name__)
DATASET_URL = "https://data.public.lu/api/1/datasets/cour-de-cassation/"USER_AGENT = "legex-research (open-data, friendly)"DOWNLOAD_DELAY_SECONDS = 0.5PDF_TIMEOUT = 90
_FILENAME_RE = re.compile(r"^(penal)?(\d{4})(\d{2})(\d{2})-")_STRIP_SUFFIXES = ( "-pseudonymise-accessible.pdf", "-accessible.pdf", ".pdf",)
def _case_id_from_title(title: str) -> str: name = title for suffix in _STRIP_SUFFIXES: if name.endswith(suffix): name = name[: -len(suffix)] break return name
def _extract_pdf_text(path: Path) -> str | None: try: with pdfplumber.open(path) as pdf: pages = [page.extract_text() or "" for page in pdf.pages] text = "\n".join(p for p in pages if p).strip() return text or None except Exception as e: log.warning("LU pdfplumber failed for %s (%s)", path.name, e) return None
class LUScraper(BaseScraper): country = "Luxemburg"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: session = requests.Session() session.headers.update({"User-Agent": USER_AGENT, "Accept": "application/json"})
try: resp = session.get(DATASET_URL, timeout=60) resp.raise_for_status() dataset = resp.json() except Exception as e: log.warning("LU dataset fetch failed (%s); returning empty", e) return []
resources = dataset.get("resources", []) or [] log.info("LU resources listed: %d", len(resources))
cases: list[Case] = [] seen: set[str] = set()
for res in resources: title = res.get("title") or "" url = res.get("url") or "" if not title or not url: continue m = _FILENAME_RE.match(title) if not m: continue criminal = m.group(1) is not None try: decision_date = date(int(m.group(2)), int(m.group(3)), int(m.group(4))) except ValueError: continue if start_date and decision_date < start_date: continue if end_date and decision_date > end_date: continue
case_id = _case_id_from_title(title) if case_id in seen: continue seen.add(case_id)
cases.append( Case( case_id=case_id, link=url, decision_date=decision_date, jurisdiction="lu", language="fr", full_text=None, metadata={ "filename": title, "criminal_prefix": criminal, "resource_id": res.get("id"), }, ) )
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
# Pre-sample the civil shortlist using the same seed as the downstream # pipeline (legex.processing.filter_and_sample). Both samples operate on # the same ordered list, so the picks match — and we only need to # download/OCR PDFs for this shortlist. civil_cases = [c for c in cases if not c.metadata.get("criminal_prefix")] n = min(settings.sample_n, len(civil_cases)) shortlist = random.Random(settings.sample_seed).sample(civil_cases, n) shortlist_ids = {c.case_id for c in shortlist} log.info( "LU candidates: %d total (%d civil); downloading PDFs for %d sampled", len(cases), len(civil_cases), len(shortlist_ids), )
cache_dir = settings.data_dir / "cache" / "lu" cache_dir.mkdir(parents=True, exist_ok=True) downloaded = 0 for case in cases: if case.case_id not in shortlist_ids: continue pdf_path = cache_dir / f"{case.case_id}.pdf" if not pdf_path.exists(): try: r = session.get(case.link, timeout=PDF_TIMEOUT) r.raise_for_status() pdf_path.write_bytes(r.content) downloaded += 1 if downloaded % 25 == 0: log.info("LU downloaded %d PDFs", downloaded) time.sleep(DOWNLOAD_DELAY_SECONDS) except Exception as e: log.warning("LU PDF download failed %s (%s)", case.case_id, e) continue case.full_text = _extract_pdf_text(pdf_path)
log.info( "Collected %d Luxembourg cases (%d with full_text, %d criminal-prefixed)", len(cases), sum(1 for c in cases if c.full_text), sum(1 for c in cases if c.metadata.get("criminal_prefix")), ) return cases
@staticmethod def civil_filter(cases: list[Case]) -> list[Case]: kept = [c for c in cases if not (c.metadata or {}).get("criminal_prefix")] log.info("LU civil_filter kept %d/%d", len(kept), len(cases)) return kept123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214from __future__ import annotations
import hashlibimport loggingimport osimport reimport timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom datetime import datefrom pathlib import Path
import pypdfimport requestsfrom dateutil import parser as dateutil_parser
from legex.config import settingsfrom legex.models.base import Casefrom legex.scrapers.base import BaseScraper
# Data source: https://www.justice.govt.nz/jdo-search-api# This is the JSON API backing the JDO React frontend (justice.govt.nz/courts/decisions/jdo/).# No official public API exists; this endpoint is used by the site's own search UI.# Court filter: "SUPREME COURT".# Date is embedded in caseName: e.g. "... [2026] NZSC 18 _x000b_[20 March 2026]"
log = logging.getLogger(__name__)
BASE_URL = "https://www.justice.govt.nz"API_URL = f"{BASE_URL}/jdo-search-api"PAGE_SIZE = 50USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:149.0) Gecko/20100101 Firefox/149.0"DELAY_SECONDS = 1RETRY_DELAY_SECONDS = 30PDF_CACHE_DIR = settings.data_dir / "pdfs" / "nz"PDF_WORKERS = 8
_DATE_RE = re.compile(r"\[(\d{1,2}\s+\w+\s+\d{4})\]\s*$")_CITATION_RE = re.compile(r"\[(\d{4})\]\s*NZSC\s*(\d+)")
_API_PARAMS: dict = { "court": "SUPREME COURT", "location": "All", "judge": "", "counsel": "", "caseName": "", "fileNumber": "", "citation": "", "judgmentDate": "All", "minuteReference": "", "searchTerms": "", "sort": "judgmentdate desc",}
def _parse_date(text: str) -> date | None: text = text.strip() if not text: return None try: return date.fromisoformat(text) except ValueError: pass try: return dateutil_parser.parse(text, dayfirst=True).date() except (ValueError, OverflowError, dateutil_parser.ParserError): return None
def _pdf_cache_path(url: str) -> Path: h = hashlib.sha1(url.encode()).hexdigest()[:16] return PDF_CACHE_DIR / f"{h}.pdf"
def _fetch_pdf_text(url: str) -> str: pdf_path = _pdf_cache_path(url) if not pdf_path.exists(): pdf_path.parent.mkdir(parents=True, exist_ok=True) resp = requests.get(url, timeout=60) resp.raise_for_status() pdf_path.write_bytes(resp.content) reader = pypdf.PdfReader(str(pdf_path)) parts = [t for p in reader.pages if (t := (p.extract_text() or "").strip())] return "\n\n".join(parts)
def _fetch_page(session: requests.Session, page_num: int) -> list[dict] | None: params = {**_API_PARAMS, "page": page_num} try: resp = session.get(API_URL, params=params, timeout=15) if resp.status_code == 429: log.warning( "HTTP 429 on page %d — sleeping %ds then retrying", page_num, RETRY_DELAY_SECONDS ) time.sleep(RETRY_DELAY_SECONDS) resp = session.get(API_URL, params=params, timeout=15) if not resp.ok: log.warning("HTTP %d on page %d", resp.status_code, page_num) return None data = resp.json() return data if isinstance(data, list) else data.get("results", []) except (requests.RequestException, ValueError) as exc: log.warning("Error fetching page %d: %s", page_num, exc) return None
class NZScraper(BaseScraper): country = "New Zealand"
def __init__(self) -> None: self._cookie = os.getenv("NZ_WAF_COOKIE", "").strip() if not self._cookie: raise ValueError("NZ_WAF_COOKIE is required. Set the token from justice.govt.nz.")
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: session = requests.Session() session.headers.update( { "Accept": "*/*", "Accept-Language": "en-US,en;q=0.9", "Cookie": self._cookie, "Referer": "https://www.justice.govt.nz/courts/decisions/jdo/", "Sec-Fetch-Dest": "empty", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Site": "same-origin", "User-Agent": USER_AGENT, } )
cases: list[Case] = [] seen: set[str] = set()
page_num = 1 while True: log.info("Fetching page %d", page_num) items = _fetch_page(session, page_num)
if not items: log.info("Empty or failed page %d — stopping", page_num) break
all_before_start = True # for early termination when sorted desc for item in items: url_path = item.get("url", "") if not url_path: continue link = BASE_URL + url_path if link in seen: continue
case_name: str = item.get("caseName", "") decision_date: date | None = None m = _DATE_RE.search(case_name) if m: decision_date = _parse_date(m.group(1)) c = _CITATION_RE.search(case_name) case_id = f"[{c.group(1)}] NZSC {c.group(2)}" if c else None
if end_date and decision_date and decision_date > end_date: continue if start_date and decision_date and decision_date >= start_date: all_before_start = False if start_date and decision_date and decision_date < start_date: continue
seen.add(link) cases.append( Case( case_id=case_id, link=link, decision_date=decision_date, jurisdiction="nz", language="en", full_text=None, metadata={"caseName": case_name}, ) )
# Results sorted newest-first: once every item on a page predates # start_date, all subsequent pages will too. if start_date and all_before_start: log.info("All items on page %d predate start_date — stopping early", page_num) break
if len(items) < PAGE_SIZE: log.info("Last page at %d (%d items)", page_num, len(items)) break
time.sleep(DELAY_SECONDS) page_num += 1
log.info("Collected %d NZ Supreme Court cases", len(cases))
todo = [c for c in cases if c.link and not c.full_text] log.info("Fetching full_text for %d PDFs", len(todo)) done = failed = 0 with ThreadPoolExecutor(max_workers=PDF_WORKERS) as pool: futures = {pool.submit(_fetch_pdf_text, c.link): c for c in todo} for fut in as_completed(futures): case = futures[fut] try: case.full_text = fut.result() done += 1 except Exception as exc: failed += 1 log.warning("PDF fetch failed for %s: %s", case.case_id, exc) if (done + failed) % 25 == 0: log.info("PDF progress %d/%d (failed=%d)", done + failed, len(todo), failed) log.info("Hydrated %d PDFs (failed=%d)", done, failed) return cases123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import loggingimport reimport timefrom datetime import date, datetimefrom typing import Any
import requests
from legex.models.base import Casefrom legex.scrapers.base import BaseScraper
log = logging.getLogger(__name__)
HEADERS = {"User-Agent": "Mozilla/5.0 (compatible; LegalResearch/1.0)"}MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]DEFAULT_YEARS = list(range(2026, 2004, -1))MAX_CANDIDATES = 500DELAY_SECONDS = 0.3
_LINK_RE = re.compile(r"<a\s+href='[^']*showdocs/(\d+)/(\d+)'[^>]*>(.*?)</a>", re.DOTALL)_CASE_NO_RE = re.compile(r"<STRONG>\s*(.*?)\s*</STRONG>", re.DOTALL)_DATE_RE = re.compile( r"((?:January|February|March|April|May|June|July|August|September|October|November|December)" r"\s+\d{1,2},\s+\d{4})")
def _scrape_month(mon: str, year: int) -> tuple[list[dict[str, Any]], str | None]: """Scrape a single month's decisions page.""" url = f"https://elibrary.judiciary.gov.ph/thebookshelf/docmonth/{mon}/{year}/1" cases: list[dict[str, Any]] = [] try: r = requests.get(url, headers=HEADERS, timeout=30) r.raise_for_status() except Exception as e: return cases, str(e)
for doc_type, doc_id, inner_html in _LINK_RE.findall(r.text): cn_match = _CASE_NO_RE.search(inner_html) case_no = cn_match.group(1).strip() if cn_match else ""
date_str = "" d_match = _DATE_RE.search(inner_html) if d_match: try: dt = datetime.strptime(d_match.group(1), "%B %d, %Y") date_str = dt.strftime("%Y-%m-%d") except ValueError: pass
link = f"https://elibrary.judiciary.gov.ph/thebookshelf/showdocsfriendly/{doc_type}/{doc_id}" cases.append({"decision_date": date_str, "link": link, "case_id": case_no}) return cases, None
class PHScraper(BaseScraper): country = "Philippinen"
def scrape( self, start_date: date | None = None, end_date: date | None = None, ) -> list[Case]: years = DEFAULT_YEARS if end_date is not None: years = [y for y in years if y <= end_date.year] if start_date is not None: years = [y for y in years if y >= start_date.year]
rows: list[dict[str, Any]] = [] seen: set[str] = set() for year in years: if len(rows) >= MAX_CANDIDATES: break for mon in MONTHS: if len(rows) >= MAX_CANDIDATES: break month_rows, err = _scrape_month(mon, year) if err: log.warning("PH %s %s: %s", mon, year, err) else: for row in month_rows: if row["link"] in seen: continue seen.add(row["link"]) rows.append(row) log.info("PH %s %s: %d new (running %d)", mon, year, len(month_rows), len(rows)) time.sleep(DELAY_SECONDS)
cases: list[Case] = [] for row in rows: decision_date: date | None = None if row["decision_date"]: try: decision_date = date.fromisoformat(row["decision_date"]) except ValueError: decision_date = None
if start_date and decision_date and decision_date < start_date: continue if end_date and decision_date and decision_date > end_date: continue
cases.append(Case( case_id=row["case_id"] or None, link=row["link"], decision_date=decision_date, jurisdiction="ph", language="en", full_text=None, metadata={}, ))
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True) log.info("Collected %d Philippines cases", len(cases)) return cases.env.templateAdded+20
.gitignoreAdded+226
LICENSEAdded+21
README.md+88
convert_goldenset_to_jsonl.pyAdded+212
legex/__init__.pyAdded+1
legex/analysis.pyAdded+388
legex/config.pyAdded+40
legex/evaluation.pyAdded+419
legex/extract_raw_text.pyAdded+137
legex/harvey.pyAdded+214
legex/inference.pyAdded+560
legex/main.pyAdded+37
legex/models/__init__.pyAdded
legex/models/base.pyAdded+14
legex/models/classification.pyAdded+64
legex/pdf_export/__init__.pyAdded+5
legex/pdf_export/cli.pyAdded+119
legex/pdf_export/core.pyAdded+127
legex/pdf_export/font_keys.pyAdded+32
legex/pdf_export/sheet.pyAdded+74
legex/pdf_export/urls.pyAdded+185
legex/pdf_export/workbook.pyAdded+30
legex/plots.pyAdded+180
legex/processing.pyAdded+97
legex/prompts/__init__.pyAdded+53
legex/prompts/v1.pyAdded+113
legex/prompts/v2.pyAdded+86
legex/prompts/v3.pyAdded+99
legex/quant_results.pyAdded+295
legex/scrape_full_text.pyAdded+183
legex/scrapers/__init__.pyAdded+46
legex/scrapers/al.pyAdded+363
legex/scrapers/am.pyAdded+117
legex/scrapers/at.pyAdded+310
legex/scrapers/au.pyAdded+84
legex/scrapers/base.pyAdded+30
legex/scrapers/be.pyAdded+301
legex/scrapers/ch.pyAdded+86
legex/scrapers/de.pyAdded+79
legex/scrapers/fr.pyAdded+182
legex/scrapers/ge.pyAdded+151
legex/scrapers/gh.pyAdded+131
legex/scrapers/in_.pyAdded+461
legex/scrapers/it.pyAdded+190
legex/scrapers/kr.pyAdded+115
legex/scrapers/li.pyAdded+222
legex/scrapers/lu.pyAdded+181
legex/scrapers/nz.pyAdded+214
legex/scrapers/ph.pyAdded+117