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
- .env.template +20 -0
- .gitignore +226 -0
- LICENSE +21 -0
- README.md +88 -0
- convert_goldenset_to_jsonl.py +212 -0
- legex/__init__.py +1 -0
- legex/analysis.py +388 -0
- legex/config.py +40 -0
- legex/evaluation.py +419 -0
- legex/extract_raw_text.py +137 -0
- legex/harvey.py +214 -0
- legex/inference.py +560 -0
- legex/main.py +37 -0
- legex/models/__init__.py +0 -0
- legex/models/base.py +14 -0
- legex/models/classification.py +64 -0
- legex/pdf_export/__init__.py +5 -0
- legex/pdf_export/cli.py +119 -0
- legex/pdf_export/core.py +127 -0
- legex/pdf_export/font_keys.py +32 -0
- legex/pdf_export/sheet.py +74 -0
- legex/pdf_export/urls.py +185 -0
- legex/pdf_export/workbook.py +30 -0
- legex/plots.py +180 -0
- legex/processing.py +97 -0
- legex/prompts/__init__.py +53 -0
- legex/prompts/v1.py +113 -0
- legex/prompts/v2.py +86 -0
- legex/prompts/v3.py +99 -0
- legex/quant_results.py +295 -0
- legex/scrape_full_text.py +183 -0
- legex/scrapers/__init__.py +46 -0
- legex/scrapers/al.py +363 -0
- legex/scrapers/am.py +117 -0
- legex/scrapers/at.py +310 -0
- legex/scrapers/au.py +84 -0
- legex/scrapers/base.py +30 -0
- legex/scrapers/be.py +301 -0
- legex/scrapers/ch.py +86 -0
- legex/scrapers/de.py +79 -0
- legex/scrapers/fr.py +182 -0
- legex/scrapers/ge.py +151 -0
- legex/scrapers/gh.py +131 -0
- legex/scrapers/in_.py +461 -0
- legex/scrapers/it.py +190 -0
- legex/scrapers/kr.py +115 -0
- legex/scrapers/li.py +222 -0
- legex/scrapers/lu.py +181 -0
- legex/scrapers/nz.py +214 -0
- legex/scrapers/ph.py +117 -0
.env.template
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copy to `.env` and edit.
|
| 2 |
+
REPO_ROOT=
|
| 3 |
+
|
| 4 |
+
# France, see PISTE Judilibre
|
| 5 |
+
JUDILIBRE_CLIENT_ID=
|
| 6 |
+
JUDILIBRE_CLIENT_SECRET=
|
| 7 |
+
|
| 8 |
+
# Germanay, gated HF dataset openlegaldata/court-decisions-germany)
|
| 9 |
+
HF_TOKEN=
|
| 10 |
+
|
| 11 |
+
# Korea, set a registered law.go.kr Open API OC value.
|
| 12 |
+
LAW_GO_KR_OC=
|
| 13 |
+
|
| 14 |
+
# New Zealand, set the token from justice.govt.nz
|
| 15 |
+
NZ_WAF_COOKIE=
|
| 16 |
+
# See https://docs.litellm.ai/docs/providers for the full list of env var names.
|
| 17 |
+
OPENAI_API_KEY=
|
| 18 |
+
ANTHROPIC_API_KEY=
|
| 19 |
+
GEMINI_API_KEY=
|
| 20 |
+
# ...
|
.gitignore
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Byte-compiled / optimized / DLL files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[codz]
|
| 4 |
+
*$py.class
|
| 5 |
+
*.pdf
|
| 6 |
+
|
| 7 |
+
# C extensions
|
| 8 |
+
*.so
|
| 9 |
+
|
| 10 |
+
# Distribution / packaging
|
| 11 |
+
.Python
|
| 12 |
+
build/
|
| 13 |
+
develop-eggs/
|
| 14 |
+
dist/
|
| 15 |
+
downloads/
|
| 16 |
+
eggs/
|
| 17 |
+
.eggs/
|
| 18 |
+
lib/
|
| 19 |
+
lib64/
|
| 20 |
+
parts/
|
| 21 |
+
sdist/
|
| 22 |
+
var/
|
| 23 |
+
wheels/
|
| 24 |
+
share/python-wheels/
|
| 25 |
+
*.egg-info/
|
| 26 |
+
.installed.cfg
|
| 27 |
+
*.egg
|
| 28 |
+
MANIFEST
|
| 29 |
+
|
| 30 |
+
# PyInstaller
|
| 31 |
+
# Usually these files are written by a python script from a template
|
| 32 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 33 |
+
*.manifest
|
| 34 |
+
*.spec
|
| 35 |
+
|
| 36 |
+
# Installer logs
|
| 37 |
+
pip-log.txt
|
| 38 |
+
pip-delete-this-directory.txt
|
| 39 |
+
|
| 40 |
+
# Unit test / coverage reports
|
| 41 |
+
htmlcov/
|
| 42 |
+
.tox/
|
| 43 |
+
.nox/
|
| 44 |
+
.coverage
|
| 45 |
+
.coverage.*
|
| 46 |
+
.cache
|
| 47 |
+
nosetests.xml
|
| 48 |
+
coverage.xml
|
| 49 |
+
*.cover
|
| 50 |
+
*.py.cover
|
| 51 |
+
.hypothesis/
|
| 52 |
+
.pytest_cache/
|
| 53 |
+
cover/
|
| 54 |
+
|
| 55 |
+
# Translations
|
| 56 |
+
*.mo
|
| 57 |
+
*.pot
|
| 58 |
+
|
| 59 |
+
# Django stuff:
|
| 60 |
+
*.log
|
| 61 |
+
local_settings.py
|
| 62 |
+
db.sqlite3
|
| 63 |
+
db.sqlite3-journal
|
| 64 |
+
|
| 65 |
+
# Flask stuff:
|
| 66 |
+
instance/
|
| 67 |
+
.webassets-cache
|
| 68 |
+
|
| 69 |
+
# Scrapy stuff:
|
| 70 |
+
.scrapy
|
| 71 |
+
|
| 72 |
+
# Sphinx documentation
|
| 73 |
+
docs/_build/
|
| 74 |
+
|
| 75 |
+
# PyBuilder
|
| 76 |
+
.pybuilder/
|
| 77 |
+
target/
|
| 78 |
+
|
| 79 |
+
# Jupyter Notebook
|
| 80 |
+
.ipynb_checkpoints
|
| 81 |
+
|
| 82 |
+
# IPython
|
| 83 |
+
profile_default/
|
| 84 |
+
ipython_config.py
|
| 85 |
+
|
| 86 |
+
# pyenv
|
| 87 |
+
# For a library or package, you might want to ignore these files since the code is
|
| 88 |
+
# intended to run in multiple environments; otherwise, check them in:
|
| 89 |
+
# .python-version
|
| 90 |
+
|
| 91 |
+
# pipenv
|
| 92 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
| 93 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
| 94 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
| 95 |
+
# install all needed dependencies.
|
| 96 |
+
#Pipfile.lock
|
| 97 |
+
|
| 98 |
+
# UV
|
| 99 |
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
| 100 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 101 |
+
# commonly ignored for libraries.
|
| 102 |
+
#uv.lock
|
| 103 |
+
|
| 104 |
+
# poetry
|
| 105 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
| 106 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 107 |
+
# commonly ignored for libraries.
|
| 108 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
| 109 |
+
#poetry.lock
|
| 110 |
+
#poetry.toml
|
| 111 |
+
|
| 112 |
+
# pdm
|
| 113 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
| 114 |
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
| 115 |
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
| 116 |
+
#pdm.lock
|
| 117 |
+
#pdm.toml
|
| 118 |
+
.pdm-python
|
| 119 |
+
.pdm-build/
|
| 120 |
+
|
| 121 |
+
# pixi
|
| 122 |
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
| 123 |
+
#pixi.lock
|
| 124 |
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
| 125 |
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
| 126 |
+
.pixi
|
| 127 |
+
|
| 128 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
| 129 |
+
__pypackages__/
|
| 130 |
+
|
| 131 |
+
# Celery stuff
|
| 132 |
+
celerybeat-schedule
|
| 133 |
+
celerybeat.pid
|
| 134 |
+
|
| 135 |
+
# SageMath parsed files
|
| 136 |
+
*.sage.py
|
| 137 |
+
|
| 138 |
+
# Environments
|
| 139 |
+
.env
|
| 140 |
+
.envrc
|
| 141 |
+
.venv
|
| 142 |
+
env/
|
| 143 |
+
venv/
|
| 144 |
+
ENV/
|
| 145 |
+
env.bak/
|
| 146 |
+
venv.bak/
|
| 147 |
+
|
| 148 |
+
# Spyder project settings
|
| 149 |
+
.spyderproject
|
| 150 |
+
.spyproject
|
| 151 |
+
|
| 152 |
+
# Rope project settings
|
| 153 |
+
.ropeproject
|
| 154 |
+
|
| 155 |
+
# mkdocs documentation
|
| 156 |
+
/site
|
| 157 |
+
|
| 158 |
+
# mypy
|
| 159 |
+
.mypy_cache/
|
| 160 |
+
.dmypy.json
|
| 161 |
+
dmypy.json
|
| 162 |
+
|
| 163 |
+
# Pyre type checker
|
| 164 |
+
.pyre/
|
| 165 |
+
|
| 166 |
+
# pytype static type analyzer
|
| 167 |
+
.pytype/
|
| 168 |
+
|
| 169 |
+
# Cython debug symbols
|
| 170 |
+
cython_debug/
|
| 171 |
+
|
| 172 |
+
# PyCharm
|
| 173 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
| 174 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
| 175 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
| 176 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
| 177 |
+
#.idea/
|
| 178 |
+
|
| 179 |
+
# Abstra
|
| 180 |
+
# Abstra is an AI-powered process automation framework.
|
| 181 |
+
# Ignore directories containing user credentials, local state, and settings.
|
| 182 |
+
# Learn more at https://abstra.io/docs
|
| 183 |
+
.abstra/
|
| 184 |
+
|
| 185 |
+
# Visual Studio Code
|
| 186 |
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
| 187 |
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
| 188 |
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
| 189 |
+
# you could uncomment the following to ignore the entire vscode folder
|
| 190 |
+
# .vscode/
|
| 191 |
+
|
| 192 |
+
# Ruff stuff:
|
| 193 |
+
.ruff_cache/
|
| 194 |
+
|
| 195 |
+
# PyPI configuration file
|
| 196 |
+
.pypirc
|
| 197 |
+
|
| 198 |
+
# Cursor
|
| 199 |
+
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
| 200 |
+
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
| 201 |
+
# refer to https://docs.cursor.com/context/ignore-files
|
| 202 |
+
.cursorignore
|
| 203 |
+
.cursorindexingignore
|
| 204 |
+
|
| 205 |
+
# Marimo
|
| 206 |
+
marimo/_static/
|
| 207 |
+
marimo/_lsp/
|
| 208 |
+
__marimo__/
|
| 209 |
+
|
| 210 |
+
# Project data
|
| 211 |
+
data/raw/*
|
| 212 |
+
data/processed/*
|
| 213 |
+
data/pdf/*
|
| 214 |
+
!data/raw/.gitkeep
|
| 215 |
+
!data/processed/.gitkeep
|
| 216 |
+
|
| 217 |
+
# Downloaded fonts for PDF export (legex-pdf)
|
| 218 |
+
legex/pdf_export/_fonts/
|
| 219 |
+
|
| 220 |
+
# IDE
|
| 221 |
+
.idea
|
| 222 |
+
.claude
|
| 223 |
+
.DS_Store
|
| 224 |
+
Pipfile
|
| 225 |
+
/data/cache
|
| 226 |
+
!data/raw/harvey.xlsx
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Anonymous Authors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
CHANGED
|
@@ -1,3 +1,91 @@
|
|
| 1 |
---
|
| 2 |
license: mit
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: mit
|
| 3 |
+
pretty_name: "LEGEX Code: Scrapers, Inference and Evaluation Pipeline"
|
| 4 |
+
tags:
|
| 5 |
+
- legal
|
| 6 |
+
- benchmark
|
| 7 |
+
- code
|
| 8 |
+
- llm-evaluation
|
| 9 |
+
- information-extraction
|
| 10 |
---
|
| 11 |
+
|
| 12 |
+
# LEGEX Code, Scrapers, Inference and Evaluation Pipeline
|
| 13 |
+
|
| 14 |
+
Python source for the LEGEX benchmark of civil-judgment review-table
|
| 15 |
+
extraction. This repository contains:
|
| 16 |
+
|
| 17 |
+
- Scrapers for 19 jurisdictions (per-court HTML / API / HuggingFace
|
| 18 |
+
pull) in [`legex/scrapers/`](legex/scrapers/).
|
| 19 |
+
- Inference pipeline that calls Harvey, Gemini and OpenAI APIs against
|
| 20 |
+
a schema-constrained 14-field review table
|
| 21 |
+
([`legex/inference.py`](legex/inference.py),
|
| 22 |
+
[`legex/harvey.py`](legex/harvey.py),
|
| 23 |
+
[`legex/models/classification.py`](legex/models/classification.py)).
|
| 24 |
+
- Evaluation that compares system outputs against expert-coded gold
|
| 25 |
+
cells ([`legex/evaluation.py`](legex/evaluation.py)), aggregates across
|
| 26 |
+
jurisdictions ([`legex/analysis.py`](legex/analysis.py)), and renders
|
| 27 |
+
paper tables ([`legex/quant_results.py`](legex/quant_results.py)).
|
| 28 |
+
- Conversion script [`convert_goldenset_to_jsonl.py`](convert_goldenset_to_jsonl.py)
|
| 29 |
+
— turns the source XLSX goldensets into the JSONL format used by
|
| 30 |
+
[`legexbenchmark/goldensets`](https://huggingface.co/datasets/legexbenchmark/goldensets).
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
## Setup
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
git clone https://huggingface.co/datasets/legexbenchmark/code legex-code
|
| 37 |
+
cd legex-code
|
| 38 |
+
uv sync
|
| 39 |
+
cp .env.template .env
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
Required tokens depend on which scrapers / models you run, see
|
| 43 |
+
[`.env.template`](.env.template).
|
| 44 |
+
|
| 45 |
+
## End-to-end workflow
|
| 46 |
+
|
| 47 |
+
```bash
|
| 48 |
+
# Acquire raw judgments per jurisdiction.
|
| 49 |
+
uv run legex-run
|
| 50 |
+
|
| 51 |
+
# Run inference for one system on one jurisdiction, Harvey has do be done separately as this is a commercial tool
|
| 52 |
+
uv run legex-classify --country us --model gpt-5.4-mini --full_text
|
| 53 |
+
|
| 54 |
+
# Evaluate one system on one jurisdiction.
|
| 55 |
+
uv run legex-evaluate --country us --system gpt
|
| 56 |
+
|
| 57 |
+
# Aggregate across all 12 evaluated jurisdictions and 3 systems.
|
| 58 |
+
uv run legex-analysis --out data/analysis
|
| 59 |
+
|
| 60 |
+
# Render the paper-headline LaTeX table.
|
| 61 |
+
uv run legex-quant-results \
|
| 62 |
+
--input data/analysis/per_country_per_column.csv \
|
| 63 |
+
--out data/analysis/quant_results.tex
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
To evaluate against the published goldensets and inference outputs, pull
|
| 67 |
+
the two data repos into the expected layout:
|
| 68 |
+
|
| 69 |
+
```bash
|
| 70 |
+
huggingface-cli download legexbenchmark/goldensets --repo-type dataset --local-dir data --include "data/*"
|
| 71 |
+
huggingface-cli download legexbenchmark/inference-results --repo-type dataset --local-dir data --include "data/*"
|
| 72 |
+
# After these, data/<cc>/ contains goldenset_<cc>.jsonl + inference_*.csv
|
| 73 |
+
uv run legex-analysis --out data/analysis
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
## CLI entrypoints
|
| 77 |
+
|
| 78 |
+
| Command | Module | Purpose |
|
| 79 |
+
|---|---|---|
|
| 80 |
+
| `legex-run` | `legex.main:main` | Top-level scrape + filter + sample pipeline. |
|
| 81 |
+
| `legex-classify` | `legex.inference:main` | Run an LLM over the goldenset and write predictions to CSV. |
|
| 82 |
+
| `legex-harvey-ingest` | `legex.harvey:main` | Ingest a Harvey Vault Review export into the per-jurisdiction CSV format. |
|
| 83 |
+
| `legex-evaluate` | `legex.evaluation:main` | Per-country, per-field bucket counts and recall / hallucination. |
|
| 84 |
+
| `legex-analysis` | `legex.analysis:main` | Cross-jurisdiction analysis → CSV + LaTeX tables. |
|
| 85 |
+
| `legex-quant-results` | `legex.quant_results:main` | Paper-headline summary from the analysis CSV. |
|
| 86 |
+
| `legex-pdf` | `legex.pdf_export.cli:main` | Render per-row PDFs from a goldenset workbook. |
|
| 87 |
+
| `legex-plots` | `legex.plots:main` | Plot helpers used in the paper. |
|
| 88 |
+
|
| 89 |
+
## License
|
| 90 |
+
|
| 91 |
+
MIT.
|
convert_goldenset_to_jsonl.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Convert handcrafted Goldenset XLSX files to anonymised JSONL.
|
| 3 |
+
|
| 4 |
+
For each ``Goldenset_*_final*.xlsx`` workbook under ``<data-dir>/<cc>/`` the
|
| 5 |
+
GOLDENSET sheet is read, rows that the expert annotator did not fully
|
| 6 |
+
classify are dropped (criterion: ``legal_subject_judgement`` must be
|
| 7 |
+
populated, which the annotators used as the marker that a row has been
|
| 8 |
+
substantively reviewed), and the remaining rows are written to
|
| 9 |
+
``<out-dir>/<cc>/goldenset_<cc>.jsonl`` as one JSON object per line.
|
| 10 |
+
|
| 11 |
+
Each output record contains the case identifiers (``case_id``, ``link``,
|
| 12 |
+
``full_text``) followed by the 14 schema fields defined in
|
| 13 |
+
``legex/models/classification.py``. ``full_text`` falls back to
|
| 14 |
+
``<data-dir>/<cc>/full_text.jsonl`` when the XLSX cell is empty, mirroring the
|
| 15 |
+
behaviour of ``legex.inference._read_goldenset_cases``.
|
| 16 |
+
|
| 17 |
+
Usage
|
| 18 |
+
-----
|
| 19 |
+
python convert_goldenset_to_jsonl.py \
|
| 20 |
+
--data-dir ../data \
|
| 21 |
+
--out-dir ./data
|
| 22 |
+
|
| 23 |
+
Without arguments the script assumes ``./data`` for both inputs and outputs and
|
| 24 |
+
processes the 19 jurisdictions of the paper.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
import json
|
| 31 |
+
import sys
|
| 32 |
+
from datetime import date, datetime
|
| 33 |
+
from pathlib import Path
|
| 34 |
+
from typing import Any, Iterable
|
| 35 |
+
|
| 36 |
+
from openpyxl import load_workbook
|
| 37 |
+
|
| 38 |
+
JURISDICTIONS = (
|
| 39 |
+
"am", "au", "be", "br", "ch", "de", "es", "fr", "ge", "hk",
|
| 40 |
+
"in", "np", "nz", "ph", "rs", "sg", "tw", "uk", "us",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
SCHEMA_FIELDS = (
|
| 44 |
+
"legal_subject_judgement",
|
| 45 |
+
"trial_start_date",
|
| 46 |
+
"trial_end_date",
|
| 47 |
+
"dispute_value_nominal",
|
| 48 |
+
"Currency_dispute_value_nominal",
|
| 49 |
+
"plaintiff_loosing_share",
|
| 50 |
+
"court_cost_awarded_nominal",
|
| 51 |
+
"Currency_court_cost_awarded_nominal",
|
| 52 |
+
"party_compensation_awarded_nominal",
|
| 53 |
+
"Currency_party_compensation_awarded_nominal",
|
| 54 |
+
"plaintiffs_all_count",
|
| 55 |
+
"defendants_all_count",
|
| 56 |
+
"plaintiff_no1_ISIC1_industry_category",
|
| 57 |
+
"defendant_no1_ISIC1_industry_category",
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
EMPTY_LITERALS = frozenset({"", "none", "null", "nan"})
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def normalise(value: Any) -> Any:
|
| 64 |
+
if value is None:
|
| 65 |
+
return None
|
| 66 |
+
if isinstance(value, datetime):
|
| 67 |
+
return value.date().isoformat()
|
| 68 |
+
if isinstance(value, date):
|
| 69 |
+
return value.isoformat()
|
| 70 |
+
if isinstance(value, float):
|
| 71 |
+
if value != value: # NaN
|
| 72 |
+
return None
|
| 73 |
+
if value.is_integer():
|
| 74 |
+
return int(value)
|
| 75 |
+
return value
|
| 76 |
+
if isinstance(value, int):
|
| 77 |
+
return value
|
| 78 |
+
s = str(value).strip()
|
| 79 |
+
if s.lower() in EMPTY_LITERALS:
|
| 80 |
+
return None
|
| 81 |
+
return s
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def find_goldenset_xlsx(data_dir: Path, cc: str) -> Path | None:
|
| 85 |
+
"""Return the *_final*.xlsx workbook for a jurisdiction, if any."""
|
| 86 |
+
jurisdiction_dir = data_dir / cc
|
| 87 |
+
if not jurisdiction_dir.exists():
|
| 88 |
+
return None
|
| 89 |
+
matches = sorted(jurisdiction_dir.glob("*_final*.xlsx"))
|
| 90 |
+
if not matches:
|
| 91 |
+
matches = sorted(jurisdiction_dir.glob("*Goldenset*.xlsx"))
|
| 92 |
+
return matches[0] if matches else None
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def find_goldenset_sheet(workbook):
|
| 96 |
+
for name in workbook.sheetnames:
|
| 97 |
+
if name.upper().startswith("GOLDENSET"):
|
| 98 |
+
return workbook[name]
|
| 99 |
+
raise ValueError(f"No GOLDENSET sheet in {workbook.sheetnames}")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def load_full_text_fallback(data_dir: Path, cc: str) -> dict[str, str]:
|
| 103 |
+
path = data_dir / cc / "full_text.jsonl"
|
| 104 |
+
if not path.exists():
|
| 105 |
+
return {}
|
| 106 |
+
fallback: dict[str, str] = {}
|
| 107 |
+
for line in path.read_text(encoding="utf-8").splitlines():
|
| 108 |
+
if not line.strip():
|
| 109 |
+
continue
|
| 110 |
+
record = json.loads(line)
|
| 111 |
+
case_id = record.get("case_id") or record.get("id")
|
| 112 |
+
text = record.get("full_text") or record.get("text")
|
| 113 |
+
if case_id and text:
|
| 114 |
+
fallback[str(case_id)] = str(text)
|
| 115 |
+
return fallback
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def convert_workbook(xlsx_path: Path, fallback: dict[str, str]) -> list[dict[str, Any]]:
|
| 119 |
+
wb = load_workbook(xlsx_path, read_only=True, data_only=True)
|
| 120 |
+
ws = find_goldenset_sheet(wb)
|
| 121 |
+
|
| 122 |
+
row_iter: Iterable[tuple] = ws.iter_rows(values_only=True)
|
| 123 |
+
header = [str(c) if c is not None else "" for c in next(row_iter)]
|
| 124 |
+
if "case_id" not in header:
|
| 125 |
+
raise ValueError(f"{xlsx_path} GOLDENSET sheet missing case_id column")
|
| 126 |
+
|
| 127 |
+
records: list[dict[str, Any]] = []
|
| 128 |
+
for row in row_iter:
|
| 129 |
+
if not any(row):
|
| 130 |
+
continue
|
| 131 |
+
cells = dict(zip(header, row))
|
| 132 |
+
case_id = normalise(cells.get("case_id"))
|
| 133 |
+
if not case_id:
|
| 134 |
+
continue
|
| 135 |
+
labels = {field: normalise(cells.get(field)) for field in SCHEMA_FIELDS}
|
| 136 |
+
if labels["legal_subject_judgement"] is None:
|
| 137 |
+
continue
|
| 138 |
+
full_text = normalise(cells.get("full_text"))
|
| 139 |
+
if not full_text:
|
| 140 |
+
full_text = fallback.get(str(case_id))
|
| 141 |
+
record: dict[str, Any] = {
|
| 142 |
+
"case_id": str(case_id),
|
| 143 |
+
"link": normalise(cells.get("link")),
|
| 144 |
+
"full_text": full_text,
|
| 145 |
+
}
|
| 146 |
+
record.update(labels)
|
| 147 |
+
records.append(record)
|
| 148 |
+
return records
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def write_jsonl(records: list[dict[str, Any]], out_path: Path) -> None:
|
| 152 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 153 |
+
with out_path.open("w", encoding="utf-8") as f:
|
| 154 |
+
for record in records:
|
| 155 |
+
f.write(json.dumps(record, ensure_ascii=False) + "\n")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def main(argv: list[str] | None = None) -> int:
|
| 159 |
+
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 160 |
+
parser.add_argument(
|
| 161 |
+
"--data-dir",
|
| 162 |
+
type=Path,
|
| 163 |
+
default=Path("data"),
|
| 164 |
+
help="Directory containing <cc>/Goldenset_*_final*.xlsx workbooks.",
|
| 165 |
+
)
|
| 166 |
+
parser.add_argument(
|
| 167 |
+
"--out-dir",
|
| 168 |
+
type=Path,
|
| 169 |
+
default=Path("data"),
|
| 170 |
+
help="Directory to write goldenset_<cc>.jsonl files into (per jurisdiction).",
|
| 171 |
+
)
|
| 172 |
+
parser.add_argument(
|
| 173 |
+
"--jurisdictions",
|
| 174 |
+
nargs="+",
|
| 175 |
+
default=list(JURISDICTIONS),
|
| 176 |
+
help="ISO codes to process (default: the 19 jurisdictions of the paper).",
|
| 177 |
+
)
|
| 178 |
+
parser.add_argument(
|
| 179 |
+
"--dry-run",
|
| 180 |
+
action="store_true",
|
| 181 |
+
help="Report counts without writing JSONL files.",
|
| 182 |
+
)
|
| 183 |
+
args = parser.parse_args(argv)
|
| 184 |
+
|
| 185 |
+
data_dir: Path = args.data_dir.resolve()
|
| 186 |
+
out_dir: Path = args.out_dir.resolve()
|
| 187 |
+
|
| 188 |
+
total = 0
|
| 189 |
+
missing: list[str] = []
|
| 190 |
+
for cc in args.jurisdictions:
|
| 191 |
+
xlsx = find_goldenset_xlsx(data_dir, cc)
|
| 192 |
+
if xlsx is None:
|
| 193 |
+
missing.append(cc)
|
| 194 |
+
print(f"[{cc}] no Goldenset XLSX found in {data_dir / cc}", file=sys.stderr)
|
| 195 |
+
continue
|
| 196 |
+
fallback = load_full_text_fallback(data_dir, cc)
|
| 197 |
+
records = convert_workbook(xlsx, fallback)
|
| 198 |
+
out_path = out_dir / cc / f"goldenset_{cc}.jsonl"
|
| 199 |
+
if not args.dry_run:
|
| 200 |
+
write_jsonl(records, out_path)
|
| 201 |
+
print(f"[{cc}] {xlsx.name} -> {out_path.relative_to(out_dir.parent)}: {len(records)} rows")
|
| 202 |
+
total += len(records)
|
| 203 |
+
|
| 204 |
+
print(f"\nTotal: {total} rows across {len(args.jurisdictions) - len(missing)} jurisdictions.")
|
| 205 |
+
if missing:
|
| 206 |
+
print(f"Missing XLSX for: {', '.join(missing)}", file=sys.stderr)
|
| 207 |
+
return 1
|
| 208 |
+
return 0
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
if __name__ == "__main__":
|
| 212 |
+
raise SystemExit(main())
|
legex/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""legex — Extract structured data from legal decisions with LLMs."""
|
legex/analysis.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cross-jurisdiction analysis of Goldenset vs prediction CSVs.
|
| 2 |
+
|
| 3 |
+
Builds on `legex.evaluation.score_country`: reuses the (tp, mismatch, missed,
|
| 4 |
+
hallucinated, tn) per-cell buckets and exposes paper-headline aggregates —
|
| 5 |
+
hallucination rate, recall-when-filled, miss rate — across countries, fields,
|
| 6 |
+
models, legal traditions, and language families.
|
| 7 |
+
|
| 8 |
+
Outputs CSV + LaTeX tables under ``--out`` (default ``data/analysis``).
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import csv
|
| 13 |
+
import logging
|
| 14 |
+
import re
|
| 15 |
+
import sys
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
from legex.config import settings
|
| 20 |
+
from legex.evaluation import SYSTEMS, _BUCKETS, _derived, score_country
|
| 21 |
+
from legex.utils import evaluable_countries
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Paper §A. Static maps — adding a jurisdiction = adding two entries.
|
| 27 |
+
LEGAL_TRADITION: dict[str, str] = {
|
| 28 |
+
"au": "common", "hk": "common", "in": "common", "nz": "common",
|
| 29 |
+
"sg": "common", "uk": "common", "us": "common", "gh": "common",
|
| 30 |
+
"ph": "common",
|
| 31 |
+
"am": "civil", "at": "civil", "be": "civil", "br": "civil",
|
| 32 |
+
"ch": "civil", "de": "civil", "es": "civil", "fr": "civil",
|
| 33 |
+
"ge": "civil", "it": "civil", "li": "civil", "lu": "civil",
|
| 34 |
+
"np": "civil", "rs": "civil", "tw": "civil", "xk": "civil",
|
| 35 |
+
"al": "civil",
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
LANGUAGE_FAMILY: dict[str, str] = {
|
| 39 |
+
"au": "en-latin", "hk": "en-latin", "in": "en-latin", "nz": "en-latin",
|
| 40 |
+
"sg": "en-latin", "uk": "en-latin", "us": "en-latin", "gh": "en-latin",
|
| 41 |
+
"ph": "en-latin",
|
| 42 |
+
"at": "eu-latin", "be": "eu-latin", "br": "eu-latin", "ch": "eu-latin",
|
| 43 |
+
"de": "eu-latin", "es": "eu-latin", "fr": "eu-latin", "it": "eu-latin",
|
| 44 |
+
"li": "eu-latin", "lu": "eu-latin", "rs": "eu-latin", "al": "eu-latin",
|
| 45 |
+
"xk": "eu-latin",
|
| 46 |
+
"am": "non-latin", "ge": "non-latin", "np": "non-latin", "tw": "non-latin",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
COST_BLOCK: tuple[str, ...] = (
|
| 51 |
+
"dispute_value_nominal",
|
| 52 |
+
"plaintiff_loosing_share",
|
| 53 |
+
"court_cost_awarded_nominal",
|
| 54 |
+
"party_compensation_awarded_nominal",
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
DERIVED_KEYS = (
|
| 59 |
+
"accuracy",
|
| 60 |
+
"recall_when_filled",
|
| 61 |
+
"precision_when_emitted",
|
| 62 |
+
"hallucination_rate",
|
| 63 |
+
"miss_rate",
|
| 64 |
+
"wrong_when_both_filled",
|
| 65 |
+
"f1",
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def derived_metrics(c: dict[str, int]) -> dict[str, float]:
|
| 70 |
+
"""Seven paper-headline metrics from a single bucket counter."""
|
| 71 |
+
tp, mism, miss, hallu, tn = c["tp"], c["mismatch"], c["missed"], c["hallucinated"], c["tn"]
|
| 72 |
+
total = tp + mism + miss + hallu + tn
|
| 73 |
+
filled_gold = tp + mism + miss
|
| 74 |
+
emitted = tp + mism + hallu
|
| 75 |
+
empty_gold = hallu + tn
|
| 76 |
+
both_filled = tp + mism
|
| 77 |
+
p, r, f1 = _derived(c)
|
| 78 |
+
return {
|
| 79 |
+
"accuracy": (tp + tn) / total if total else 0.0,
|
| 80 |
+
"recall_when_filled": r,
|
| 81 |
+
"precision_when_emitted": p,
|
| 82 |
+
"hallucination_rate": hallu / empty_gold if empty_gold else 0.0,
|
| 83 |
+
"miss_rate": miss / filled_gold if filled_gold else 0.0,
|
| 84 |
+
"wrong_when_both_filled": mism / both_filled if both_filled else 0.0,
|
| 85 |
+
"f1": f1,
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def add_buckets(a: dict[str, int], b: dict[str, int]) -> dict[str, int]:
|
| 90 |
+
return {k: a.get(k, 0) + b.get(k, 0) for k in _BUCKETS}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def sum_buckets(counters: dict[str, dict[str, int]], cols: tuple[str, ...] | None = None) -> dict[str, int]:
|
| 94 |
+
"""Sum bucket counts across `cols` (or all columns when None)."""
|
| 95 |
+
out = {k: 0 for k in _BUCKETS}
|
| 96 |
+
for col, c in counters.items():
|
| 97 |
+
if cols is not None and col not in cols:
|
| 98 |
+
continue
|
| 99 |
+
for k in _BUCKETS:
|
| 100 |
+
out[k] += c[k]
|
| 101 |
+
return out
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
_INFERENCE_CSV_RE = re.compile(r"^inference_(.+)\.csv$")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def models_present(cc: str) -> list[str]:
|
| 108 |
+
"""Which systems have an inference_<system>.csv on disk for `cc`."""
|
| 109 |
+
d = settings.data_dir / cc
|
| 110 |
+
if not d.is_dir():
|
| 111 |
+
return []
|
| 112 |
+
found: set[str] = set()
|
| 113 |
+
for p in d.glob("inference_*.csv"):
|
| 114 |
+
m = _INFERENCE_CSV_RE.match(p.name)
|
| 115 |
+
if m:
|
| 116 |
+
found.add(m.group(1))
|
| 117 |
+
return sorted(found)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def collect(
|
| 121 |
+
countries: list[str], models: list[str]
|
| 122 |
+
) -> list[tuple[str, str, dict[str, dict[str, int]]]]:
|
| 123 |
+
"""Score every (country, system) pair. Returns rows of (cc, system, counters)."""
|
| 124 |
+
rows: list[tuple[str, str, dict[str, dict[str, int]]]] = []
|
| 125 |
+
for cc in countries:
|
| 126 |
+
ms = models or models_present(cc)
|
| 127 |
+
for model in ms:
|
| 128 |
+
result = score_country(cc, model, verbose=False)
|
| 129 |
+
if result is None:
|
| 130 |
+
log.info(f"[{cc}/{model}] no scoreable data, skipping")
|
| 131 |
+
continue
|
| 132 |
+
counters, _coverage = result
|
| 133 |
+
rows.append((cc, model, counters))
|
| 134 |
+
log.info(f"[{cc}/{model}] scored {len(counters)} columns")
|
| 135 |
+
return rows
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _fmt(v: float) -> str:
|
| 139 |
+
return f"{v:.4f}"
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _write_csv(path: Path, header: list[str], rows: list[dict[str, object]]) -> None:
|
| 143 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 144 |
+
with open(path, "w", encoding="utf-8", newline="") as f:
|
| 145 |
+
w = csv.DictWriter(f, fieldnames=header, extrasaction="ignore")
|
| 146 |
+
w.writeheader()
|
| 147 |
+
w.writerows(rows)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def write_per_country_per_column(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None:
|
| 151 |
+
header = ["country", "model", "column", *_BUCKETS, *DERIVED_KEYS]
|
| 152 |
+
out_rows: list[dict[str, object]] = []
|
| 153 |
+
for cc, model, counters in rows:
|
| 154 |
+
for col, c in counters.items():
|
| 155 |
+
d = derived_metrics(c)
|
| 156 |
+
out_rows.append({
|
| 157 |
+
"country": cc, "model": model, "column": col,
|
| 158 |
+
**c, **{k: _fmt(d[k]) for k in DERIVED_KEYS},
|
| 159 |
+
})
|
| 160 |
+
_write_csv(out / "per_country_per_column.csv", header, out_rows)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def write_per_country(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None:
|
| 164 |
+
"""One row per (cc, model): summed buckets across all label columns, plus
|
| 165 |
+
cost-block-only summed buckets. Also adds tradition / language tags."""
|
| 166 |
+
header = [
|
| 167 |
+
"country", "model", "legal_tradition", "language_family",
|
| 168 |
+
*_BUCKETS, *DERIVED_KEYS,
|
| 169 |
+
*(f"cost_{k}" for k in _BUCKETS),
|
| 170 |
+
*(f"cost_{k}" for k in DERIVED_KEYS),
|
| 171 |
+
]
|
| 172 |
+
out_rows: list[dict[str, object]] = []
|
| 173 |
+
for cc, model, counters in rows:
|
| 174 |
+
all_b = sum_buckets(counters)
|
| 175 |
+
cost_b = sum_buckets(counters, COST_BLOCK)
|
| 176 |
+
d_all = derived_metrics(all_b)
|
| 177 |
+
d_cost = derived_metrics(cost_b)
|
| 178 |
+
out_rows.append({
|
| 179 |
+
"country": cc, "model": model,
|
| 180 |
+
"legal_tradition": LEGAL_TRADITION.get(cc, ""),
|
| 181 |
+
"language_family": LANGUAGE_FAMILY.get(cc, ""),
|
| 182 |
+
**all_b,
|
| 183 |
+
**{k: _fmt(d_all[k]) for k in DERIVED_KEYS},
|
| 184 |
+
**{f"cost_{k}": cost_b[k] for k in _BUCKETS},
|
| 185 |
+
**{f"cost_{k}": _fmt(d_cost[k]) for k in DERIVED_KEYS},
|
| 186 |
+
})
|
| 187 |
+
_write_csv(out / "per_country.csv", header, out_rows)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def write_per_column(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None:
|
| 191 |
+
"""One row per (model, column): summed across countries."""
|
| 192 |
+
agg: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: {k: 0 for k in _BUCKETS})
|
| 193 |
+
for _cc, model, counters in rows:
|
| 194 |
+
for col, c in counters.items():
|
| 195 |
+
for k in _BUCKETS:
|
| 196 |
+
agg[(model, col)][k] += c[k]
|
| 197 |
+
header = ["model", "column", *_BUCKETS, *DERIVED_KEYS]
|
| 198 |
+
out_rows: list[dict[str, object]] = []
|
| 199 |
+
for (model, col), c in sorted(agg.items()):
|
| 200 |
+
d = derived_metrics(c)
|
| 201 |
+
out_rows.append({
|
| 202 |
+
"model": model, "column": col, **c,
|
| 203 |
+
**{k: _fmt(d[k]) for k in DERIVED_KEYS},
|
| 204 |
+
})
|
| 205 |
+
_write_csv(out / "per_column.csv", header, out_rows)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _write_grouped(
|
| 209 |
+
out: Path, name: str, group_map: dict[str, str],
|
| 210 |
+
rows: list[tuple[str, str, dict[str, dict[str, int]]]],
|
| 211 |
+
) -> None:
|
| 212 |
+
agg: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: {k: 0 for k in _BUCKETS})
|
| 213 |
+
cost_agg: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: {k: 0 for k in _BUCKETS})
|
| 214 |
+
counts: dict[tuple[str, str], int] = defaultdict(int)
|
| 215 |
+
for cc, model, counters in rows:
|
| 216 |
+
group = group_map.get(cc)
|
| 217 |
+
if group is None:
|
| 218 |
+
continue
|
| 219 |
+
key = (model, group)
|
| 220 |
+
all_b = sum_buckets(counters)
|
| 221 |
+
cost_b = sum_buckets(counters, COST_BLOCK)
|
| 222 |
+
for k in _BUCKETS:
|
| 223 |
+
agg[key][k] += all_b[k]
|
| 224 |
+
cost_agg[key][k] += cost_b[k]
|
| 225 |
+
counts[key] += 1
|
| 226 |
+
header = [
|
| 227 |
+
"model", "group", "n_countries",
|
| 228 |
+
*_BUCKETS, *DERIVED_KEYS,
|
| 229 |
+
*(f"cost_{k}" for k in _BUCKETS),
|
| 230 |
+
*(f"cost_{k}" for k in DERIVED_KEYS),
|
| 231 |
+
]
|
| 232 |
+
out_rows: list[dict[str, object]] = []
|
| 233 |
+
for (model, group), c in sorted(agg.items()):
|
| 234 |
+
cost_c = cost_agg[(model, group)]
|
| 235 |
+
d_all = derived_metrics(c)
|
| 236 |
+
d_cost = derived_metrics(cost_c)
|
| 237 |
+
out_rows.append({
|
| 238 |
+
"model": model, "group": group,
|
| 239 |
+
"n_countries": counts[(model, group)],
|
| 240 |
+
**c,
|
| 241 |
+
**{k: _fmt(d_all[k]) for k in DERIVED_KEYS},
|
| 242 |
+
**{f"cost_{k}": cost_c[k] for k in _BUCKETS},
|
| 243 |
+
**{f"cost_{k}": _fmt(d_cost[k]) for k in DERIVED_KEYS},
|
| 244 |
+
})
|
| 245 |
+
_write_csv(out / f"{name}.csv", header, out_rows)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _latex_escape(s: str) -> str:
|
| 249 |
+
return s.replace("\\", "\\textbackslash{}").replace("&", "\\&").replace("_", "\\_").replace("%", "\\%")
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _pct(v: float) -> str:
|
| 253 |
+
return f"{v * 100:5.1f}\\%"
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def write_headline_latex(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None:
|
| 257 |
+
"""One LaTeX `tabular` per model: rows = jurisdiction, cols = headline metrics."""
|
| 258 |
+
by_model: dict[str, list[tuple[str, dict[str, dict[str, int]]]]] = defaultdict(list)
|
| 259 |
+
for cc, model, counters in rows:
|
| 260 |
+
by_model[model].append((cc, counters))
|
| 261 |
+
|
| 262 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 263 |
+
lines: list[str] = []
|
| 264 |
+
for model in sorted(by_model):
|
| 265 |
+
lines.append("% Auto-generated by legex-analysis.")
|
| 266 |
+
lines.append("\\begin{table}[h]")
|
| 267 |
+
lines.append(
|
| 268 |
+
"\\caption{Headline extraction metrics by jurisdiction for model \\texttt{"
|
| 269 |
+
f"{_latex_escape(model)}"
|
| 270 |
+
"}. Recall when filled is over the cells where the expert recorded a value. "
|
| 271 |
+
"False-fill rate is the share of legitimately-empty cells where the model "
|
| 272 |
+
"invented a value.}"
|
| 273 |
+
)
|
| 274 |
+
lines.append("\\label{tab:headline-" + re.sub(r"[^a-zA-Z0-9]+", "-", model).strip("-") + "}")
|
| 275 |
+
lines.append("\\centering\\small")
|
| 276 |
+
lines.append("\\begin{tabular}{@{}lrr@{}}")
|
| 277 |
+
lines.append("\\toprule")
|
| 278 |
+
lines.append("Jurisdiction & Recall when filled & False-fill rate \\\\")
|
| 279 |
+
lines.append("\\midrule")
|
| 280 |
+
for cc, counters in sorted(by_model[model]):
|
| 281 |
+
d_all = derived_metrics(sum_buckets(counters))
|
| 282 |
+
lines.append(
|
| 283 |
+
f"{cc.upper()} & {_pct(d_all['recall_when_filled'])} "
|
| 284 |
+
f"& {_pct(d_all['hallucination_rate'])} \\\\"
|
| 285 |
+
)
|
| 286 |
+
lines.append("\\bottomrule")
|
| 287 |
+
lines.append("\\end{tabular}")
|
| 288 |
+
lines.append("\\end{table}")
|
| 289 |
+
lines.append("")
|
| 290 |
+
(out / "headline.tex").write_text("\n".join(lines), encoding="utf-8")
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def write_per_field_latex(out: Path, rows: list[tuple[str, str, dict[str, dict[str, int]]]]) -> None:
|
| 294 |
+
"""One LaTeX table per model: rows = variable, cols = headline metrics (summed across jurisdictions)."""
|
| 295 |
+
by_model_col: dict[str, dict[str, dict[str, int]]] = defaultdict(lambda: defaultdict(lambda: {k: 0 for k in _BUCKETS}))
|
| 296 |
+
for _cc, model, counters in rows:
|
| 297 |
+
for col, c in counters.items():
|
| 298 |
+
for k in _BUCKETS:
|
| 299 |
+
by_model_col[model][col][k] += c[k]
|
| 300 |
+
|
| 301 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 302 |
+
lines: list[str] = []
|
| 303 |
+
for model in sorted(by_model_col):
|
| 304 |
+
lines.append("% Auto-generated by legex-analysis.")
|
| 305 |
+
lines.append("\\begin{table}[h]")
|
| 306 |
+
lines.append(
|
| 307 |
+
"\\caption{Per-field extraction metrics, summed across jurisdictions, for model \\texttt{"
|
| 308 |
+
f"{_latex_escape(model)}"
|
| 309 |
+
"}. Recall when filled is over the cells where the expert recorded a value. False-fill "
|
| 310 |
+
"rate is the share of legitimately-empty cells where the model invented a value.}"
|
| 311 |
+
)
|
| 312 |
+
lines.append("\\label{tab:per-field-" + re.sub(r"[^a-zA-Z0-9]+", "-", model).strip("-") + "}")
|
| 313 |
+
lines.append("\\centering\\small")
|
| 314 |
+
lines.append("\\begin{tabular}{@{}lrr@{}}")
|
| 315 |
+
lines.append("\\toprule")
|
| 316 |
+
lines.append("Variable & Recall when filled & False-fill rate \\\\")
|
| 317 |
+
lines.append("\\midrule")
|
| 318 |
+
for col, c in sorted(by_model_col[model].items()):
|
| 319 |
+
d = derived_metrics(c)
|
| 320 |
+
lines.append(
|
| 321 |
+
f"\\texttt{{{_latex_escape(col)}}} "
|
| 322 |
+
f"& {_pct(d['recall_when_filled'])} & {_pct(d['hallucination_rate'])} \\\\"
|
| 323 |
+
)
|
| 324 |
+
lines.append("\\bottomrule")
|
| 325 |
+
lines.append("\\end{tabular}")
|
| 326 |
+
lines.append("\\end{table}")
|
| 327 |
+
lines.append("")
|
| 328 |
+
(out / "per_field.tex").write_text("\n".join(lines), encoding="utf-8")
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def analyse(
|
| 332 |
+
countries: list[str] | None,
|
| 333 |
+
models: list[str] | None,
|
| 334 |
+
out_dir: Path,
|
| 335 |
+
) -> None:
|
| 336 |
+
targets = countries or evaluable_countries()
|
| 337 |
+
rows = collect(targets, models or [])
|
| 338 |
+
if not rows:
|
| 339 |
+
log.warning("no (country, system) pairs produced results; nothing to write")
|
| 340 |
+
return
|
| 341 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 342 |
+
write_per_country_per_column(out_dir, rows)
|
| 343 |
+
write_per_country(out_dir, rows)
|
| 344 |
+
write_per_column(out_dir, rows)
|
| 345 |
+
_write_grouped(out_dir, "per_tradition", LEGAL_TRADITION, rows)
|
| 346 |
+
_write_grouped(out_dir, "per_language", LANGUAGE_FAMILY, rows)
|
| 347 |
+
write_headline_latex(out_dir / "tables", rows)
|
| 348 |
+
write_per_field_latex(out_dir / "tables", rows)
|
| 349 |
+
log.info(f"wrote analysis for {len(rows)} (country, system) pairs to {out_dir}")
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def main() -> None:
|
| 353 |
+
logging.basicConfig(
|
| 354 |
+
level=logging.INFO,
|
| 355 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 356 |
+
handlers=[logging.StreamHandler(sys.stderr)],
|
| 357 |
+
)
|
| 358 |
+
parser = argparse.ArgumentParser(
|
| 359 |
+
prog="legex-analysis",
|
| 360 |
+
description="Cross-jurisdiction analysis of JSONL goldensets vs system inference CSVs.",
|
| 361 |
+
)
|
| 362 |
+
parser.add_argument(
|
| 363 |
+
"--country", action="extend", nargs="+", dest="countries",
|
| 364 |
+
help=(
|
| 365 |
+
"Country code(s). Repeatable. "
|
| 366 |
+
"Default: every jurisdiction with a goldenset_<cc>.jsonl minus the "
|
| 367 |
+
"round-2 exclusion set (BE/NP/RS plus TW/BR/HK/IN)."
|
| 368 |
+
),
|
| 369 |
+
)
|
| 370 |
+
parser.add_argument(
|
| 371 |
+
"--system", "--model", action="extend", nargs="+", dest="models",
|
| 372 |
+
choices=list(SYSTEMS),
|
| 373 |
+
help=f"Inference system(s). Repeatable. Default: every system with a CSV on disk per country ({list(SYSTEMS)}).",
|
| 374 |
+
)
|
| 375 |
+
parser.add_argument(
|
| 376 |
+
"--out", type=Path, default=Path("data/analysis"),
|
| 377 |
+
help="Output directory (default: data/analysis).",
|
| 378 |
+
)
|
| 379 |
+
args = parser.parse_args()
|
| 380 |
+
analyse(
|
| 381 |
+
countries=args.countries,
|
| 382 |
+
models=args.models,
|
| 383 |
+
out_dir=args.out,
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
if __name__ == "__main__":
|
| 388 |
+
main()
|
legex/config.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Runtime configuration. Override via .env."""
|
| 2 |
+
|
| 3 |
+
from datetime import date
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Settings(BaseSettings):
|
| 10 |
+
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
| 11 |
+
|
| 12 |
+
date_start: date = date(2015, 1, 1)
|
| 13 |
+
date_end: date = date(2025, 12, 31)
|
| 14 |
+
|
| 15 |
+
sample_n: int = 130
|
| 16 |
+
sample_seed: int = 0
|
| 17 |
+
|
| 18 |
+
judilibre_client_id: str = ""
|
| 19 |
+
judilibre_client_secret: str = ""
|
| 20 |
+
hf_token: str = ""
|
| 21 |
+
|
| 22 |
+
data_dir: Path = Path("data")
|
| 23 |
+
dist_dir: Path = Path("dist")
|
| 24 |
+
|
| 25 |
+
drive_folder_url: str = ""
|
| 26 |
+
|
| 27 |
+
@property
|
| 28 |
+
def raw_dir(self) -> Path:
|
| 29 |
+
return self.data_dir / "raw"
|
| 30 |
+
|
| 31 |
+
@property
|
| 32 |
+
def processed_dir(self) -> Path:
|
| 33 |
+
return self.data_dir / "processed"
|
| 34 |
+
|
| 35 |
+
@property
|
| 36 |
+
def template(self) -> Path:
|
| 37 |
+
return self.data_dir / "Vorlage.xlsx"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
settings = Settings()
|
legex/evaluation.py
ADDED
|
@@ -0,0 +1,419 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compare Goldenset gold labels against inference output.
|
| 2 |
+
|
| 3 |
+
Reads each country's goldenset_<cc>.jsonl (the human-labelled truth, produced
|
| 4 |
+
by ``convert_goldenset_to_jsonl.py``) and the matching ``inference_<system>.csv``
|
| 5 |
+
file from one of the evaluated systems (``harvey``, ``gemini``, ``gpt``), then
|
| 6 |
+
reports per-field agreement.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import csv
|
| 11 |
+
import json
|
| 12 |
+
import logging
|
| 13 |
+
import re
|
| 14 |
+
import sys
|
| 15 |
+
from datetime import date, datetime
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import get_args
|
| 18 |
+
|
| 19 |
+
from legex.config import settings
|
| 20 |
+
from legex.models.classification import Classification
|
| 21 |
+
from legex.utils import (
|
| 22 |
+
EXCLUDED_FOR_EVAL,
|
| 23 |
+
countries_with_goldenset_jsonl,
|
| 24 |
+
evaluable_countries,
|
| 25 |
+
goldenset_jsonl_path,
|
| 26 |
+
inference_csv_path,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Systems whose inference outputs are evaluated.
|
| 30 |
+
SYSTEMS: tuple[str, ...] = ("harvey", "gemini", "gpt")
|
| 31 |
+
|
| 32 |
+
log = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
# Columns that don't carry a label to evaluate against (matched case-insensitively).
|
| 35 |
+
_NON_LABEL_COLUMNS = {"case_id", "link", "full_text"}
|
| 36 |
+
|
| 37 |
+
# Goldenset / inference sentinels for “no value” (non_empty as empty).
|
| 38 |
+
_EMPTY_LITERALS = frozenset({"", "none", "null", "nan"})
|
| 39 |
+
|
| 40 |
+
# CSV columns whose Classification field is numeric (int / float). Loose
|
| 41 |
+
# parsing (apostrophe thousand separators, leading number + trailing prose)
|
| 42 |
+
# applies only to these.
|
| 43 |
+
_NUMERIC_COLUMNS = frozenset(
|
| 44 |
+
(info.alias or name)
|
| 45 |
+
for name, info in Classification.model_fields.items()
|
| 46 |
+
if any(a is int or a is float for a in (get_args(info.annotation) or (info.annotation,)))
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
_NUM_TOKEN_RE = re.compile(r"-?\d[\d',. ]*")
|
| 50 |
+
|
| 51 |
+
# CSV columns whose Classification field is a date. Separator normalisation
|
| 52 |
+
# (treat `_`, `/`, `.` as `-`) plus a small format fallback applies only here.
|
| 53 |
+
_DATE_COLUMNS = frozenset(
|
| 54 |
+
(info.alias or name)
|
| 55 |
+
for name, info in Classification.model_fields.items()
|
| 56 |
+
if any(a is date for a in (get_args(info.annotation) or (info.annotation,)))
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
_DATE_SEP_RE = re.compile(r"[_/.\s]+")
|
| 60 |
+
_DATE_FALLBACK_FORMATS = ("%d-%m-%Y", "%m-%d-%Y", "%Y%m%d")
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _is_label_column(name: str) -> bool:
|
| 64 |
+
if not name or name.lower() in _NON_LABEL_COLUMNS:
|
| 65 |
+
return False
|
| 66 |
+
if name.startswith("Currency_"):
|
| 67 |
+
return False
|
| 68 |
+
return True
|
| 69 |
+
|
| 70 |
+
def _normalise(value: object) -> str:
|
| 71 |
+
"""Make gold and prediction cells comparable as strings."""
|
| 72 |
+
if value is None:
|
| 73 |
+
return ""
|
| 74 |
+
if isinstance(value, float):
|
| 75 |
+
if value != value: # NaN
|
| 76 |
+
return ""
|
| 77 |
+
if value.is_integer():
|
| 78 |
+
return str(int(value))
|
| 79 |
+
s = str(value).strip()
|
| 80 |
+
if s.lower() in _EMPTY_LITERALS:
|
| 81 |
+
return ""
|
| 82 |
+
return s
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _try_float(s: str) -> float | None:
|
| 86 |
+
if not s:
|
| 87 |
+
return None
|
| 88 |
+
try:
|
| 89 |
+
return float(s)
|
| 90 |
+
except ValueError:
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _parse_loose_number(s: str) -> float | None:
|
| 95 |
+
"""Extract the first numeric token from `s`, tolerating apostrophe/space
|
| 96 |
+
thousand separators (`20'000`, `20 000`), EU decimal commas (`1.000,50`),
|
| 97 |
+
and trailing prose (`150 GEL state fee awarded …`, `0%, motion satisfied`).
|
| 98 |
+
Returns None when no digit appears.
|
| 99 |
+
"""
|
| 100 |
+
if not s:
|
| 101 |
+
return None
|
| 102 |
+
m = _NUM_TOKEN_RE.search(s)
|
| 103 |
+
if not m:
|
| 104 |
+
return None
|
| 105 |
+
tok = m.group(0).strip().rstrip(",.' ")
|
| 106 |
+
if not tok:
|
| 107 |
+
return None
|
| 108 |
+
cleaned = tok.replace("'", "").replace(" ", "")
|
| 109 |
+
if "," in cleaned and "." in cleaned:
|
| 110 |
+
# Whichever appears last is the decimal mark.
|
| 111 |
+
if cleaned.rfind(",") > cleaned.rfind("."):
|
| 112 |
+
cleaned = cleaned.replace(".", "").replace(",", ".")
|
| 113 |
+
else:
|
| 114 |
+
cleaned = cleaned.replace(",", "")
|
| 115 |
+
elif "," in cleaned:
|
| 116 |
+
parts = cleaned.split(",")
|
| 117 |
+
# Single trailing group of 1-2 digits → decimal comma; else thousands.
|
| 118 |
+
if len(parts) == 2 and 1 <= len(parts[1]) <= 2:
|
| 119 |
+
cleaned = parts[0] + "." + parts[1]
|
| 120 |
+
else:
|
| 121 |
+
cleaned = cleaned.replace(",", "")
|
| 122 |
+
try:
|
| 123 |
+
return float(cleaned)
|
| 124 |
+
except ValueError:
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _numeric_value(s: str, column: str | None) -> float | None:
|
| 129 |
+
"""Strict float for any column, plus loose parse for numeric columns."""
|
| 130 |
+
n = _try_float(s)
|
| 131 |
+
if n is not None:
|
| 132 |
+
return n
|
| 133 |
+
if column in _NUMERIC_COLUMNS:
|
| 134 |
+
return _parse_loose_number(s)
|
| 135 |
+
return None
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _parse_loose_date(s: str) -> date | None:
|
| 139 |
+
"""Parse a date string, treating `_`, `/`, `.`, whitespace as `-`.
|
| 140 |
+
|
| 141 |
+
Accepts ISO `YYYY-MM-DD` (after separator collapse), and as a fallback
|
| 142 |
+
`DD-MM-YYYY`, `MM-DD-YYYY`, `YYYYMMDD`.
|
| 143 |
+
"""
|
| 144 |
+
if not s:
|
| 145 |
+
return None
|
| 146 |
+
t = _DATE_SEP_RE.sub("-", s.strip()).strip("-")
|
| 147 |
+
if not t:
|
| 148 |
+
return None
|
| 149 |
+
try:
|
| 150 |
+
return date.fromisoformat(t)
|
| 151 |
+
except ValueError:
|
| 152 |
+
pass
|
| 153 |
+
for fmt in _DATE_FALLBACK_FORMATS:
|
| 154 |
+
try:
|
| 155 |
+
return datetime.strptime(t, fmt).date()
|
| 156 |
+
except ValueError:
|
| 157 |
+
continue
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _values_agree(gv: str, pv: str, column: str | None = None) -> bool:
|
| 162 |
+
"""Compare normalised gold vs prediction cell values."""
|
| 163 |
+
if gv == pv:
|
| 164 |
+
return True
|
| 165 |
+
if column in _DATE_COLUMNS:
|
| 166 |
+
gd, pd_ = _parse_loose_date(gv), _parse_loose_date(pv)
|
| 167 |
+
if gd is not None and pd_ is not None and gd == pd_:
|
| 168 |
+
return True
|
| 169 |
+
gn = _numeric_value(gv, column)
|
| 170 |
+
if gn is not None and gn == 0:
|
| 171 |
+
# Gold is zero: empty pred or any zero form (0, 0.0, …) counts as match.
|
| 172 |
+
if not pv:
|
| 173 |
+
return True
|
| 174 |
+
pn = _numeric_value(pv, column)
|
| 175 |
+
return pn is not None and pn == 0
|
| 176 |
+
if gn is not None:
|
| 177 |
+
pn = _numeric_value(pv, column)
|
| 178 |
+
if pn is not None:
|
| 179 |
+
return gn == pn
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
_BUCKETS = ("tp", "mismatch", "missed", "hallucinated", "tn")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _classify_cell(gv: str, pv: str, column: str | None) -> str:
|
| 187 |
+
"""Bucket a (gold, pred) cell. `gv`/`pv` must already be `_normalise()`-d.
|
| 188 |
+
|
| 189 |
+
tp - gold filled, values agree
|
| 190 |
+
mismatch - gold filled, pred filled, values differ (FP_wrong)
|
| 191 |
+
missed - gold filled, pred empty (FN)
|
| 192 |
+
hallucinated - gold empty, pred filled (FP on a not-filled gold field)
|
| 193 |
+
tn - both empty
|
| 194 |
+
"""
|
| 195 |
+
gold_filled = bool(gv)
|
| 196 |
+
pred_filled = bool(pv)
|
| 197 |
+
if _values_agree(gv, pv, column):
|
| 198 |
+
return "tp" if gold_filled else "tn"
|
| 199 |
+
if gold_filled and pred_filled:
|
| 200 |
+
return "mismatch"
|
| 201 |
+
if gold_filled:
|
| 202 |
+
return "missed"
|
| 203 |
+
return "hallucinated"
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _derived(c: dict[str, int]) -> tuple[float, float, float]:
|
| 207 |
+
"""Per-column precision, recall, F1 from a bucket counter."""
|
| 208 |
+
tp, mism, miss, hallu = c["tp"], c["mismatch"], c["missed"], c["hallucinated"]
|
| 209 |
+
p_denom = tp + mism + hallu
|
| 210 |
+
r_denom = tp + mism + miss
|
| 211 |
+
p = tp / p_denom if p_denom else 0.0
|
| 212 |
+
r = tp / r_denom if r_denom else 0.0
|
| 213 |
+
f1 = 2 * p * r / (p + r) if (p + r) else 0.0
|
| 214 |
+
return p, r, f1
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def _read_goldenset_rows(cc: str) -> tuple[list[str], dict[str, dict[str, str]]]:
|
| 218 |
+
"""Return (label_columns, rows_by_case_id) for a country's JSONL goldenset."""
|
| 219 |
+
path = goldenset_jsonl_path(cc)
|
| 220 |
+
if not path.exists():
|
| 221 |
+
raise FileNotFoundError(f"{path} does not exist")
|
| 222 |
+
|
| 223 |
+
label_columns: list[str] | None = None
|
| 224 |
+
by_id: dict[str, dict[str, str]] = {}
|
| 225 |
+
with path.open(encoding="utf-8") as f:
|
| 226 |
+
for line in f:
|
| 227 |
+
if not line.strip():
|
| 228 |
+
continue
|
| 229 |
+
record = json.loads(line)
|
| 230 |
+
if label_columns is None:
|
| 231 |
+
label_columns = [k for k in record.keys() if _is_label_column(k)]
|
| 232 |
+
case_id = _normalise(record.get("case_id"))
|
| 233 |
+
if not case_id:
|
| 234 |
+
continue
|
| 235 |
+
labels = {col: _normalise(record.get(col)) for col in label_columns}
|
| 236 |
+
if not any(labels.values()):
|
| 237 |
+
continue
|
| 238 |
+
by_id[case_id] = labels
|
| 239 |
+
return label_columns or [], by_id
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def _read_predictions(cc: str, system: str) -> dict[str, dict[str, str]]:
|
| 243 |
+
path = inference_csv_path(cc, system)
|
| 244 |
+
by_id: dict[str, dict[str, str]] = {}
|
| 245 |
+
with open(path, encoding="utf-8", newline="") as f:
|
| 246 |
+
reader = csv.DictReader(f)
|
| 247 |
+
for row in reader:
|
| 248 |
+
case_id = _normalise(row.get("case_id"))
|
| 249 |
+
if not case_id:
|
| 250 |
+
continue
|
| 251 |
+
by_id[case_id] = {k: _normalise(v) for k, v in row.items()}
|
| 252 |
+
return by_id
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def _coverage(
|
| 256 |
+
gold: dict[str, dict[str, str]], preds: dict[str, dict[str, str]]
|
| 257 |
+
) -> dict[str, int]:
|
| 258 |
+
gold_ids = set(gold)
|
| 259 |
+
pred_ids = set(preds)
|
| 260 |
+
overlap = len(gold_ids & pred_ids)
|
| 261 |
+
return {
|
| 262 |
+
"gold": len(gold_ids),
|
| 263 |
+
"pred": len(pred_ids),
|
| 264 |
+
"overlap": overlap,
|
| 265 |
+
"missing": len(gold_ids - pred_ids),
|
| 266 |
+
"extra": len(pred_ids - gold_ids),
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def score_country(
|
| 271 |
+
cc: str, system: str, verbose: bool = True
|
| 272 |
+
) -> tuple[dict[str, dict[str, int]], dict[str, int]] | None:
|
| 273 |
+
"""Return (per-column counters, case coverage stats) for one (country, system)."""
|
| 274 |
+
pred_path = inference_csv_path(cc, system)
|
| 275 |
+
gs_path = goldenset_jsonl_path(cc)
|
| 276 |
+
if not pred_path.exists():
|
| 277 |
+
if verbose:
|
| 278 |
+
log.warning(f"[{cc}/{system}] missing predictions {pred_path}, skipping")
|
| 279 |
+
return None
|
| 280 |
+
if not gs_path.exists():
|
| 281 |
+
if verbose:
|
| 282 |
+
log.warning(f"[{cc}] missing goldenset {gs_path}, skipping")
|
| 283 |
+
return None
|
| 284 |
+
|
| 285 |
+
label_columns, gold = _read_goldenset_rows(cc)
|
| 286 |
+
preds = _read_predictions(cc, system)
|
| 287 |
+
stats = _coverage(gold, preds)
|
| 288 |
+
|
| 289 |
+
counters: dict[str, dict[str, int]] = {
|
| 290 |
+
col: {b: 0 for b in _BUCKETS} for col in label_columns
|
| 291 |
+
}
|
| 292 |
+
overlap_ids = [cid for cid in gold if cid in preds]
|
| 293 |
+
if verbose:
|
| 294 |
+
print()
|
| 295 |
+
log.info(
|
| 296 |
+
f"[{cc}/{system}] gold={stats['gold']} pred={stats['pred']} "
|
| 297 |
+
f"overlap={stats['overlap']} missing={stats['missing']} extra={stats['extra']}"
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
for case_id in overlap_ids:
|
| 301 |
+
g = gold[case_id]
|
| 302 |
+
p = preds[case_id]
|
| 303 |
+
for col in label_columns:
|
| 304 |
+
bucket = _classify_cell(g.get(col, ""), p.get(col, ""), col)
|
| 305 |
+
counters[col][bucket] += 1
|
| 306 |
+
return counters, stats
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def _print_report(
|
| 310 |
+
cc: str, counters: dict[str, dict[str, int]], coverage: dict[str, int] | None = None
|
| 311 |
+
) -> None:
|
| 312 |
+
name_width = max((len(c) for c in counters), default=0)
|
| 313 |
+
name_width = max(name_width, len("column"))
|
| 314 |
+
print(f"=== {cc} ===")
|
| 315 |
+
if coverage is not None:
|
| 316 |
+
print(
|
| 317 |
+
f"cases: gold={coverage['gold']} pred={coverage['pred']} "
|
| 318 |
+
f"overlap={coverage['overlap']} missing={coverage['missing']} "
|
| 319 |
+
f"extra={coverage['extra']}"
|
| 320 |
+
)
|
| 321 |
+
print(
|
| 322 |
+
f"{'column'.ljust(name_width)} "
|
| 323 |
+
f"{'TP':>5} {'Mism':>5} {'Miss':>5} {'Hallu':>5} {'TN':>5} "
|
| 324 |
+
f"{'P':>7} {'R':>7} {'F1':>5}"
|
| 325 |
+
)
|
| 326 |
+
for col, c in counters.items():
|
| 327 |
+
p, r, f1 = _derived(c)
|
| 328 |
+
f1_s = f"{f1:.2f}" if (p + r) else " - "
|
| 329 |
+
print(
|
| 330 |
+
f"{col.ljust(name_width)} "
|
| 331 |
+
f"{c['tp']:>5} {c['mismatch']:>5} {c['missed']:>5} "
|
| 332 |
+
f"{c['hallucinated']:>5} {c['tn']:>5} "
|
| 333 |
+
f"{p:>7.2%} {r:>7.2%} {f1_s:>5}"
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def _schema_label_columns() -> list[str]:
|
| 338 |
+
"""The 14 label columns derived from the Classification pydantic model."""
|
| 339 |
+
return [
|
| 340 |
+
(info.alias or name)
|
| 341 |
+
for name, info in Classification.model_fields.items()
|
| 342 |
+
if _is_label_column(info.alias or name)
|
| 343 |
+
]
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def evaluate(
|
| 347 |
+
countries: list[str] | None,
|
| 348 |
+
systems: list[str] | None,
|
| 349 |
+
) -> None:
|
| 350 |
+
overall: dict[str, dict[str, int]] = {
|
| 351 |
+
col: {b: 0 for b in _BUCKETS} for col in _schema_label_columns()
|
| 352 |
+
}
|
| 353 |
+
overall_coverage = {"gold": 0, "pred": 0, "overlap": 0, "missing": 0, "extra": 0}
|
| 354 |
+
|
| 355 |
+
targets = countries or evaluable_countries()
|
| 356 |
+
chosen_systems = systems or list(SYSTEMS)
|
| 357 |
+
|
| 358 |
+
seen_any = False
|
| 359 |
+
for system in chosen_systems:
|
| 360 |
+
print(f"\n########## SYSTEM: {system} ##########")
|
| 361 |
+
for cc in targets:
|
| 362 |
+
result = score_country(cc, system)
|
| 363 |
+
if result is None:
|
| 364 |
+
continue
|
| 365 |
+
counters, coverage = result
|
| 366 |
+
seen_any = True
|
| 367 |
+
_print_report(f"{cc} / {system}", counters, coverage)
|
| 368 |
+
for key in overall_coverage:
|
| 369 |
+
overall_coverage[key] += coverage[key]
|
| 370 |
+
for col, c in counters.items():
|
| 371 |
+
if col not in overall:
|
| 372 |
+
overall[col] = {b: 0 for b in _BUCKETS}
|
| 373 |
+
for b in _BUCKETS:
|
| 374 |
+
overall[col][b] += c[b]
|
| 375 |
+
|
| 376 |
+
if seen_any:
|
| 377 |
+
_print_report("ALL", overall, overall_coverage)
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def main() -> None:
|
| 381 |
+
logging.basicConfig(
|
| 382 |
+
level=logging.INFO,
|
| 383 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 384 |
+
handlers=[logging.StreamHandler(sys.stderr)],
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
parser = argparse.ArgumentParser(
|
| 388 |
+
prog="legex-evaluate",
|
| 389 |
+
description="Compare Goldenset JSONL labels against system inference CSV outputs.",
|
| 390 |
+
)
|
| 391 |
+
parser.add_argument(
|
| 392 |
+
"--country",
|
| 393 |
+
action="extend",
|
| 394 |
+
nargs="+",
|
| 395 |
+
dest="countries",
|
| 396 |
+
help=(
|
| 397 |
+
"Country code(s). Repeatable and/or space-separated. "
|
| 398 |
+
f"Defaults to the {len(SYSTEMS)}-system evaluation set "
|
| 399 |
+
"(all jurisdictions with a goldenset JSONL minus "
|
| 400 |
+
f"{sorted(EXCLUDED_FOR_EVAL)})."
|
| 401 |
+
),
|
| 402 |
+
)
|
| 403 |
+
parser.add_argument(
|
| 404 |
+
"--system",
|
| 405 |
+
action="extend",
|
| 406 |
+
nargs="+",
|
| 407 |
+
dest="systems",
|
| 408 |
+
choices=list(SYSTEMS),
|
| 409 |
+
help=f"Inference system(s). Repeatable. Default: all of {list(SYSTEMS)}.",
|
| 410 |
+
)
|
| 411 |
+
args = parser.parse_args()
|
| 412 |
+
evaluate(
|
| 413 |
+
countries=args.countries,
|
| 414 |
+
systems=args.systems,
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
if __name__ == "__main__":
|
| 419 |
+
main()
|
legex/extract_raw_text.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Extract full text from goldenset PDFs in data/raw/drive-download-*/<Country>/.
|
| 2 |
+
|
| 3 |
+
Writes data/<cc>/full_text.jsonl with fields: case_id, full_text.
|
| 4 |
+
Text is whitespace-normalized (no newlines, runs of whitespace collapsed to one space).
|
| 5 |
+
|
| 6 |
+
Usage:
|
| 7 |
+
uv run python -m legex.extract_raw_text
|
| 8 |
+
uv run python -m legex.extract_raw_text --country kr
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import logging
|
| 16 |
+
import re
|
| 17 |
+
import sys
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
from pypdf import PdfReader
|
| 21 |
+
|
| 22 |
+
log = logging.getLogger("legex.extract_raw_text")
|
| 23 |
+
|
| 24 |
+
REPO_ROOT = Path(__file__).resolve().parent.parent
|
| 25 |
+
RAW_DIR = REPO_ROOT / "data" / "raw"
|
| 26 |
+
DATA_DIR = REPO_ROOT / "data"
|
| 27 |
+
|
| 28 |
+
FOLDER_TO_CC: dict[str, str] = {
|
| 29 |
+
"Armenia": "am",
|
| 30 |
+
"Belgium": "be",
|
| 31 |
+
"China": "cn",
|
| 32 |
+
"Dominican_Republic": "do",
|
| 33 |
+
"Georgia": "ge",
|
| 34 |
+
"Hong_Kong": "hk",
|
| 35 |
+
"India": "in",
|
| 36 |
+
"Nepal": "np",
|
| 37 |
+
"New_Zealand": "nz",
|
| 38 |
+
"Philippines": "ph",
|
| 39 |
+
"Russia": "ru",
|
| 40 |
+
"Singapore": "sg",
|
| 41 |
+
"South_Korea fixed": "kr",
|
| 42 |
+
"South_Korea": "kr",
|
| 43 |
+
"Spain": "es",
|
| 44 |
+
"Taiwan": "tw",
|
| 45 |
+
"Ukraine": "ua",
|
| 46 |
+
"United_States": "us",
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
_WS_RE = re.compile(r"\s+")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def normalize_ws(text: str) -> str:
|
| 54 |
+
return _WS_RE.sub(" ", text).strip()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def extract_pdf_text(pdf: Path) -> str:
|
| 58 |
+
try:
|
| 59 |
+
reader = PdfReader(str(pdf))
|
| 60 |
+
text = " ".join((page.extract_text() or "") for page in reader.pages)
|
| 61 |
+
except Exception as e:
|
| 62 |
+
log.warning(f"failed to read {pdf}: {type(e).__name__}: {e}")
|
| 63 |
+
return ""
|
| 64 |
+
return normalize_ws(text)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def find_country_folders() -> dict[str, list[Path]]:
|
| 68 |
+
"""Map country code -> list of PDFs found across all drive-download-* folders."""
|
| 69 |
+
by_cc: dict[str, list[Path]] = {}
|
| 70 |
+
unknown: list[str] = []
|
| 71 |
+
for drive_dir in sorted(RAW_DIR.glob("drive-download-*")):
|
| 72 |
+
if not drive_dir.is_dir():
|
| 73 |
+
continue
|
| 74 |
+
for sub in sorted(drive_dir.iterdir()):
|
| 75 |
+
if not sub.is_dir():
|
| 76 |
+
continue
|
| 77 |
+
cc = FOLDER_TO_CC.get(sub.name)
|
| 78 |
+
if cc is None:
|
| 79 |
+
unknown.append(str(sub))
|
| 80 |
+
continue
|
| 81 |
+
pdfs = sorted(sub.glob("*.pdf"))
|
| 82 |
+
by_cc.setdefault(cc, []).extend(pdfs)
|
| 83 |
+
if unknown:
|
| 84 |
+
log.warning("unmapped folders (skipped): %s", ", ".join(unknown))
|
| 85 |
+
return by_cc
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def write_jsonl(cc: str, pdfs: list[Path]) -> Path:
|
| 89 |
+
out_dir = DATA_DIR / cc
|
| 90 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 91 |
+
out_path = out_dir / "full_text.jsonl"
|
| 92 |
+
with out_path.open("w", encoding="utf-8") as f:
|
| 93 |
+
for pdf in pdfs:
|
| 94 |
+
text = extract_pdf_text(pdf)
|
| 95 |
+
f.write(json.dumps({"case_id": pdf.stem, "full_text": text}, ensure_ascii=False))
|
| 96 |
+
f.write("\n")
|
| 97 |
+
return out_path
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def main() -> int:
|
| 101 |
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
| 102 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 103 |
+
ap.add_argument(
|
| 104 |
+
"--country",
|
| 105 |
+
"-c",
|
| 106 |
+
action="append",
|
| 107 |
+
help="Only process the given country code (repeatable). Default: all.",
|
| 108 |
+
)
|
| 109 |
+
args = ap.parse_args()
|
| 110 |
+
|
| 111 |
+
if not RAW_DIR.exists():
|
| 112 |
+
log.error("raw dir not found: %s", RAW_DIR)
|
| 113 |
+
return 1
|
| 114 |
+
|
| 115 |
+
by_cc = find_country_folders()
|
| 116 |
+
if args.country:
|
| 117 |
+
wanted = {c.lower() for c in args.country}
|
| 118 |
+
by_cc = {cc: pdfs for cc, pdfs in by_cc.items() if cc in wanted}
|
| 119 |
+
missing = wanted - set(by_cc)
|
| 120 |
+
if missing:
|
| 121 |
+
log.error("no PDFs found for: %s", ", ".join(sorted(missing)))
|
| 122 |
+
return 1
|
| 123 |
+
|
| 124 |
+
if not by_cc:
|
| 125 |
+
log.error("no country folders matched")
|
| 126 |
+
return 1
|
| 127 |
+
|
| 128 |
+
for cc in sorted(by_cc):
|
| 129 |
+
pdfs = by_cc[cc]
|
| 130 |
+
log.info("[%s] extracting %d PDFs", cc, len(pdfs))
|
| 131 |
+
out = write_jsonl(cc, pdfs)
|
| 132 |
+
log.info("[%s] wrote %s", cc, out)
|
| 133 |
+
return 0
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if __name__ == "__main__":
|
| 137 |
+
sys.exit(main())
|
legex/harvey.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ingest Harvey-AI extractions from a single xlsx into per-country CSVs.
|
| 2 |
+
|
| 3 |
+
`data/raw/harvey.xlsx` (Sheet1) holds Harvey's outputs for 23 jurisdictions
|
| 4 |
+
with 4 columns per question (Value / Reasoning / Citations / Comments). We
|
| 5 |
+
keep only the Value columns, clean them, match each row to a Goldenset
|
| 6 |
+
case_id via the PDF filename, and write a CSV that looks exactly like the
|
| 7 |
+
output of `legex.inference` — so `legex-evaluate`, `legex-analysis`, and
|
| 8 |
+
`legex-plots` treat Harvey as just another model.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import csv
|
| 13 |
+
import logging
|
| 14 |
+
import re
|
| 15 |
+
import sys
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
from openpyxl import load_workbook
|
| 20 |
+
|
| 21 |
+
from legex.config import settings
|
| 22 |
+
from legex.inference import _output_columns
|
| 23 |
+
from legex.utils import (
|
| 24 |
+
classified_csv_path,
|
| 25 |
+
goldenset_path,
|
| 26 |
+
goldenset_sheet,
|
| 27 |
+
norm_case_id,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
log = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
HARVEY_FOLDER_TO_CC: dict[str, str] = {
|
| 34 |
+
"Armenia": "am",
|
| 35 |
+
"Australia": "au",
|
| 36 |
+
"Belgium": "be",
|
| 37 |
+
"Brazil": "br",
|
| 38 |
+
"China": "cn",
|
| 39 |
+
"Dominican_Republic": "do",
|
| 40 |
+
"France": "fr",
|
| 41 |
+
"Georgia": "ge",
|
| 42 |
+
"Germany": "de",
|
| 43 |
+
"Hong_Kong": "hk",
|
| 44 |
+
"India": "in",
|
| 45 |
+
"Nepal": "np",
|
| 46 |
+
"New_Zealand": "nz",
|
| 47 |
+
"Philippines": "ph",
|
| 48 |
+
"Russia": "ru",
|
| 49 |
+
"Schweiz_final": "ch",
|
| 50 |
+
"Singapore": "sg",
|
| 51 |
+
"South_Korea fixed": "kr",
|
| 52 |
+
"Spain": "es",
|
| 53 |
+
"Taiwan": "tw",
|
| 54 |
+
"Ukraine": "ua",
|
| 55 |
+
"United_Kingdom": "uk",
|
| 56 |
+
"United_States": "us",
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Harvey Sheet1 value-column index → Goldenset header name.
|
| 61 |
+
HARVEY_COL_TO_GOLD: dict[int, str] = {
|
| 62 |
+
7: "legal_subject_judgement",
|
| 63 |
+
11: "trial_start_date",
|
| 64 |
+
15: "trial_end_date",
|
| 65 |
+
19: "dispute_value_nominal",
|
| 66 |
+
23: "plaintiff_loosing_share",
|
| 67 |
+
27: "court_cost_awarded_nominal",
|
| 68 |
+
31: "party_compensation_awarded_nominal",
|
| 69 |
+
35: "plaintiffs_all_count",
|
| 70 |
+
39: "defendants_all_count",
|
| 71 |
+
43: "plaintiff_no1_ISIC1_industry_category",
|
| 72 |
+
47: "defendant_no1_ISIC1_industry_category",
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
_CITATION_RE = re.compile(r"\s*(?:\[\d+\])+\s*$")
|
| 76 |
+
_EMPTY_LITERALS = {"", "—"}
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _clean(value: object) -> str:
|
| 80 |
+
if value is None:
|
| 81 |
+
return ""
|
| 82 |
+
s = str(value).strip()
|
| 83 |
+
if s in _EMPTY_LITERALS:
|
| 84 |
+
return ""
|
| 85 |
+
s = _CITATION_RE.sub("", s).strip()
|
| 86 |
+
if s.lower() == "nonpecuniary":
|
| 87 |
+
return "nonpecuniary"
|
| 88 |
+
return s
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _gold_case_id_index(cc: str) -> dict[str, str] | None:
|
| 92 |
+
"""{ norm_case_id(gold) → gold case_id } for one country, or None if no Goldenset."""
|
| 93 |
+
gs = goldenset_path(cc)
|
| 94 |
+
if not gs.exists():
|
| 95 |
+
return None
|
| 96 |
+
wb = load_workbook(gs, read_only=True, data_only=True)
|
| 97 |
+
ws = goldenset_sheet(wb)
|
| 98 |
+
rows = ws.iter_rows(values_only=True)
|
| 99 |
+
header = [str(c) if c is not None else "" for c in next(rows)]
|
| 100 |
+
try:
|
| 101 |
+
cid_idx = header.index("case_id")
|
| 102 |
+
except ValueError as e:
|
| 103 |
+
raise ValueError(f"{gs}: GOLDENSET sheet has no case_id column") from e
|
| 104 |
+
index: dict[str, str] = {}
|
| 105 |
+
for row in rows:
|
| 106 |
+
if not any(row):
|
| 107 |
+
continue
|
| 108 |
+
raw = row[cid_idx]
|
| 109 |
+
if raw is None:
|
| 110 |
+
continue
|
| 111 |
+
gold = str(raw).strip()
|
| 112 |
+
if not gold:
|
| 113 |
+
continue
|
| 114 |
+
index.setdefault(norm_case_id(gold), gold)
|
| 115 |
+
return index
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def ingest(
|
| 119 |
+
xlsx: Path,
|
| 120 |
+
prompt_version: str = "v3",
|
| 121 |
+
source: str = "full_text",
|
| 122 |
+
model: str = "harvey",
|
| 123 |
+
) -> None:
|
| 124 |
+
columns = _output_columns()
|
| 125 |
+
wb = load_workbook(xlsx, read_only=True, data_only=True)
|
| 126 |
+
if "Sheet1" not in wb.sheetnames:
|
| 127 |
+
raise ValueError(f"{xlsx} missing Sheet1 (found {wb.sheetnames})")
|
| 128 |
+
ws = wb["Sheet1"]
|
| 129 |
+
rows_iter = ws.iter_rows(values_only=True)
|
| 130 |
+
next(rows_iter) # skip header
|
| 131 |
+
|
| 132 |
+
by_folder: dict[str, list[tuple]] = defaultdict(list)
|
| 133 |
+
for row in rows_iter:
|
| 134 |
+
if not row or row[0] is None:
|
| 135 |
+
continue
|
| 136 |
+
folder = row[1]
|
| 137 |
+
if folder is None:
|
| 138 |
+
continue
|
| 139 |
+
by_folder[str(folder)].append(row)
|
| 140 |
+
|
| 141 |
+
for folder, rows in by_folder.items():
|
| 142 |
+
cc = HARVEY_FOLDER_TO_CC.get(folder)
|
| 143 |
+
if cc is None:
|
| 144 |
+
log.warning(f"unknown folder {folder!r}, skipping {len(rows)} row(s)")
|
| 145 |
+
continue
|
| 146 |
+
index = _gold_case_id_index(cc)
|
| 147 |
+
if index is None:
|
| 148 |
+
log.info(f"[{cc}] no Goldenset on disk, skipping {len(rows)} Harvey row(s)")
|
| 149 |
+
continue
|
| 150 |
+
|
| 151 |
+
out = classified_csv_path(cc, prompt_version, source, model)
|
| 152 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 153 |
+
|
| 154 |
+
matched = 0
|
| 155 |
+
unmatched = 0
|
| 156 |
+
with open(out, "w", encoding="utf-8", newline="") as f:
|
| 157 |
+
writer = csv.DictWriter(f, fieldnames=columns, extrasaction="ignore")
|
| 158 |
+
writer.writeheader()
|
| 159 |
+
for row in rows:
|
| 160 |
+
stem = Path(str(row[0])).stem
|
| 161 |
+
gold = index.get(norm_case_id(stem))
|
| 162 |
+
if gold is None:
|
| 163 |
+
unmatched += 1
|
| 164 |
+
log.info(f"[{cc}] no Goldenset match for {row[0]!r}")
|
| 165 |
+
continue
|
| 166 |
+
out_row = {col: "" for col in columns}
|
| 167 |
+
out_row["case_id"] = gold
|
| 168 |
+
out_row["model"] = model
|
| 169 |
+
for harvey_idx, gold_col in HARVEY_COL_TO_GOLD.items():
|
| 170 |
+
if harvey_idx < len(row):
|
| 171 |
+
out_row[gold_col] = _clean(row[harvey_idx])
|
| 172 |
+
writer.writerow(out_row)
|
| 173 |
+
matched += 1
|
| 174 |
+
log.info(
|
| 175 |
+
f"[{cc}] wrote {matched} Harvey row(s) → {out} "
|
| 176 |
+
f"({unmatched} unmatched, {len(rows)} total)"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def main() -> None:
|
| 181 |
+
logging.basicConfig(
|
| 182 |
+
level=logging.INFO,
|
| 183 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 184 |
+
handlers=[logging.StreamHandler(sys.stderr)],
|
| 185 |
+
)
|
| 186 |
+
parser = argparse.ArgumentParser(
|
| 187 |
+
prog="legex-harvey-ingest",
|
| 188 |
+
description="Convert data/raw/harvey.xlsx into per-country Goldenset_*_harvey.csv files.",
|
| 189 |
+
)
|
| 190 |
+
parser.add_argument(
|
| 191 |
+
"--xlsx",
|
| 192 |
+
type=Path,
|
| 193 |
+
default=settings.raw_dir / "harvey.xlsx",
|
| 194 |
+
help="Path to harvey.xlsx (default: data/raw/harvey.xlsx).",
|
| 195 |
+
)
|
| 196 |
+
parser.add_argument("--prompt_version", default="v3")
|
| 197 |
+
parser.add_argument(
|
| 198 |
+
"--source",
|
| 199 |
+
choices=("full_text", "pdf"),
|
| 200 |
+
default="full_text",
|
| 201 |
+
help="Source bucket label used in the CSV filename (default: full_text).",
|
| 202 |
+
)
|
| 203 |
+
parser.add_argument("--model", default="harvey", help="Model slug for the CSV filename.")
|
| 204 |
+
args = parser.parse_args()
|
| 205 |
+
ingest(
|
| 206 |
+
xlsx=args.xlsx,
|
| 207 |
+
prompt_version=args.prompt_version,
|
| 208 |
+
source=args.source,
|
| 209 |
+
model=args.model,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
if __name__ == "__main__":
|
| 214 |
+
main()
|
legex/inference.py
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LLM inference over Goldenset full_text or per-country PDFs.
|
| 2 |
+
|
| 3 |
+
For each registered country, reads case inputs from either:
|
| 4 |
+
- the `full_text` column of `data/<cc>/Goldenset_*.xlsx`, or
|
| 5 |
+
- the PDFs at `data/<cc>/*.pdf`
|
| 6 |
+
|
| 7 |
+
runs an LLM with the Vorlage coding rules, and appends a CSV of predictions
|
| 8 |
+
to `data/<cc>/Goldenset_{country}_{prompt_version}_{full_text|pdf}_{model}.csv`.
|
| 9 |
+
Successful rows (by case_id) are skipped; rows with a non-empty `error`
|
| 10 |
+
column are retried on the next run.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import asyncio
|
| 15 |
+
import csv
|
| 16 |
+
import json
|
| 17 |
+
import logging
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import threading
|
| 21 |
+
import time
|
| 22 |
+
from collections.abc import Callable
|
| 23 |
+
from datetime import date
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
from dotenv import load_dotenv
|
| 27 |
+
from openpyxl import load_workbook
|
| 28 |
+
|
| 29 |
+
from legex.config import settings
|
| 30 |
+
from legex.models.base import Case
|
| 31 |
+
from legex.models.classification import Classification
|
| 32 |
+
from legex.prompts import PromptPlan, load_plan
|
| 33 |
+
from legex.scrapers import SCRAPERS
|
| 34 |
+
from legex.utils import (
|
| 35 |
+
classified_csv_path,
|
| 36 |
+
countries_with_goldenset,
|
| 37 |
+
goldenset_path,
|
| 38 |
+
goldenset_sheet,
|
| 39 |
+
load_coding_rules,
|
| 40 |
+
load_goldenset_columns,
|
| 41 |
+
load_isic_categories,
|
| 42 |
+
norm_case_id,
|
| 43 |
+
pdf_paths,
|
| 44 |
+
read_full_text_jsonl,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
log = logging.getLogger(__name__)
|
| 48 |
+
|
| 49 |
+
_DATE_FIELD_KEYS: frozenset[str] = frozenset(
|
| 50 |
+
name
|
| 51 |
+
for name, info in Classification.model_fields.items()
|
| 52 |
+
if date in getattr(info.annotation, "__args__", (info.annotation,))
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _coerce_json_dates(data: dict) -> None:
|
| 57 |
+
"""JSON has no date type; convert strings before pydantic validation."""
|
| 58 |
+
for key in _DATE_FIELD_KEYS:
|
| 59 |
+
if key not in data:
|
| 60 |
+
continue
|
| 61 |
+
val = data[key]
|
| 62 |
+
if isinstance(val, str) and val:
|
| 63 |
+
data[key] = date.fromisoformat(val)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _parse_classification(content: str) -> Classification:
|
| 67 |
+
"""Parse LLM JSON; accept a one-element array when the model returns a list."""
|
| 68 |
+
data = json.loads(content)
|
| 69 |
+
if isinstance(data, list):
|
| 70 |
+
if len(data) != 1 or not isinstance(data[0], dict):
|
| 71 |
+
raise ValueError("expected a JSON object or a one-element array of objects")
|
| 72 |
+
data = data[0]
|
| 73 |
+
_coerce_json_dates(data)
|
| 74 |
+
return Classification.model_validate(data)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class _RequestRateLimiter:
|
| 78 |
+
"""Minimum spacing between LLM calls (60 / rpm seconds). None rpm = no limit."""
|
| 79 |
+
|
| 80 |
+
def __init__(self, rpm: int | None) -> None:
|
| 81 |
+
self._min_interval = 60.0 / rpm if rpm else 0.0
|
| 82 |
+
self._last_at = 0.0
|
| 83 |
+
self._sync_lock = threading.Lock()
|
| 84 |
+
self._async_lock: asyncio.Lock | None = None
|
| 85 |
+
|
| 86 |
+
def acquire(self) -> None:
|
| 87 |
+
if self._min_interval <= 0:
|
| 88 |
+
return
|
| 89 |
+
with self._sync_lock:
|
| 90 |
+
now = time.monotonic()
|
| 91 |
+
wait = self._min_interval - (now - self._last_at)
|
| 92 |
+
if wait > 0:
|
| 93 |
+
time.sleep(wait)
|
| 94 |
+
self._last_at = time.monotonic()
|
| 95 |
+
|
| 96 |
+
async def acquire_async(self) -> None:
|
| 97 |
+
if self._min_interval <= 0:
|
| 98 |
+
return
|
| 99 |
+
if self._async_lock is None:
|
| 100 |
+
self._async_lock = asyncio.Lock()
|
| 101 |
+
async with self._async_lock:
|
| 102 |
+
now = time.monotonic()
|
| 103 |
+
wait = self._min_interval - (now - self._last_at)
|
| 104 |
+
if wait > 0:
|
| 105 |
+
await asyncio.sleep(wait)
|
| 106 |
+
self._last_at = time.monotonic()
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def inference_output_path(cc: str, prompt_version: str, source: str, model: str) -> Path:
|
| 110 |
+
return classified_csv_path(cc, prompt_version, source, model)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# CSV columns (and GOLDENSET headers) use the alias when one is set,
|
| 114 |
+
# e.g. `Currency_dispute_value_nominal` (capital C). The Python attribute
|
| 115 |
+
# is the lowercase model field name. These maps move between the two.
|
| 116 |
+
_FIELD_TO_COL: dict[str, str] = {
|
| 117 |
+
name: (info.alias or name) for name, info in Classification.model_fields.items()
|
| 118 |
+
}
|
| 119 |
+
_COL_TO_FIELD: dict[str, str] = {col: field for field, col in _FIELD_TO_COL.items()}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _output_columns() -> list[str]:
|
| 123 |
+
headers = load_goldenset_columns(settings.template)
|
| 124 |
+
return [h for h in headers if h != "full_text"] + ["model", "error"]
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _read_goldenset_cases(cc: str) -> list[Case]:
|
| 128 |
+
"""Pull case_id / link / full_text rows from the GOLDENSET sheet.
|
| 129 |
+
|
| 130 |
+
Falls back to data/<cc>/full_text.jsonl (keyed by case_id) when the xlsx
|
| 131 |
+
full_text column is empty or absent, so jurisdictions whose text doesn't
|
| 132 |
+
fit in Excel can still be classified.
|
| 133 |
+
"""
|
| 134 |
+
path = goldenset_path(cc)
|
| 135 |
+
wb = load_workbook(path, read_only=True, data_only=True)
|
| 136 |
+
ws = goldenset_sheet(wb)
|
| 137 |
+
rows = ws.iter_rows(values_only=True)
|
| 138 |
+
header = [str(c) if c is not None else "" for c in next(rows)]
|
| 139 |
+
idx = {h.strip().lower(): i for i, h in enumerate(header) if h}
|
| 140 |
+
for required in ("case_id", "link"):
|
| 141 |
+
if required not in idx:
|
| 142 |
+
raise ValueError(f"{path} GOLDENSET sheet missing column {required!r}")
|
| 143 |
+
full_text_idx = idx.get("full_text")
|
| 144 |
+
fallback = read_full_text_jsonl(cc)
|
| 145 |
+
if full_text_idx is None and not fallback:
|
| 146 |
+
raise ValueError(
|
| 147 |
+
f"{path} GOLDENSET sheet has no full_text column and no "
|
| 148 |
+
f"data/{cc}/full_text.jsonl fallback"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
cases: list[Case] = []
|
| 152 |
+
n_from_jsonl = 0
|
| 153 |
+
for row in rows:
|
| 154 |
+
if not any(row):
|
| 155 |
+
continue
|
| 156 |
+
case_id = row[idx["case_id"]]
|
| 157 |
+
link = row[idx["link"]]
|
| 158 |
+
full_text = row[full_text_idx] if full_text_idx is not None else None
|
| 159 |
+
if not full_text and case_id is not None:
|
| 160 |
+
cid_s = str(case_id)
|
| 161 |
+
fb = fallback.get(cid_s) or fallback.get(norm_case_id(cid_s))
|
| 162 |
+
if fb:
|
| 163 |
+
full_text = fb
|
| 164 |
+
n_from_jsonl += 1
|
| 165 |
+
cases.append(
|
| 166 |
+
Case(
|
| 167 |
+
case_id=str(case_id) if case_id is not None else None,
|
| 168 |
+
link=str(link) if link is not None else None,
|
| 169 |
+
jurisdiction=cc,
|
| 170 |
+
full_text=str(full_text) if full_text is not None else None,
|
| 171 |
+
)
|
| 172 |
+
)
|
| 173 |
+
if n_from_jsonl:
|
| 174 |
+
log.info(f"[{cc}] using full_text from full_text.jsonl for {n_from_jsonl} case(s)")
|
| 175 |
+
return cases
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _read_pdf_cases(cc: str) -> list[Case]:
|
| 179 |
+
"""One Case per PDF at data/<cc>/*.pdf; case_id = file stem."""
|
| 180 |
+
from pypdf import PdfReader
|
| 181 |
+
|
| 182 |
+
cases: list[Case] = []
|
| 183 |
+
for pdf in pdf_paths(cc):
|
| 184 |
+
try:
|
| 185 |
+
reader = PdfReader(str(pdf))
|
| 186 |
+
text = "\n".join((page.extract_text() or "") for page in reader.pages)
|
| 187 |
+
except Exception as e:
|
| 188 |
+
log.warning(f"[{cc}] failed to read {pdf.name}: {type(e).__name__}: {e}")
|
| 189 |
+
text = ""
|
| 190 |
+
cases.append(
|
| 191 |
+
Case(
|
| 192 |
+
case_id=pdf.stem,
|
| 193 |
+
link=str(pdf),
|
| 194 |
+
jurisdiction=cc,
|
| 195 |
+
full_text=text or None,
|
| 196 |
+
)
|
| 197 |
+
)
|
| 198 |
+
return cases
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _read_cases(cc: str, source: str) -> list[Case]:
|
| 202 |
+
if source == "full_text":
|
| 203 |
+
return _read_goldenset_cases(cc)
|
| 204 |
+
return _read_pdf_cases(cc)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _empty_row(case: Case, model: str, columns: list[str]) -> dict[str, str]:
|
| 208 |
+
row: dict[str, str] = {col: "" for col in columns}
|
| 209 |
+
row["case_id"] = case.case_id or ""
|
| 210 |
+
row["link"] = case.link or ""
|
| 211 |
+
row["model"] = model
|
| 212 |
+
return row
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
async def _classify_case_single(
|
| 216 |
+
case: Case,
|
| 217 |
+
system_prompt: str,
|
| 218 |
+
model: str,
|
| 219 |
+
columns: list[str],
|
| 220 |
+
limiter: _RequestRateLimiter,
|
| 221 |
+
) -> dict[str, str]:
|
| 222 |
+
import litellm
|
| 223 |
+
|
| 224 |
+
row = _empty_row(case, model, columns)
|
| 225 |
+
if not case.full_text:
|
| 226 |
+
row["error"] = "no full_text"
|
| 227 |
+
return row
|
| 228 |
+
|
| 229 |
+
try:
|
| 230 |
+
await limiter.acquire_async()
|
| 231 |
+
resp = await litellm.acompletion(
|
| 232 |
+
model=model,
|
| 233 |
+
messages=[
|
| 234 |
+
{"role": "system", "content": system_prompt},
|
| 235 |
+
{"role": "user", "content": case.full_text},
|
| 236 |
+
],
|
| 237 |
+
response_format=Classification,
|
| 238 |
+
)
|
| 239 |
+
content = resp["choices"][0]["message"]["content"]
|
| 240 |
+
parsed = _parse_classification(content)
|
| 241 |
+
except Exception as e:
|
| 242 |
+
row["error"] = f"{type(e).__name__}: {e}"
|
| 243 |
+
return row
|
| 244 |
+
|
| 245 |
+
extras = [col for col in _FIELD_TO_COL.values() if col not in row]
|
| 246 |
+
if extras:
|
| 247 |
+
row["error"] = f"Classification fields not in GOLDENSET header: {extras}"
|
| 248 |
+
return row
|
| 249 |
+
for field, col in _FIELD_TO_COL.items():
|
| 250 |
+
value = getattr(parsed, field)
|
| 251 |
+
row[col] = "" if value is None else str(value)
|
| 252 |
+
return row
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
async def _classify_one_column(
|
| 256 |
+
column: str,
|
| 257 |
+
system_prompt: str,
|
| 258 |
+
full_text: str,
|
| 259 |
+
model: str,
|
| 260 |
+
limiter: _RequestRateLimiter,
|
| 261 |
+
) -> tuple[str, object | None, str | None]:
|
| 262 |
+
"""Return (CSV column, value, error). `column` is the CSV header name
|
| 263 |
+
(alias-aware); we read the corresponding Python attribute off the
|
| 264 |
+
parsed Classification."""
|
| 265 |
+
import litellm
|
| 266 |
+
|
| 267 |
+
try:
|
| 268 |
+
await limiter.acquire_async()
|
| 269 |
+
resp = await litellm.acompletion(
|
| 270 |
+
model=model,
|
| 271 |
+
messages=[
|
| 272 |
+
{"role": "system", "content": system_prompt},
|
| 273 |
+
{"role": "user", "content": full_text},
|
| 274 |
+
],
|
| 275 |
+
response_format={"type": "json_object"},
|
| 276 |
+
)
|
| 277 |
+
content = resp["choices"][0]["message"]["content"]
|
| 278 |
+
parsed = _parse_classification(content)
|
| 279 |
+
field = _COL_TO_FIELD.get(column, column)
|
| 280 |
+
return column, getattr(parsed, field), None
|
| 281 |
+
except Exception as e:
|
| 282 |
+
return column, None, f"{column}: {type(e).__name__}: {e}"
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
async def _classify_case_per_column(
|
| 286 |
+
case: Case,
|
| 287 |
+
column_systems: dict[str, str],
|
| 288 |
+
model: str,
|
| 289 |
+
columns: list[str],
|
| 290 |
+
limiter: _RequestRateLimiter,
|
| 291 |
+
) -> dict[str, str]:
|
| 292 |
+
row = _empty_row(case, model, columns)
|
| 293 |
+
if not case.full_text:
|
| 294 |
+
row["error"] = "no full_text"
|
| 295 |
+
return row
|
| 296 |
+
|
| 297 |
+
extras = [c for c in column_systems if c not in row]
|
| 298 |
+
if extras:
|
| 299 |
+
row["error"] = f"Per-column prompts target fields not in GOLDENSET header: {extras}"
|
| 300 |
+
return row
|
| 301 |
+
|
| 302 |
+
results = await asyncio.gather(
|
| 303 |
+
*(
|
| 304 |
+
_classify_one_column(col, sys_prompt, case.full_text, model, limiter)
|
| 305 |
+
for col, sys_prompt in column_systems.items()
|
| 306 |
+
)
|
| 307 |
+
)
|
| 308 |
+
errors: list[str] = []
|
| 309 |
+
for col, value, err in results:
|
| 310 |
+
if err is not None:
|
| 311 |
+
errors.append(err)
|
| 312 |
+
elif value is not None:
|
| 313 |
+
row[col] = str(value)
|
| 314 |
+
if errors:
|
| 315 |
+
row["error"] = "; ".join(errors)
|
| 316 |
+
return row
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class _CsvRowWriter:
|
| 320 |
+
"""Append rows to a CSV, flushing after each write."""
|
| 321 |
+
|
| 322 |
+
def __init__(self, path: Path, columns: list[str]) -> None:
|
| 323 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 324 |
+
write_header = not path.exists()
|
| 325 |
+
self._file = open(path, "a", encoding="utf-8", newline="")
|
| 326 |
+
self._writer = csv.DictWriter(self._file, fieldnames=columns)
|
| 327 |
+
if write_header:
|
| 328 |
+
self._writer.writeheader()
|
| 329 |
+
|
| 330 |
+
def write_row(self, row: dict[str, str]) -> None:
|
| 331 |
+
self._writer.writerow(row)
|
| 332 |
+
self._file.flush()
|
| 333 |
+
|
| 334 |
+
def close(self) -> None:
|
| 335 |
+
self._file.close()
|
| 336 |
+
|
| 337 |
+
def __enter__(self) -> "_CsvRowWriter":
|
| 338 |
+
return self
|
| 339 |
+
|
| 340 |
+
def __exit__(self, *args: object) -> None:
|
| 341 |
+
self.close()
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def _classify_cases(
|
| 345 |
+
cases: list[Case],
|
| 346 |
+
plan: PromptPlan,
|
| 347 |
+
model: str,
|
| 348 |
+
columns: list[str],
|
| 349 |
+
limiter: _RequestRateLimiter,
|
| 350 |
+
write_row: Callable[[dict[str, str]], None],
|
| 351 |
+
concurrency: int = 1,
|
| 352 |
+
) -> int:
|
| 353 |
+
"""Classify cases and stream each result via write_row. Returns success count.
|
| 354 |
+
|
| 355 |
+
With concurrency > 1, up to N cases are processed in parallel; the rate
|
| 356 |
+
limiter still gates total request throughput. Rows are written as each
|
| 357 |
+
case finishes, so output order is non-deterministic when concurrency > 1.
|
| 358 |
+
"""
|
| 359 |
+
|
| 360 |
+
async def run_all() -> int:
|
| 361 |
+
sem = asyncio.Semaphore(max(1, concurrency))
|
| 362 |
+
|
| 363 |
+
async def process(case: Case) -> dict[str, str]:
|
| 364 |
+
async with sem:
|
| 365 |
+
if plan.mode == "single":
|
| 366 |
+
return await _classify_case_single(
|
| 367 |
+
case, plan.system or "", model, columns, limiter
|
| 368 |
+
)
|
| 369 |
+
return await _classify_case_per_column(
|
| 370 |
+
case, plan.column_systems or {}, model, columns, limiter
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
ok = 0
|
| 374 |
+
for coro in asyncio.as_completed([process(c) for c in cases]):
|
| 375 |
+
row = await coro
|
| 376 |
+
write_row(row)
|
| 377 |
+
if not row["error"]:
|
| 378 |
+
ok += 1
|
| 379 |
+
return ok
|
| 380 |
+
|
| 381 |
+
return asyncio.run(run_all())
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def _successful_case_ids(path: Path) -> set[str]:
|
| 385 |
+
if not path.exists():
|
| 386 |
+
return set()
|
| 387 |
+
ids: set[str] = set()
|
| 388 |
+
with open(path, encoding="utf-8", newline="") as f:
|
| 389 |
+
for r in csv.DictReader(f):
|
| 390 |
+
if (r.get("error") or "").strip():
|
| 391 |
+
continue
|
| 392 |
+
cid = (r.get("case_id") or "").strip()
|
| 393 |
+
if cid:
|
| 394 |
+
ids.add(cid)
|
| 395 |
+
return ids
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def _drop_case_ids(path: Path, columns: list[str], case_ids: set[str]) -> int:
|
| 399 |
+
"""Remove rows for the given case_ids. Returns number of rows removed."""
|
| 400 |
+
if not path.exists() or not case_ids:
|
| 401 |
+
return 0
|
| 402 |
+
with open(path, encoding="utf-8", newline="") as f:
|
| 403 |
+
rows = list(csv.DictReader(f))
|
| 404 |
+
kept = [r for r in rows if (r.get("case_id") or "").strip() not in case_ids]
|
| 405 |
+
removed = len(rows) - len(kept)
|
| 406 |
+
if removed == 0:
|
| 407 |
+
return 0
|
| 408 |
+
with open(path, "w", encoding="utf-8", newline="") as f:
|
| 409 |
+
writer = csv.DictWriter(f, fieldnames=columns, extrasaction="ignore")
|
| 410 |
+
writer.writeheader()
|
| 411 |
+
writer.writerows(kept)
|
| 412 |
+
return removed
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def classify(
|
| 416 |
+
countries: list[str] | None,
|
| 417 |
+
model: str,
|
| 418 |
+
source: str,
|
| 419 |
+
prompt_version: str,
|
| 420 |
+
limit: int | None,
|
| 421 |
+
rpm: int | None = None,
|
| 422 |
+
concurrency: int = 1,
|
| 423 |
+
) -> None:
|
| 424 |
+
rules = load_coding_rules(settings.template)
|
| 425 |
+
isic = load_isic_categories(settings.template)
|
| 426 |
+
columns = _output_columns()
|
| 427 |
+
plan = load_plan(prompt_version, rules, isic)
|
| 428 |
+
limiter = _RequestRateLimiter(rpm)
|
| 429 |
+
if rpm:
|
| 430 |
+
log.info(f"Rate limit: {rpm} requests/min ({limiter._min_interval:.2f}s between calls)")
|
| 431 |
+
if concurrency > 1:
|
| 432 |
+
log.info(f"Concurrency: up to {concurrency} cases in parallel")
|
| 433 |
+
|
| 434 |
+
targets = countries or countries_with_goldenset() or list(SCRAPERS)
|
| 435 |
+
for cc in targets:
|
| 436 |
+
if source == "full_text":
|
| 437 |
+
gs = goldenset_path(cc)
|
| 438 |
+
if not gs.exists():
|
| 439 |
+
log.warning(f"[{cc}] missing {gs}, skipping")
|
| 440 |
+
continue
|
| 441 |
+
else:
|
| 442 |
+
if not pdf_paths(cc):
|
| 443 |
+
log.warning(f"[{cc}] no PDFs at {settings.data_dir / cc}/*.pdf, skipping")
|
| 444 |
+
continue
|
| 445 |
+
|
| 446 |
+
cases = _read_cases(cc, source)
|
| 447 |
+
if not cases:
|
| 448 |
+
log.info(f"[{cc}] no cases found, skipping")
|
| 449 |
+
continue
|
| 450 |
+
|
| 451 |
+
out = inference_output_path(cc, prompt_version, source, model)
|
| 452 |
+
done = _successful_case_ids(out)
|
| 453 |
+
todo = [c for c in cases if (c.case_id or "") not in done]
|
| 454 |
+
if limit is not None:
|
| 455 |
+
todo = todo[:limit]
|
| 456 |
+
if not todo:
|
| 457 |
+
log.info(f"[{cc}] all {len(cases)} cases already classified in {out}, skipping")
|
| 458 |
+
continue
|
| 459 |
+
|
| 460 |
+
retry_ids = {c.case_id for c in todo if c.case_id}
|
| 461 |
+
n_removed = _drop_case_ids(out, columns, retry_ids)
|
| 462 |
+
n_new = len(todo) - n_removed
|
| 463 |
+
if n_removed:
|
| 464 |
+
log.info(f"[{cc}] retrying {n_removed} failed case(s), {n_new} new")
|
| 465 |
+
|
| 466 |
+
log.info(
|
| 467 |
+
f"[{cc}] classifying {len(todo)} cases ({len(done)} already done) "
|
| 468 |
+
f"in {plan.mode} mode → {out}"
|
| 469 |
+
)
|
| 470 |
+
with _CsvRowWriter(out, columns) as writer:
|
| 471 |
+
n_ok = _classify_cases(
|
| 472 |
+
todo, plan, model, columns, limiter, writer.write_row, concurrency
|
| 473 |
+
)
|
| 474 |
+
log.info(f"[{cc}] classified {n_ok}/{len(todo)} → {out}")
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def main() -> None:
|
| 478 |
+
logging.basicConfig(
|
| 479 |
+
level=logging.INFO,
|
| 480 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 481 |
+
handlers=[logging.StreamHandler(sys.stderr)],
|
| 482 |
+
)
|
| 483 |
+
load_dotenv(override=True)
|
| 484 |
+
print(f"gemini key {os.environ.get('GEMINI_API_KEY')}") # sanity check for env var
|
| 485 |
+
|
| 486 |
+
parser = argparse.ArgumentParser(
|
| 487 |
+
prog="legex-classify",
|
| 488 |
+
description="Run LLM inference over Goldenset full_text or per-country PDFs.",
|
| 489 |
+
)
|
| 490 |
+
parser.add_argument(
|
| 491 |
+
"--country",
|
| 492 |
+
action="extend",
|
| 493 |
+
nargs="+",
|
| 494 |
+
dest="countries",
|
| 495 |
+
help="Country code (repeatable). Defaults to all registered scrapers.",
|
| 496 |
+
)
|
| 497 |
+
parser.add_argument(
|
| 498 |
+
"--model",
|
| 499 |
+
default="gpt-4o-mini",
|
| 500 |
+
help="litellm model id (e.g. gpt-4o-mini, anthropic/claude-opus-4-7).",
|
| 501 |
+
)
|
| 502 |
+
parser.add_argument(
|
| 503 |
+
"--prompt_version",
|
| 504 |
+
default="v1",
|
| 505 |
+
help="Prompt version under legex/prompts/ (default: v1).",
|
| 506 |
+
)
|
| 507 |
+
parser.add_argument(
|
| 508 |
+
"--limit",
|
| 509 |
+
type=int,
|
| 510 |
+
default=None,
|
| 511 |
+
help="Cap NEW cases per country (useful for cheap dry runs).",
|
| 512 |
+
)
|
| 513 |
+
parser.add_argument(
|
| 514 |
+
"--rpm",
|
| 515 |
+
type=int,
|
| 516 |
+
default=None,
|
| 517 |
+
metavar="N",
|
| 518 |
+
help="Max LLM requests per minute (applies to every completion call).",
|
| 519 |
+
)
|
| 520 |
+
parser.add_argument(
|
| 521 |
+
"--concurrency",
|
| 522 |
+
type=int,
|
| 523 |
+
default=1,
|
| 524 |
+
metavar="N",
|
| 525 |
+
help="Process up to N cases in parallel (default: 1).",
|
| 526 |
+
)
|
| 527 |
+
source = parser.add_mutually_exclusive_group(required=True)
|
| 528 |
+
source.add_argument(
|
| 529 |
+
"--full_text",
|
| 530 |
+
dest="source",
|
| 531 |
+
action="store_const",
|
| 532 |
+
const="full_text",
|
| 533 |
+
help="Read input from the full_text column of data/<cc>/Goldenset_*.xlsx.",
|
| 534 |
+
)
|
| 535 |
+
source.add_argument(
|
| 536 |
+
"--pdf",
|
| 537 |
+
dest="source",
|
| 538 |
+
action="store_const",
|
| 539 |
+
const="pdf",
|
| 540 |
+
help="Read input from data/<cc>/*.pdf.",
|
| 541 |
+
)
|
| 542 |
+
args = parser.parse_args()
|
| 543 |
+
if args.rpm is not None and args.rpm <= 0:
|
| 544 |
+
parser.error("--rpm must be a positive integer")
|
| 545 |
+
if args.concurrency <= 0:
|
| 546 |
+
parser.error("--concurrency must be a positive integer")
|
| 547 |
+
|
| 548 |
+
classify(
|
| 549 |
+
countries=args.countries,
|
| 550 |
+
model=args.model,
|
| 551 |
+
source=args.source,
|
| 552 |
+
prompt_version=args.prompt_version,
|
| 553 |
+
limit=args.limit,
|
| 554 |
+
rpm=args.rpm,
|
| 555 |
+
concurrency=args.concurrency,
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
if __name__ == "__main__":
|
| 560 |
+
main()
|
legex/main.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the full pipeline: scrape → filter_and_sample → fill_goldenset → dist."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import logging
|
| 5 |
+
import sys
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
|
| 8 |
+
from legex.processing import dist, fill_goldenset, filter_and_sample, scrape
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def main() -> None:
|
| 12 |
+
logging.basicConfig(
|
| 13 |
+
level=logging.INFO,
|
| 14 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 15 |
+
handlers=[logging.StreamHandler(sys.stderr)],
|
| 16 |
+
)
|
| 17 |
+
load_dotenv()
|
| 18 |
+
|
| 19 |
+
parser = argparse.ArgumentParser(
|
| 20 |
+
prog="legex-run",
|
| 21 |
+
description="Run the legex pipeline (scrape → filter_and_sample → fill_goldenset → dist).",
|
| 22 |
+
)
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
"-f", "--force",
|
| 25 |
+
action="store_true",
|
| 26 |
+
help="Recreate all artefacts, overwriting cached outputs at every stage.",
|
| 27 |
+
)
|
| 28 |
+
args = parser.parse_args()
|
| 29 |
+
|
| 30 |
+
scrape(force=args.force)
|
| 31 |
+
filter_and_sample(force=args.force)
|
| 32 |
+
fill_goldenset(force=args.force)
|
| 33 |
+
dist(force=args.force)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if __name__ == "__main__":
|
| 37 |
+
main()
|
legex/models/__init__.py
ADDED
|
File without changes
|
legex/models/base.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import date
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Case(BaseModel):
|
| 8 |
+
case_id: str | None = None
|
| 9 |
+
link: str | None = None
|
| 10 |
+
decision_date: date | None = None
|
| 11 |
+
jurisdiction: str # ISO country code: "ch", "fr", etc.
|
| 12 |
+
language: str | None = None # ISO 639-1: "de", "fr", "it", "en"
|
| 13 |
+
full_text: str | None = None # populated in jsonl mode only
|
| 14 |
+
metadata: dict[str, Any] = {} # jurisdiction-specific extra fields
|
legex/models/classification.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import date
|
| 2 |
+
from typing import Literal
|
| 3 |
+
|
| 4 |
+
from pydantic import BaseModel, ConfigDict, Field
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Classification(BaseModel):
|
| 8 |
+
"""LLM-extracted variables for a single legal case.
|
| 9 |
+
|
| 10 |
+
Strict typing: numbers are numbers, dates are dates. The LLM must
|
| 11 |
+
return native JSON types — no string-wrapped numerics.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
model_config = ConfigDict(strict=True, populate_by_name=True)
|
| 15 |
+
|
| 16 |
+
legal_subject_judgement: str | None = Field(
|
| 17 |
+
default=None, description="Legal subject of the case (English, formatted)."
|
| 18 |
+
)
|
| 19 |
+
trial_start_date: date | None = Field(
|
| 20 |
+
default=None, description="Trial start date (YYYY-MM-DD)."
|
| 21 |
+
)
|
| 22 |
+
trial_end_date: date | None = Field(
|
| 23 |
+
default=None, description="Trial end (decision) date (YYYY-MM-DD)."
|
| 24 |
+
)
|
| 25 |
+
dispute_value_nominal: float | Literal["nonpecuniary"] | None = Field(
|
| 26 |
+
default=None,
|
| 27 |
+
description="Amount in dispute as a number, or the literal string 'nonpecuniary'.",
|
| 28 |
+
)
|
| 29 |
+
currency_dispute_value_nominal: str | None = Field(
|
| 30 |
+
default=None,
|
| 31 |
+
alias="Currency_dispute_value_nominal",
|
| 32 |
+
description="ISO-4217 currency code for the dispute value (e.g. CHF).",
|
| 33 |
+
)
|
| 34 |
+
plaintiff_loosing_share: float | None = Field(
|
| 35 |
+
default=None, description="Plaintiff's losing share between 0.0 and 1.0."
|
| 36 |
+
)
|
| 37 |
+
court_cost_awarded_nominal: float | None = Field(
|
| 38 |
+
default=None, description="Total court fees as a number."
|
| 39 |
+
)
|
| 40 |
+
currency_court_cost_awarded_nominal: str | None = Field(
|
| 41 |
+
default=None,
|
| 42 |
+
alias="Currency_court_cost_awarded_nominal",
|
| 43 |
+
description="ISO-4217 currency code for the court fees.",
|
| 44 |
+
)
|
| 45 |
+
party_compensation_awarded_nominal: float | None = Field(
|
| 46 |
+
default=None, description="Total party compensation as a number."
|
| 47 |
+
)
|
| 48 |
+
currency_party_compensation_awarded_nominal: str | None = Field(
|
| 49 |
+
default=None,
|
| 50 |
+
alias="Currency_party_compensation_awarded_nominal",
|
| 51 |
+
description="ISO-4217 currency code for party compensation.",
|
| 52 |
+
)
|
| 53 |
+
plaintiffs_all_count: int | None = Field(
|
| 54 |
+
default=None, description="Number of plaintiffs."
|
| 55 |
+
)
|
| 56 |
+
defendants_all_count: int | None = Field(
|
| 57 |
+
default=None, description="Number of defendants."
|
| 58 |
+
)
|
| 59 |
+
plaintiff_no1_ISIC1_industry_category: str | None = Field(
|
| 60 |
+
default=None, description="ISIC sector for the first plaintiff."
|
| 61 |
+
)
|
| 62 |
+
defendant_no1_ISIC1_industry_category: str | None = Field(
|
| 63 |
+
default=None, description="ISIC sector for the first defendant."
|
| 64 |
+
)
|
legex/pdf_export/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export goldenset rows to PDF (sheet text or fetched from URLs)."""
|
| 2 |
+
|
| 3 |
+
__all__ = ["ensure_fonts"]
|
| 4 |
+
|
| 5 |
+
from legex.pdf_export.core import ensure_fonts
|
legex/pdf_export/cli.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CLI: ``legex-pdf sheet`` (table only) and ``legex-pdf urls`` (HTTP + fallback)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
|
| 11 |
+
from legex.config import settings
|
| 12 |
+
from legex.pdf_export.core import ensure_fonts
|
| 13 |
+
from legex.pdf_export.sheet import export_workbook as export_sheet_workbook
|
| 14 |
+
from legex.pdf_export.urls import collect_workbooks, export_workbook as export_urls_workbook
|
| 15 |
+
from legex.pdf_export.workbook import discover_goldensets
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _data_dir(ns: argparse.Namespace) -> Path:
|
| 19 |
+
if getattr(ns, "data_dir", None):
|
| 20 |
+
return Path(ns.data_dir).expanduser().resolve()
|
| 21 |
+
return settings.data_dir.expanduser().resolve()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _cmd_sheet(ns: argparse.Namespace) -> int:
|
| 25 |
+
data_dir = _data_dir(ns)
|
| 26 |
+
files = discover_goldensets(data_dir) if not ns.input_dir else _files_from_input_dirs(ns.input_dir)
|
| 27 |
+
if not files:
|
| 28 |
+
print("Keine Goldenset_*.xlsx gefunden.", file=sys.stderr)
|
| 29 |
+
return 1
|
| 30 |
+
out = data_dir / "pdf" / "from_sheet"
|
| 31 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 32 |
+
ensure_fonts()
|
| 33 |
+
print(f"→ {len(files)} Workbooks → {out}\n", flush=True)
|
| 34 |
+
total = 0
|
| 35 |
+
for xlsx in files:
|
| 36 |
+
print(xlsx, flush=True)
|
| 37 |
+
total += export_sheet_workbook(xlsx, out, limit=ns.limit)
|
| 38 |
+
print(f"Insgesamt PDFs: {total}")
|
| 39 |
+
return 0
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _cmd_urls(ns: argparse.Namespace) -> int:
|
| 43 |
+
data_dir = _data_dir(ns)
|
| 44 |
+
input_dirs = [Path(p).expanduser().resolve() for p in ns.input_dir] if ns.input_dir else None
|
| 45 |
+
files = collect_workbooks(data_dir, input_dirs)
|
| 46 |
+
if not files:
|
| 47 |
+
print("Keine Goldenset_*.xlsx gefunden.", file=sys.stderr)
|
| 48 |
+
return 1
|
| 49 |
+
out = data_dir / "pdf" / "from_urls"
|
| 50 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 51 |
+
ensure_fonts()
|
| 52 |
+
mode = "explizite --input-dir" if input_dirs else f"unter {data_dir}"
|
| 53 |
+
print(f"→ {len(files)} Workbooks ({mode}) → {out}\n", flush=True)
|
| 54 |
+
total = 0
|
| 55 |
+
for xlsx in files:
|
| 56 |
+
print(xlsx, flush=True)
|
| 57 |
+
total += export_urls_workbook(
|
| 58 |
+
xlsx,
|
| 59 |
+
out,
|
| 60 |
+
pause_s=ns.pause,
|
| 61 |
+
limit=ns.limit,
|
| 62 |
+
req_timeout=ns.timeout,
|
| 63 |
+
resume=ns.resume,
|
| 64 |
+
)
|
| 65 |
+
print(f"Insgesamt PDFs: {total}")
|
| 66 |
+
return 0
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _files_from_input_dirs(paths: list[str]) -> list[Path]:
|
| 70 |
+
files: list[Path] = []
|
| 71 |
+
for raw in paths:
|
| 72 |
+
d = Path(raw).expanduser().resolve()
|
| 73 |
+
if not d.is_dir():
|
| 74 |
+
print("Ordner fehlt:", d, file=sys.stderr)
|
| 75 |
+
continue
|
| 76 |
+
files.extend(sorted(d.glob("Goldenset_*.xlsx")))
|
| 77 |
+
return sorted(files, key=lambda p: (p.stem.lower(), str(p)))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def main() -> None:
|
| 81 |
+
load_dotenv()
|
| 82 |
+
ap = argparse.ArgumentParser(prog="legex-pdf")
|
| 83 |
+
ap.add_argument(
|
| 84 |
+
"--data-dir",
|
| 85 |
+
type=Path,
|
| 86 |
+
default=None,
|
| 87 |
+
help="Daten-Root (Default: settings.data_dir, per .env z. B. DATA_DIR)",
|
| 88 |
+
)
|
| 89 |
+
sub = ap.add_subparsers(dest="command", required=True)
|
| 90 |
+
|
| 91 |
+
p_sheet = sub.add_parser("sheet", help="PDF aus Spalte full_text (ohne HTTP)")
|
| 92 |
+
p_sheet.add_argument("--limit", type=int, default=None, help="Max. PDFs pro Workbook")
|
| 93 |
+
p_sheet.add_argument(
|
| 94 |
+
"--input-dir",
|
| 95 |
+
action="append",
|
| 96 |
+
dest="input_dir",
|
| 97 |
+
help="Ordner mit Goldenset_*.xlsx (mehrfach möglich); sonst data_dir/*/Goldenset_*.xlsx",
|
| 98 |
+
)
|
| 99 |
+
p_sheet.set_defaults(_run=_cmd_sheet)
|
| 100 |
+
|
| 101 |
+
p_urls = sub.add_parser("urls", help="PDF aus URL-Fetch, Fallback full_text")
|
| 102 |
+
p_urls.add_argument("--timeout", type=float, default=28.0, help="HTTP-Timeout (Sek.)")
|
| 103 |
+
p_urls.add_argument("--pause", type=float, default=0.25, help="Pause zwischen Requests (Sek.)")
|
| 104 |
+
p_urls.add_argument("--limit", type=int, default=None, help="Max. PDFs pro Workbook (inkl. Resume)")
|
| 105 |
+
p_urls.add_argument("--resume", action="store_true", help="Vorhandene PDFs nicht überschreiben")
|
| 106 |
+
p_urls.add_argument(
|
| 107 |
+
"--input-dir",
|
| 108 |
+
action="append",
|
| 109 |
+
dest="input_dir",
|
| 110 |
+
help="Ordner mit Goldenset_*.xlsx; sonst data_dir/*/Goldenset_*.xlsx",
|
| 111 |
+
)
|
| 112 |
+
p_urls.set_defaults(_run=_cmd_urls)
|
| 113 |
+
|
| 114 |
+
ns = ap.parse_args()
|
| 115 |
+
raise SystemExit(ns._run(ns))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
main()
|
legex/pdf_export/core.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Font download, sanitization, and FPDF writing."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import re
|
| 7 |
+
import urllib.request
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from fpdf import FPDF
|
| 11 |
+
from fpdf.enums import Align, WrapMode
|
| 12 |
+
|
| 13 |
+
FONT_DIR = Path(__file__).resolve().parent / "_fonts"
|
| 14 |
+
|
| 15 |
+
FONT_URLS = {
|
| 16 |
+
"NotoSans-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf",
|
| 17 |
+
"SourceHanSansSC-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/SimplifiedChinese/SourceHanSansSC-Regular.otf",
|
| 18 |
+
"SourceHanSansK-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/Korean/SourceHanSansK-Regular.otf",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
EXTRA_FONT_URLS = {
|
| 22 |
+
"SourceHanSansTC-Regular.otf": "https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/OTF/TraditionalChinese/SourceHanSansTC-Regular.otf",
|
| 23 |
+
"NotoSansDevanagari-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansDevanagari/NotoSansDevanagari-Regular.ttf",
|
| 24 |
+
"NotoSansArmenian-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansArmenian/NotoSansArmenian-Regular.ttf",
|
| 25 |
+
"NotoSansGeorgian-Regular.ttf": "https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansGeorgian/NotoSansGeorgian-Regular.ttf",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def ensure_fonts() -> None:
|
| 30 |
+
FONT_DIR.mkdir(parents=True, exist_ok=True)
|
| 31 |
+
all_fonts = {**FONT_URLS, **EXTRA_FONT_URLS}
|
| 32 |
+
for name, url in all_fonts.items():
|
| 33 |
+
dest = FONT_DIR / name
|
| 34 |
+
if dest.exists() and dest.stat().st_size > 1000:
|
| 35 |
+
continue
|
| 36 |
+
print(f"Downloading font {name} …", flush=True)
|
| 37 |
+
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
| 38 |
+
with urllib.request.urlopen(req, timeout=600) as r, open(dest, "wb") as f:
|
| 39 |
+
f.write(r.read())
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def sanitize_pdf_text(s: str) -> str:
|
| 43 |
+
s = str(s).replace("\t", " ").replace("\r\n", "\n").replace("\r", "\n")
|
| 44 |
+
s = s.replace("\uf0b7", "•").replace("\uf0a7", "•").replace("\uf0d8", "•")
|
| 45 |
+
s = s.replace("\uf02d", "–")
|
| 46 |
+
return s
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def safe_slug(case_id: str | None, link: str | None, row_idx: int) -> str:
|
| 50 |
+
raw = (case_id or "").strip()
|
| 51 |
+
if not raw:
|
| 52 |
+
h = hashlib.sha256(((link or "") + str(row_idx)).encode("utf-8")).hexdigest()[:12]
|
| 53 |
+
raw = f"decision_{row_idx}_{h}"
|
| 54 |
+
raw = raw.replace("\n", " ").strip()
|
| 55 |
+
raw = re.sub(r'[\x00-\x1f<>:"/\\|?*]', "_", raw)
|
| 56 |
+
raw = re.sub(r"\s+", "_", raw)
|
| 57 |
+
raw = raw.strip("._") or f"row_{row_idx}"
|
| 58 |
+
if len(raw) > 120:
|
| 59 |
+
raw = raw[:120].rstrip("_")
|
| 60 |
+
return raw
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class UnicodePDF(FPDF):
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def pdf_font_setup(pdf: FPDF, key: str) -> str:
|
| 68 |
+
if key == "han_sc":
|
| 69 |
+
pdf.add_font("HanSC", "", str(FONT_DIR / "SourceHanSansSC-Regular.otf"))
|
| 70 |
+
return "HanSC"
|
| 71 |
+
if key == "han_tc":
|
| 72 |
+
pdf.add_font("HanTC", "", str(FONT_DIR / "SourceHanSansTC-Regular.otf"))
|
| 73 |
+
return "HanTC"
|
| 74 |
+
if key == "han_k":
|
| 75 |
+
pdf.add_font("HanK", "", str(FONT_DIR / "SourceHanSansK-Regular.otf"))
|
| 76 |
+
return "HanK"
|
| 77 |
+
if key == "deva":
|
| 78 |
+
pdf.add_font("Deva", "", str(FONT_DIR / "NotoSansDevanagari-Regular.ttf"))
|
| 79 |
+
return "Deva"
|
| 80 |
+
if key == "arm":
|
| 81 |
+
pdf.add_font("Arm", "", str(FONT_DIR / "NotoSansArmenian-Regular.ttf"))
|
| 82 |
+
return "Arm"
|
| 83 |
+
if key == "geo":
|
| 84 |
+
pdf.add_font("Geo", "", str(FONT_DIR / "NotoSansGeorgian-Regular.ttf"))
|
| 85 |
+
return "Geo"
|
| 86 |
+
pdf.add_font("NotoSans", "", str(FONT_DIR / "NotoSans-Regular.ttf"))
|
| 87 |
+
return "NotoSans"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def write_one_pdf(
|
| 91 |
+
path: Path,
|
| 92 |
+
case_id: str,
|
| 93 |
+
link: str,
|
| 94 |
+
body: str,
|
| 95 |
+
font_key: str,
|
| 96 |
+
*,
|
| 97 |
+
text_source: str | None = None,
|
| 98 |
+
) -> None:
|
| 99 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 100 |
+
pdf = UnicodePDF()
|
| 101 |
+
pdf.set_auto_page_break(auto=True, margin=14)
|
| 102 |
+
pdf.set_left_margin(14)
|
| 103 |
+
pdf.set_right_margin(14)
|
| 104 |
+
pdf.add_page()
|
| 105 |
+
# Use one font for meta + body when the script is non-Latin: case_id often
|
| 106 |
+
# contains Hangul etc., and NotoSans would miss those glyphs in the header.
|
| 107 |
+
if font_key == "default":
|
| 108 |
+
text_family = pdf_font_setup(pdf, "default")
|
| 109 |
+
else:
|
| 110 |
+
text_family = pdf_font_setup(pdf, font_key)
|
| 111 |
+
pdf.set_font(text_family, size=11)
|
| 112 |
+
head = [f"case_id: {case_id}", f"link: {link}"]
|
| 113 |
+
if text_source:
|
| 114 |
+
head.append(f"Quelle Text: {text_source}")
|
| 115 |
+
head.append("")
|
| 116 |
+
meta = sanitize_pdf_text("\n".join(head))
|
| 117 |
+
# Latin header: WORD wrap; CJK header lines are short — WORD is fine with LEFT.
|
| 118 |
+
pdf.multi_cell(0, 6, meta, align=Align.L, wrapmode=WrapMode.WORD)
|
| 119 |
+
pdf.ln(2)
|
| 120 |
+
pdf.set_font(text_family, size=10)
|
| 121 |
+
text = body if (body and str(body).strip()) else "(kein Volltext in der Quelle)"
|
| 122 |
+
body_txt = sanitize_pdf_text(text)
|
| 123 |
+
if font_key == "default":
|
| 124 |
+
pdf.multi_cell(0, 5, body_txt, align=Align.L, wrapmode=WrapMode.WORD)
|
| 125 |
+
else:
|
| 126 |
+
pdf.multi_cell(0, 5, body_txt, align=Align.L, wrapmode=WrapMode.CHAR)
|
| 127 |
+
pdf.output(str(path))
|
legex/pdf_export/font_keys.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Map workbook location / stem label to body-text font preset."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
# data/<cc>/… — two-letter folder names from legex scrapers
|
| 8 |
+
FONT_BY_CC: dict[str, str] = {
|
| 9 |
+
"kr": "han_k",
|
| 10 |
+
"in": "deva",
|
| 11 |
+
"am": "arm",
|
| 12 |
+
"ge": "geo",
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
# Goldenset_* stem label (ohne Präfix), z. B. aus älteren Drive-Layouts
|
| 16 |
+
FOLDER_FONT_BY_STEM: dict[str, str] = {
|
| 17 |
+
"China": "han_sc",
|
| 18 |
+
"South_Korea": "han_k",
|
| 19 |
+
"Taiwan": "han_tc",
|
| 20 |
+
"Hong_Kong": "han_tc",
|
| 21 |
+
"India": "deva",
|
| 22 |
+
"Armenia": "arm",
|
| 23 |
+
"Georgia": "geo",
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def font_key_for_workbook(xlsx: Path) -> str:
|
| 28 |
+
cc = xlsx.parent.name
|
| 29 |
+
if cc in FONT_BY_CC:
|
| 30 |
+
return FONT_BY_CC[cc]
|
| 31 |
+
stem_label = xlsx.stem.removeprefix("Goldenset_")
|
| 32 |
+
return FOLDER_FONT_BY_STEM.get(stem_label, "default")
|
legex/pdf_export/sheet.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Write PDFs from the ``full_text`` column only (no HTTP)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import openpyxl
|
| 8 |
+
|
| 9 |
+
from legex.pdf_export.core import safe_slug, write_one_pdf
|
| 10 |
+
from legex.pdf_export.font_keys import font_key_for_workbook
|
| 11 |
+
from legex.pdf_export.workbook import cell, header_map
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def export_workbook(
|
| 15 |
+
xlsx: Path,
|
| 16 |
+
out_root: Path,
|
| 17 |
+
*,
|
| 18 |
+
limit: int | None = None,
|
| 19 |
+
) -> int:
|
| 20 |
+
wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True)
|
| 21 |
+
if "GOLDENSET" not in wb.sheetnames:
|
| 22 |
+
wb.close()
|
| 23 |
+
print(f" skip {xlsx.name}: kein Sheet GOLDENSET", flush=True)
|
| 24 |
+
return 0
|
| 25 |
+
ws = wb["GOLDENSET"]
|
| 26 |
+
rows = ws.iter_rows(min_row=1, max_row=ws.max_row, values_only=True)
|
| 27 |
+
header_row = next(rows, None)
|
| 28 |
+
if not header_row:
|
| 29 |
+
wb.close()
|
| 30 |
+
return 0
|
| 31 |
+
h = header_map(header_row)
|
| 32 |
+
idx_case = h.get("case_id")
|
| 33 |
+
idx_link = h.get("link")
|
| 34 |
+
idx_text = h.get("full_text")
|
| 35 |
+
if idx_text is None:
|
| 36 |
+
wb.close()
|
| 37 |
+
print(f" skip {xlsx.name}: keine Spalte 'full_text'", flush=True)
|
| 38 |
+
return 0
|
| 39 |
+
|
| 40 |
+
label = xlsx.parent.name
|
| 41 |
+
out_dir = out_root / label
|
| 42 |
+
font_key = font_key_for_workbook(xlsx)
|
| 43 |
+
|
| 44 |
+
used_names: dict[str, int] = {}
|
| 45 |
+
count = 0
|
| 46 |
+
row_idx = 1
|
| 47 |
+
for row in rows:
|
| 48 |
+
row_idx += 1
|
| 49 |
+
if not row:
|
| 50 |
+
continue
|
| 51 |
+
full = cell(row, idx_text) or ""
|
| 52 |
+
case_id = cell(row, idx_case)
|
| 53 |
+
link_val = cell(row, idx_link) or ""
|
| 54 |
+
if not str(case_id or "").strip() and not link_val.strip() and not full.strip():
|
| 55 |
+
continue
|
| 56 |
+
base = safe_slug(case_id, link_val or None, row_idx)
|
| 57 |
+
used_names[base] = used_names.get(base, 0) + 1
|
| 58 |
+
fname = f"{base}_{used_names[base]}.pdf" if used_names[base] > 1 else f"{base}.pdf"
|
| 59 |
+
write_one_pdf(
|
| 60 |
+
out_dir / fname,
|
| 61 |
+
str(case_id or ""),
|
| 62 |
+
link_val,
|
| 63 |
+
full,
|
| 64 |
+
font_key,
|
| 65 |
+
text_source="full_text (Sheet)",
|
| 66 |
+
)
|
| 67 |
+
count += 1
|
| 68 |
+
if count % 25 == 0:
|
| 69 |
+
print(f" {label}: {count} …", flush=True)
|
| 70 |
+
if limit is not None and count >= limit:
|
| 71 |
+
break
|
| 72 |
+
wb.close()
|
| 73 |
+
print(f" {label}: fertig, {count} PDFs", flush=True)
|
| 74 |
+
return count
|
legex/pdf_export/urls.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fetch document bodies from ``link`` and write PDFs (fallback: ``full_text``)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import io
|
| 6 |
+
import sys
|
| 7 |
+
import time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import openpyxl
|
| 11 |
+
import requests
|
| 12 |
+
from bs4 import BeautifulSoup
|
| 13 |
+
from pypdf import PdfReader
|
| 14 |
+
|
| 15 |
+
from legex.pdf_export.core import safe_slug, write_one_pdf
|
| 16 |
+
from legex.pdf_export.font_keys import font_key_for_workbook
|
| 17 |
+
from legex.pdf_export.workbook import cell, discover_goldensets, header_map
|
| 18 |
+
|
| 19 |
+
UA = "Mozilla/5.0 (compatible; LegexPDFExport/1.0)"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def is_hf_dataset_stub_url(url: str) -> bool:
|
| 23 |
+
u = url.lower()
|
| 24 |
+
return "huggingface.co" in u and "/datasets/" in u
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def effective_timeout(url: str, configured: float) -> float:
|
| 28 |
+
u = url.lower()
|
| 29 |
+
if "hcourt.gov.au" in u:
|
| 30 |
+
return min(configured, 10.0)
|
| 31 |
+
if "openlegaldata.io" in u:
|
| 32 |
+
return min(configured, 12.0)
|
| 33 |
+
return configured
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def fetch_document_text(url: str, timeout: float = 28.0) -> str:
|
| 37 |
+
url = (url or "").strip()
|
| 38 |
+
if not url or not url.startswith("http"):
|
| 39 |
+
return ""
|
| 40 |
+
last_err: str | None = None
|
| 41 |
+
for attempt in range(2):
|
| 42 |
+
try:
|
| 43 |
+
r = requests.get(
|
| 44 |
+
url,
|
| 45 |
+
timeout=timeout,
|
| 46 |
+
headers={"User-Agent": UA, "Accept": "text/html,application/pdf;q=0.9,*/*;q=0.8"},
|
| 47 |
+
allow_redirects=True,
|
| 48 |
+
)
|
| 49 |
+
r.raise_for_status()
|
| 50 |
+
data = r.content
|
| 51 |
+
if len(data) >= 4 and data[:4] == b"%PDF":
|
| 52 |
+
reader = PdfReader(io.BytesIO(data))
|
| 53 |
+
return "\n\n".join((p.extract_text() or "") for p in reader.pages)
|
| 54 |
+
enc = r.encoding or "utf-8"
|
| 55 |
+
try:
|
| 56 |
+
html = data.decode(enc, errors="replace")
|
| 57 |
+
except LookupError:
|
| 58 |
+
html = data.decode("utf-8", errors="replace")
|
| 59 |
+
soup = BeautifulSoup(html, "lxml")
|
| 60 |
+
for tag in soup(["script", "style", "noscript"]):
|
| 61 |
+
tag.decompose()
|
| 62 |
+
text = soup.get_text("\n")
|
| 63 |
+
lines = [ln.strip() for ln in text.splitlines()]
|
| 64 |
+
return "\n".join(ln for ln in lines if ln)
|
| 65 |
+
except Exception as e:
|
| 66 |
+
last_err = str(e)
|
| 67 |
+
if attempt < 1:
|
| 68 |
+
time.sleep(1.2 * (attempt + 1))
|
| 69 |
+
if last_err:
|
| 70 |
+
return f"[Abruf fehlgeschlagen: {last_err}]\n"
|
| 71 |
+
return ""
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def pick_body(
|
| 75 |
+
link_val: str,
|
| 76 |
+
sheet_full: str | None,
|
| 77 |
+
pause_s: float,
|
| 78 |
+
req_timeout: float,
|
| 79 |
+
) -> tuple[str, str]:
|
| 80 |
+
time.sleep(pause_s)
|
| 81 |
+
link_val = (link_val or "").strip()
|
| 82 |
+
sheet = (sheet_full or "").strip()
|
| 83 |
+
|
| 84 |
+
if link_val and is_hf_dataset_stub_url(link_val):
|
| 85 |
+
if sheet:
|
| 86 |
+
return sheet, "full_text (HF-Dataset-Link)"
|
| 87 |
+
return "(kein Volltext in der Zeile trotz HF-Link)", "leer"
|
| 88 |
+
|
| 89 |
+
fetched = (
|
| 90 |
+
fetch_document_text(link_val, timeout=effective_timeout(link_val, req_timeout))
|
| 91 |
+
if link_val
|
| 92 |
+
else ""
|
| 93 |
+
)
|
| 94 |
+
if fetched and not fetched.startswith("[Abruf fehlgeschlagen"):
|
| 95 |
+
return fetched.strip(), "URL"
|
| 96 |
+
if sheet:
|
| 97 |
+
return sheet, "full_text (Fallback)"
|
| 98 |
+
if fetched:
|
| 99 |
+
return fetched.strip(), "URL (Fehlermeldung)"
|
| 100 |
+
return "(kein Volltext — weder URL noch Tabellenfeld)", "leer"
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def export_workbook(
|
| 104 |
+
xlsx: Path,
|
| 105 |
+
out_root: Path,
|
| 106 |
+
*,
|
| 107 |
+
pause_s: float,
|
| 108 |
+
limit: int | None,
|
| 109 |
+
req_timeout: float,
|
| 110 |
+
resume: bool,
|
| 111 |
+
) -> int:
|
| 112 |
+
label = xlsx.parent.name
|
| 113 |
+
out_dir = out_root / label
|
| 114 |
+
font_key = font_key_for_workbook(xlsx)
|
| 115 |
+
|
| 116 |
+
wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True)
|
| 117 |
+
if "GOLDENSET" not in wb.sheetnames:
|
| 118 |
+
wb.close()
|
| 119 |
+
print(f" skip {xlsx.name}: kein Sheet GOLDENSET", flush=True)
|
| 120 |
+
return 0
|
| 121 |
+
ws = wb["GOLDENSET"]
|
| 122 |
+
rows = ws.iter_rows(min_row=1, max_row=ws.max_row, values_only=True)
|
| 123 |
+
header_row = next(rows, None)
|
| 124 |
+
if not header_row:
|
| 125 |
+
wb.close()
|
| 126 |
+
return 0
|
| 127 |
+
h = header_map(header_row)
|
| 128 |
+
idx_case = h.get("case_id")
|
| 129 |
+
idx_link = h.get("link")
|
| 130 |
+
idx_text = h.get("full_text")
|
| 131 |
+
if idx_link is None:
|
| 132 |
+
wb.close()
|
| 133 |
+
print(f" skip {xlsx.name}: keine Spalte 'link'", flush=True)
|
| 134 |
+
return 0
|
| 135 |
+
|
| 136 |
+
used_names: dict[str, int] = {}
|
| 137 |
+
count = 0
|
| 138 |
+
row_idx = 1
|
| 139 |
+
for row in rows:
|
| 140 |
+
row_idx += 1
|
| 141 |
+
if not row:
|
| 142 |
+
continue
|
| 143 |
+
link_val = cell(row, idx_link) or ""
|
| 144 |
+
case_id = cell(row, idx_case)
|
| 145 |
+
sheet_full = cell(row, idx_text) if idx_text is not None else None
|
| 146 |
+
if (
|
| 147 |
+
not str(case_id or "").strip()
|
| 148 |
+
and not link_val.strip()
|
| 149 |
+
and not (sheet_full or "").strip()
|
| 150 |
+
):
|
| 151 |
+
continue
|
| 152 |
+
base = safe_slug(case_id, link_val or None, row_idx)
|
| 153 |
+
used_names[base] = used_names.get(base, 0) + 1
|
| 154 |
+
fname = f"{base}_{used_names[base]}.pdf" if used_names[base] > 1 else f"{base}.pdf"
|
| 155 |
+
out_path = out_dir / fname
|
| 156 |
+
if resume and out_path.exists() and out_path.stat().st_size > 80:
|
| 157 |
+
count += 1
|
| 158 |
+
if count % 25 == 0:
|
| 159 |
+
print(f" {label}: {count} (Bestand übersprungen) …", flush=True)
|
| 160 |
+
if limit is not None and count >= limit:
|
| 161 |
+
break
|
| 162 |
+
continue
|
| 163 |
+
|
| 164 |
+
body, prov = pick_body(link_val, sheet_full, pause_s, req_timeout)
|
| 165 |
+
write_one_pdf(out_path, str(case_id or ""), link_val, body, font_key, text_source=prov)
|
| 166 |
+
count += 1
|
| 167 |
+
if count % 10 == 0:
|
| 168 |
+
print(f" {label}: {count} …", flush=True)
|
| 169 |
+
if limit is not None and count >= limit:
|
| 170 |
+
break
|
| 171 |
+
wb.close()
|
| 172 |
+
print(f" {label}: fertig, {count} PDFs", flush=True)
|
| 173 |
+
return count
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def collect_workbooks(data_dir: Path, input_dirs: list[Path] | None) -> list[Path]:
|
| 177 |
+
if input_dirs:
|
| 178 |
+
files: list[Path] = []
|
| 179 |
+
for d in input_dirs:
|
| 180 |
+
if not d.is_dir():
|
| 181 |
+
print("Ordner fehlt:", d, file=sys.stderr)
|
| 182 |
+
continue
|
| 183 |
+
files.extend(sorted(d.glob("Goldenset_*.xlsx")))
|
| 184 |
+
return sorted(files, key=lambda p: (p.stem.lower(), str(p)))
|
| 185 |
+
return discover_goldensets(data_dir)
|
legex/pdf_export/workbook.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Goldenset workbook helpers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def discover_goldensets(data_dir: Path) -> list[Path]:
|
| 9 |
+
"""Workbooks under ``data/<anything>/Goldenset_*.xlsx``."""
|
| 10 |
+
return sorted(data_dir.glob("*/Goldenset_*.xlsx"))
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def header_map(header_row: tuple) -> dict[str, int]:
|
| 14 |
+
m: dict[str, int] = {}
|
| 15 |
+
for i, h in enumerate(header_row):
|
| 16 |
+
if h is None:
|
| 17 |
+
continue
|
| 18 |
+
m[str(h).strip().lower()] = i
|
| 19 |
+
return m
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def cell(row: tuple, idx: int | None) -> str | None:
|
| 23 |
+
if idx is None:
|
| 24 |
+
return None
|
| 25 |
+
if idx < 0 or idx >= len(row):
|
| 26 |
+
return None
|
| 27 |
+
v = row[idx]
|
| 28 |
+
if v is None:
|
| 29 |
+
return None
|
| 30 |
+
return str(v)
|
legex/plots.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Paper-ready figures from `data/analysis/*.csv`.
|
| 2 |
+
|
| 3 |
+
Reads the CSVs that `legex.analysis` emits and writes four PNGs into
|
| 4 |
+
``data/analysis/figures/``:
|
| 5 |
+
|
| 6 |
+
- ``hallucination_by_country.png`` — grouped bar, models side-by-side.
|
| 7 |
+
- ``recall_by_country.png`` — grouped bar, models side-by-side.
|
| 8 |
+
- ``per_variable_heatmap.png`` — variable × {accuracy, recall, hallu., F1}, one panel per model.
|
| 9 |
+
- ``hallu_vs_recall.png`` — scatter on the cost block, one marker per (cc, model).
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import csv
|
| 14 |
+
import logging
|
| 15 |
+
import sys
|
| 16 |
+
from collections import defaultdict
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import matplotlib.pyplot as plt
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
log = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _read_csv(path: Path) -> list[dict[str, str]]:
|
| 26 |
+
with open(path, encoding="utf-8", newline="") as f:
|
| 27 |
+
return list(csv.DictReader(f))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _models_in(rows: list[dict[str, str]]) -> list[str]:
|
| 31 |
+
return sorted({r["model"] for r in rows})
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _short_model(m: str) -> str:
|
| 35 |
+
return m.split("/")[-1]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _grouped_bar(
|
| 39 |
+
rows: list[dict[str, str]], metric: str, title: str, ylabel: str, out: Path,
|
| 40 |
+
) -> None:
|
| 41 |
+
"""Grouped-bar chart: one bar per (country, model) pair."""
|
| 42 |
+
countries = sorted({r["country"] for r in rows})
|
| 43 |
+
models = _models_in(rows)
|
| 44 |
+
values: dict[str, dict[str, float]] = defaultdict(dict)
|
| 45 |
+
for r in rows:
|
| 46 |
+
values[r["country"]][r["model"]] = float(r[metric])
|
| 47 |
+
|
| 48 |
+
x = np.arange(len(countries))
|
| 49 |
+
width = 0.8 / max(1, len(models))
|
| 50 |
+
fig, ax = plt.subplots(figsize=(max(10, 0.55 * len(countries)), 4.5))
|
| 51 |
+
for i, model in enumerate(models):
|
| 52 |
+
ys = [values[cc].get(model, np.nan) * 100 for cc in countries]
|
| 53 |
+
ax.bar(x + (i - (len(models) - 1) / 2) * width, ys, width, label=_short_model(model))
|
| 54 |
+
ax.set_xticks(x)
|
| 55 |
+
ax.set_xticklabels([cc.upper() for cc in countries], rotation=45, ha="right")
|
| 56 |
+
ax.set_ylabel(ylabel)
|
| 57 |
+
ax.set_title(title)
|
| 58 |
+
ax.set_ylim(0, 100)
|
| 59 |
+
ax.grid(axis="y", alpha=0.3)
|
| 60 |
+
ax.legend(frameon=False)
|
| 61 |
+
fig.tight_layout()
|
| 62 |
+
fig.savefig(out, dpi=150)
|
| 63 |
+
plt.close(fig)
|
| 64 |
+
log.info(f"wrote {out}")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _heatmap(
|
| 68 |
+
rows: list[dict[str, str]], out: Path,
|
| 69 |
+
) -> None:
|
| 70 |
+
"""Variable × {accuracy, recall_when_filled, hallucination_rate, f1} for each model."""
|
| 71 |
+
metrics = [
|
| 72 |
+
("accuracy", "Accuracy"),
|
| 73 |
+
("recall_when_filled", "Recall$_{filled}$"),
|
| 74 |
+
("hallucination_rate", "Hallu. rate"),
|
| 75 |
+
("f1", "F1"),
|
| 76 |
+
]
|
| 77 |
+
models = _models_in(rows)
|
| 78 |
+
columns = sorted({r["column"] for r in rows})
|
| 79 |
+
|
| 80 |
+
fig, axes = plt.subplots(1, len(models), figsize=(5 * len(models), max(5, 0.32 * len(columns))))
|
| 81 |
+
if len(models) == 1:
|
| 82 |
+
axes = [axes]
|
| 83 |
+
for ax, model in zip(axes, models):
|
| 84 |
+
grid = np.full((len(columns), len(metrics)), np.nan)
|
| 85 |
+
for r in rows:
|
| 86 |
+
if r["model"] != model:
|
| 87 |
+
continue
|
| 88 |
+
i = columns.index(r["column"])
|
| 89 |
+
for j, (key, _label) in enumerate(metrics):
|
| 90 |
+
grid[i, j] = float(r[key])
|
| 91 |
+
im = ax.imshow(grid, aspect="auto", cmap="RdYlGn", vmin=0, vmax=1)
|
| 92 |
+
ax.set_xticks(range(len(metrics)))
|
| 93 |
+
ax.set_xticklabels([m[1] for m in metrics], rotation=30, ha="right")
|
| 94 |
+
ax.set_yticks(range(len(columns)))
|
| 95 |
+
ax.set_yticklabels(columns, fontsize=8)
|
| 96 |
+
ax.set_title(_short_model(model), fontsize=10)
|
| 97 |
+
for i in range(len(columns)):
|
| 98 |
+
for j in range(len(metrics)):
|
| 99 |
+
v = grid[i, j]
|
| 100 |
+
if not np.isnan(v):
|
| 101 |
+
ax.text(j, i, f"{v:.2f}", ha="center", va="center", fontsize=7,
|
| 102 |
+
color="black" if 0.25 < v < 0.75 else "white")
|
| 103 |
+
fig.colorbar(im, ax=axes, shrink=0.8, label="value")
|
| 104 |
+
fig.suptitle("Per-variable metrics (summed across jurisdictions)")
|
| 105 |
+
fig.savefig(out, dpi=150, bbox_inches="tight")
|
| 106 |
+
plt.close(fig)
|
| 107 |
+
log.info(f"wrote {out}")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _scatter(rows: list[dict[str, str]], out: Path) -> None:
|
| 111 |
+
"""Hallucination vs recall on the cost block. One marker per (cc, model)."""
|
| 112 |
+
models = _models_in(rows)
|
| 113 |
+
markers = {models[0]: "o"} if len(models) == 1 else {models[0]: "o", models[1]: "s"}
|
| 114 |
+
colors = plt.cm.tab20.colors
|
| 115 |
+
|
| 116 |
+
fig, ax = plt.subplots(figsize=(7, 6))
|
| 117 |
+
for r in rows:
|
| 118 |
+
m = r["model"]
|
| 119 |
+
x = float(r["cost_hallucination_rate"]) * 100
|
| 120 |
+
y = float(r["cost_recall_when_filled"]) * 100
|
| 121 |
+
cc = r["country"]
|
| 122 |
+
c = colors[hash(cc) % len(colors)]
|
| 123 |
+
ax.scatter(x, y, marker=markers.get(m, "o"), color=c, s=70, alpha=0.85, edgecolor="black", linewidth=0.4)
|
| 124 |
+
ax.annotate(cc.upper(), (x, y), fontsize=7, xytext=(3, 3), textcoords="offset points")
|
| 125 |
+
ax.set_xlabel("Cost-block hallucination rate (%)")
|
| 126 |
+
ax.set_ylabel("Cost-block recall when filled (%)")
|
| 127 |
+
ax.set_title("Cost extraction: recall vs hallucination, by jurisdiction × model")
|
| 128 |
+
ax.set_xlim(-2, 100)
|
| 129 |
+
ax.set_ylim(-2, 100)
|
| 130 |
+
ax.grid(alpha=0.3)
|
| 131 |
+
handles = [
|
| 132 |
+
plt.Line2D([], [], marker=mk, linestyle="", color="grey", label=_short_model(m))
|
| 133 |
+
for m, mk in markers.items()
|
| 134 |
+
]
|
| 135 |
+
ax.legend(handles=handles, frameon=False, loc="lower right")
|
| 136 |
+
fig.tight_layout()
|
| 137 |
+
fig.savefig(out, dpi=150)
|
| 138 |
+
plt.close(fig)
|
| 139 |
+
log.info(f"wrote {out}")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def make_all(analysis_dir: Path, out_dir: Path) -> None:
|
| 143 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 144 |
+
per_country = _read_csv(analysis_dir / "per_country.csv")
|
| 145 |
+
per_column = _read_csv(analysis_dir / "per_column.csv")
|
| 146 |
+
|
| 147 |
+
_grouped_bar(
|
| 148 |
+
per_country, "hallucination_rate",
|
| 149 |
+
"Hallucination rate by jurisdiction (cells where the expert recorded nothing)",
|
| 150 |
+
"Hallucination rate (%)",
|
| 151 |
+
out_dir / "hallucination_by_country.png",
|
| 152 |
+
)
|
| 153 |
+
_grouped_bar(
|
| 154 |
+
per_country, "recall_when_filled",
|
| 155 |
+
"Accuracy when the expert recorded a value",
|
| 156 |
+
"Accuracy (%)",
|
| 157 |
+
out_dir / "recall_by_country.png",
|
| 158 |
+
)
|
| 159 |
+
_heatmap(per_column, out_dir / "per_variable_heatmap.png")
|
| 160 |
+
_scatter(per_country, out_dir / "hallu_vs_recall.png")
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def main() -> None:
|
| 164 |
+
logging.basicConfig(
|
| 165 |
+
level=logging.INFO,
|
| 166 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 167 |
+
handlers=[logging.StreamHandler(sys.stderr)],
|
| 168 |
+
)
|
| 169 |
+
parser = argparse.ArgumentParser(
|
| 170 |
+
prog="legex-plots",
|
| 171 |
+
description="Render paper-ready figures from data/analysis/*.csv.",
|
| 172 |
+
)
|
| 173 |
+
parser.add_argument("--in", dest="in_dir", type=Path, default=Path("data/analysis"))
|
| 174 |
+
parser.add_argument("--out", dest="out_dir", type=Path, default=Path("data/analysis/figures"))
|
| 175 |
+
args = parser.parse_args()
|
| 176 |
+
make_all(args.in_dir, args.out_dir)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
main()
|
legex/processing.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import zipfile
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from legex.config import settings
|
| 6 |
+
from legex.scrapers import SCRAPERS
|
| 7 |
+
from legex.utils import (
|
| 8 |
+
filtered_path,
|
| 9 |
+
goldenset_path,
|
| 10 |
+
random_sample,
|
| 11 |
+
raw_path,
|
| 12 |
+
read_jsonl,
|
| 13 |
+
sampled_path,
|
| 14 |
+
write_goldenset_xlsx,
|
| 15 |
+
write_jsonl,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
log = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def scrape(force: bool = False) -> None:
|
| 22 |
+
for cc, cls in SCRAPERS.items():
|
| 23 |
+
out = raw_path(cc)
|
| 24 |
+
if out.exists() and not force:
|
| 25 |
+
log.info(f"[{cc}] {out} exists, skipping")
|
| 26 |
+
continue
|
| 27 |
+
try:
|
| 28 |
+
cases = cls().scrape(settings.date_start, settings.date_end)
|
| 29 |
+
except Exception as e:
|
| 30 |
+
log.warning(f"[{cc}] scrape failed ({e}), skipping")
|
| 31 |
+
continue
|
| 32 |
+
write_jsonl(cases, out)
|
| 33 |
+
log.info(f"[{cc}] {len(cases)} → {out}")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def filter_and_sample(force: bool = False) -> None:
|
| 37 |
+
for cc, cls in SCRAPERS.items():
|
| 38 |
+
sampled = sampled_path(cc)
|
| 39 |
+
if sampled.exists() and not force:
|
| 40 |
+
log.info(f"[{cc}] {sampled} exists, skipping")
|
| 41 |
+
continue
|
| 42 |
+
raw = raw_path(cc)
|
| 43 |
+
if not raw.exists():
|
| 44 |
+
log.warning(f"[{cc}] missing {raw}, skipping")
|
| 45 |
+
continue
|
| 46 |
+
|
| 47 |
+
cases = read_jsonl(raw)
|
| 48 |
+
filtered = cls.civil_filter(cases)
|
| 49 |
+
write_jsonl(filtered, filtered_path(cc))
|
| 50 |
+
log.info(f"[{cc}] filtered {len(cases)} → {len(filtered)}")
|
| 51 |
+
|
| 52 |
+
sample = random_sample(filtered, settings.sample_n, settings.sample_seed)
|
| 53 |
+
write_jsonl(sample, sampled)
|
| 54 |
+
log.info(f"[{cc}] sampled {len(sample)} → {sampled}")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def fill_goldenset() -> None:
|
| 58 |
+
for cc, cls in SCRAPERS.items():
|
| 59 |
+
out = goldenset_path(cc)
|
| 60 |
+
if out.exists() and not force:
|
| 61 |
+
log.info(f"[{cc}] {out} exists, skipping")
|
| 62 |
+
continue
|
| 63 |
+
sampled = sampled_path(cc)
|
| 64 |
+
if not sampled.exists():
|
| 65 |
+
log.warning(f"[{cc}] missing {sampled}, skipping")
|
| 66 |
+
continue
|
| 67 |
+
cases = read_jsonl(sampled)
|
| 68 |
+
enriched = cls.enrich(cases)
|
| 69 |
+
if any(e.full_text != c.full_text for e, c in zip(enriched, cases)):
|
| 70 |
+
write_jsonl(enriched, sampled)
|
| 71 |
+
log.info(f"[{cc}] enriched {len(enriched)} cases → {sampled}")
|
| 72 |
+
write_goldenset_xlsx(enriched, settings.template, out)
|
| 73 |
+
log.info(f"[{cc}] → {out}")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def dist(force: bool = False) -> None:
|
| 77 |
+
settings.dist_dir.mkdir(parents=True, exist_ok=True)
|
| 78 |
+
produced: list[Path] = []
|
| 79 |
+
for cc in SCRAPERS:
|
| 80 |
+
xlsx = goldenset_path(cc)
|
| 81 |
+
zip_path = settings.dist_dir / f"{cc}.zip"
|
| 82 |
+
if zip_path.exists() and not force:
|
| 83 |
+
log.info(f"[{cc}] {zip_path} exists, skipping")
|
| 84 |
+
produced.append(zip_path)
|
| 85 |
+
continue
|
| 86 |
+
if not xlsx.exists():
|
| 87 |
+
log.warning(f"[{cc}] missing {xlsx}, skipping")
|
| 88 |
+
continue
|
| 89 |
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
| 90 |
+
zf.write(xlsx, arcname=xlsx.name)
|
| 91 |
+
log.info(f"[{cc}] → {zip_path}")
|
| 92 |
+
produced.append(zip_path)
|
| 93 |
+
|
| 94 |
+
if produced:
|
| 95 |
+
log.info(f"Upload to {settings.drive_folder_url}:")
|
| 96 |
+
for p in produced:
|
| 97 |
+
log.info(f" {p}")
|
legex/prompts/__init__.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned system prompts for `legex-classify`.
|
| 2 |
+
|
| 3 |
+
Each version lives in `legex/prompts/{version}.py` and exposes one of:
|
| 4 |
+
|
| 5 |
+
# single-call mode (one LLM call per case)
|
| 6 |
+
PROMPT: str — template with {rules_block}/{isic_block}
|
| 7 |
+
build(rules, isic) -> str — returns the filled prompt
|
| 8 |
+
|
| 9 |
+
# per-column mode (one LLM call per Classification field per case)
|
| 10 |
+
MODE = "per_column"
|
| 11 |
+
build_columns(rules, isic) -> dict[column_name, system_prompt]
|
| 12 |
+
|
| 13 |
+
`load_plan(...)` normalises both shapes into a `PromptPlan`.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from importlib import import_module
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class PromptPlan:
|
| 22 |
+
mode: str # "single" or "per_column"
|
| 23 |
+
system: str | None = None
|
| 24 |
+
column_systems: dict[str, str] | None = None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def load_plan(
|
| 28 |
+
version: str,
|
| 29 |
+
rules: list[tuple[str, str]],
|
| 30 |
+
isic: list[tuple[str, str, str]],
|
| 31 |
+
) -> PromptPlan:
|
| 32 |
+
try:
|
| 33 |
+
mod = import_module(f"legex.prompts.{version}")
|
| 34 |
+
except ImportError as e:
|
| 35 |
+
raise ValueError(f"Unknown prompt version: {version!r}") from e
|
| 36 |
+
mode = getattr(mod, "MODE", "single")
|
| 37 |
+
if mode == "per_column":
|
| 38 |
+
return PromptPlan(mode="per_column", column_systems=mod.build_columns(rules, isic))
|
| 39 |
+
return PromptPlan(mode="single", system=mod.build(rules, isic))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def build_prompt(
|
| 43 |
+
version: str,
|
| 44 |
+
rules: list[tuple[str, str]],
|
| 45 |
+
isic: list[tuple[str, str, str]],
|
| 46 |
+
) -> str:
|
| 47 |
+
"""Single-mode shortcut. Raises if the version is per-column."""
|
| 48 |
+
plan = load_plan(version, rules, isic)
|
| 49 |
+
if plan.mode != "single" or plan.system is None:
|
| 50 |
+
raise ValueError(
|
| 51 |
+
f"build_prompt() is single-mode only; prompt version {version!r} is {plan.mode}"
|
| 52 |
+
)
|
| 53 |
+
return plan.system
|
legex/prompts/v1.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""System prompt v1 for legal-case structured extraction."""
|
| 2 |
+
|
| 3 |
+
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.
|
| 4 |
+
|
| 5 |
+
Use native JSON types — a number is a number, not a string:
|
| 6 |
+
- 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.
|
| 7 |
+
- plaintiff_loosing_share: JSON number between 0 and 1, e.g. 0.6.
|
| 8 |
+
- *_count variables: JSON integer, e.g. 2.
|
| 9 |
+
- Date variables: JSON string in YYYY-MM-DD format, e.g. "2022-07-15".
|
| 10 |
+
- All other text fields (legal_subject_judgement, currencies, ISIC categories): JSON string.
|
| 11 |
+
|
| 12 |
+
## Variable coding rules
|
| 13 |
+
|
| 14 |
+
{rules_block}
|
| 15 |
+
|
| 16 |
+
## Allowed ISIC industry categories (for *_industry_category variables)
|
| 17 |
+
|
| 18 |
+
{isic_block}
|
| 19 |
+
|
| 20 |
+
## Currency variables
|
| 21 |
+
|
| 22 |
+
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."""
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def build(
|
| 26 |
+
rules: list[tuple[str, str]],
|
| 27 |
+
isic: list[tuple[str, str, str]],
|
| 28 |
+
) -> str:
|
| 29 |
+
rules_block = "\n\n".join(f"### {name}\n{explanation}" for name, explanation in rules)
|
| 30 |
+
isic_block = "\n".join(
|
| 31 |
+
f"- {coded_value} — {category}: {description}"
|
| 32 |
+
for coded_value, category, description in isic
|
| 33 |
+
)
|
| 34 |
+
return PROMPT.format(rules_block=rules_block, isic_block=isic_block)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# 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.
|
| 38 |
+
# 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.
|
| 39 |
+
# 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.
|
| 40 |
+
# 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.
|
| 41 |
+
# 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.
|
| 42 |
+
# 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.
|
| 43 |
+
# 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.
|
| 44 |
+
# 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.
|
| 45 |
+
# 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.
|
| 46 |
+
# 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.
|
| 47 |
+
# 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).
|
| 48 |
+
|
| 49 |
+
# Step-by-step:
|
| 50 |
+
# (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),
|
| 51 |
+
# (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'.
|
| 52 |
+
# (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).'
|
| 53 |
+
# (4) If the judgements contains no information at all about the plaintiff's economic activity, enter the literal 'None'.
|
| 54 |
+
# ISIC Categories:
|
| 55 |
+
# • 'a_agriculture_forestry_fishing': Agriculture, forestry and fishing
|
| 56 |
+
# • 'b_mining_quarrying': Mining and quarrying
|
| 57 |
+
# • 'c_manufacturing': Manufacturing
|
| 58 |
+
# • 'd_electricity_gas_steam_ac': Electricity, gas, steam and air conditioning supply
|
| 59 |
+
# • 'e_water_sewerage_waste_remediation': Water supply; sewerage, waste management and remediation
|
| 60 |
+
# • 'f_construction': Construction
|
| 61 |
+
# • 'g_wholesale_retail_trade': Wholesale and retail trade; repair of motor vehicles
|
| 62 |
+
# • 'h_transportation_storage': Transportation and storage
|
| 63 |
+
# • 'i_accommodation_food_service': Accommodation and food service activities
|
| 64 |
+
# • 'j_publishing_broadcasting_content': Publishing, broadcasting and content production
|
| 65 |
+
# • 'k_telecom_it_info_services': Telecommunications, IT and other information services
|
| 66 |
+
# • 'l_financial_insurance': Financial and insurance activities
|
| 67 |
+
# • 'm_real_estate': Real estate activities
|
| 68 |
+
# • 'n_professional_scientific_technical': Professional, scientific and technical activities
|
| 69 |
+
# • 'o_administrative_support': Administrative and support service activities
|
| 70 |
+
# • 'p_public_admin_defence': Public administration and defence; compulsory social security
|
| 71 |
+
# • 'q_education': Education
|
| 72 |
+
# • 'r_human_health_social_work': Human health and social work activities
|
| 73 |
+
# • 's_arts_entertainment_recreation': Arts, entertainment and recreation
|
| 74 |
+
# • 't_other_service_activities': Other service activities
|
| 75 |
+
# • 'u_households_as_employers': Activities of households as employers
|
| 76 |
+
# • 'v_extraterritorial_organisations': Activities of extraterritorial organisations and bodies
|
| 77 |
+
# Fallbacks:
|
| 78 |
+
# • 'no_allocation_possible'
|
| 79 |
+
# • 'None'"
|
| 80 |
+
# 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).
|
| 81 |
+
|
| 82 |
+
# Step-by-step:
|
| 83 |
+
# (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),
|
| 84 |
+
# (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'.
|
| 85 |
+
# (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).'
|
| 86 |
+
# (4) If the judgements contains no information at all about the defendant 's economic activity, enter the literal 'None'.
|
| 87 |
+
# ISIC Categories:
|
| 88 |
+
# • 'a_agriculture_forestry_fishing': Agriculture, forestry and fishing
|
| 89 |
+
# • 'b_mining_quarrying': Mining and quarrying
|
| 90 |
+
# • 'c_manufacturing': Manufacturing
|
| 91 |
+
# • 'd_electricity_gas_steam_ac': Electricity, gas, steam and air conditioning supply
|
| 92 |
+
# • 'e_water_sewerage_waste_remediation': Water supply; sewerage, waste management and remediation
|
| 93 |
+
# • 'f_construction': Construction
|
| 94 |
+
# • 'g_wholesale_retail_trade': Wholesale and retail trade; repair of motor vehicles
|
| 95 |
+
# • 'h_transportation_storage': Transportation and storage
|
| 96 |
+
# • 'i_accommodation_food_service': Accommodation and food service activities
|
| 97 |
+
# • 'j_publishing_broadcasting_content': Publishing, broadcasting and content production
|
| 98 |
+
# • 'k_telecom_it_info_services': Telecommunications, IT and other information services
|
| 99 |
+
# • 'l_financial_insurance': Financial and insurance activities
|
| 100 |
+
# • 'm_real_estate': Real estate activities
|
| 101 |
+
# • 'n_professional_scientific_technical': Professional, scientific and technical activities
|
| 102 |
+
# • 'o_administrative_support': Administrative and support service activities
|
| 103 |
+
# • 'p_public_admin_defence': Public administration and defence; compulsory social security
|
| 104 |
+
# • 'q_education': Education
|
| 105 |
+
# • 'r_human_health_social_work': Human health and social work activities
|
| 106 |
+
# • 's_arts_entertainment_recreation': Arts, entertainment and recreation
|
| 107 |
+
# • 't_other_service_activities': Other service activities
|
| 108 |
+
# • 'u_households_as_employers': Activities of households as employers
|
| 109 |
+
# • 'v_extraterritorial_organisations': Activities of extraterritorial organisations and bodies
|
| 110 |
+
# Fallbacks:
|
| 111 |
+
# • 'no_allocation_possible'
|
| 112 |
+
# • 'None'"
|
| 113 |
+
|
legex/prompts/v2.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-column system prompts: one focused LLM call per Classification field.
|
| 2 |
+
|
| 3 |
+
Each prompt is built from the column's coding rule (Vorlage
|
| 4 |
+
`Variables_Coding_Rules` sheet) plus the small targeted instructions it
|
| 5 |
+
needs (ISIC list for industry fields, currency hint for the `currency_*`
|
| 6 |
+
fields, the "nonpecuniary" exception for `dispute_value_nominal`).
|
| 7 |
+
|
| 8 |
+
The LLM is told to return JSON `{"<column>": <value>}` so the response
|
| 9 |
+
can be validated by the same `Classification` model used in v1 — we just
|
| 10 |
+
look at the one field we asked for.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from legex.models.classification import Classification
|
| 14 |
+
|
| 15 |
+
MODE = "per_column"
|
| 16 |
+
|
| 17 |
+
_PREAMBLE = (
|
| 18 |
+
"You extract a single variable from a court judgment. Read the "
|
| 19 |
+
"judgment text the user provides and return a JSON object with "
|
| 20 |
+
"exactly one key: the variable name below. The value must be the "
|
| 21 |
+
"typed answer or JSON null. Do not invent information that is not "
|
| 22 |
+
"in the text. Use native JSON types — a number is a number, not a "
|
| 23 |
+
"string. Money amounts are JSON numbers; dates are JSON strings in "
|
| 24 |
+
"YYYY-MM-DD format; counts are JSON integers."
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
_DISPUTE_TAIL = 'The value may also be the literal string "nonpecuniary" for non-monetary disputes.'
|
| 28 |
+
|
| 29 |
+
_ISIC_TAIL = (
|
| 30 |
+
"The value must be one of the coded values listed below.\n\n"
|
| 31 |
+
"## Allowed ISIC industry categories\n\n{isic_block}"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
_CURRENCY_TAIL = (
|
| 35 |
+
"Return the ISO-4217 currency code of the local currency of the "
|
| 36 |
+
"proceedings (e.g. CHF for Switzerland, EUR for France/Germany/"
|
| 37 |
+
"Belgium, GBP for the UK, AUD for Australia, NZD for New Zealand). "
|
| 38 |
+
"Return null if the corresponding amount in the judgment is null."
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
_ISIC_COLUMNS = {
|
| 42 |
+
"plaintiff_no1_ISIC1_industry_category",
|
| 43 |
+
"defendant_no1_ISIC1_industry_category",
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
_CURRENCY_COLUMNS = {
|
| 47 |
+
"Currency_dispute_value_nominal",
|
| 48 |
+
"Currency_court_cost_awarded_nominal",
|
| 49 |
+
"Currency_party_compensation_awarded_nominal",
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def build_columns(
|
| 54 |
+
rules: list[tuple[str, str]],
|
| 55 |
+
isic: list[tuple[str, str, str]],
|
| 56 |
+
) -> dict[str, str]:
|
| 57 |
+
"""Returns {csv_column_name: system_prompt}.
|
| 58 |
+
|
| 59 |
+
Keys use the field's alias when set (e.g. `Currency_*` capital C) so
|
| 60 |
+
they line up with the GOLDENSET header. Python attribute names stay
|
| 61 |
+
lowercase on the `Classification` model.
|
| 62 |
+
"""
|
| 63 |
+
rules_by_name = {name: explanation for name, explanation in rules}
|
| 64 |
+
isic_block = "\n".join(
|
| 65 |
+
f"- {coded_value} — {category}: {description}"
|
| 66 |
+
for coded_value, category, description in isic
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
out: dict[str, str] = {}
|
| 70 |
+
for field, info in Classification.model_fields.items():
|
| 71 |
+
col = info.alias or field
|
| 72 |
+
rule = rules_by_name.get(col) or rules_by_name.get(field, "")
|
| 73 |
+
body = (
|
| 74 |
+
f"{_PREAMBLE}\n\n"
|
| 75 |
+
f"## Variable: {col}\n\n"
|
| 76 |
+
f"{rule}\n\n"
|
| 77 |
+
f'Return JSON in the form: {{"{col}": <value>}}'
|
| 78 |
+
)
|
| 79 |
+
if col == "dispute_value_nominal":
|
| 80 |
+
body += f"\n\n{_DISPUTE_TAIL}"
|
| 81 |
+
if col in _ISIC_COLUMNS:
|
| 82 |
+
body += "\n\n" + _ISIC_TAIL.format(isic_block=isic_block)
|
| 83 |
+
if col in _CURRENCY_COLUMNS:
|
| 84 |
+
body += f"\n\n{_CURRENCY_TAIL}"
|
| 85 |
+
out[col] = body
|
| 86 |
+
return out
|
legex/prompts/v3.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""System prompt v3 for legal-case structured extraction.
|
| 2 |
+
"""
|
| 3 |
+
|
| 4 |
+
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.
|
| 5 |
+
|
| 6 |
+
Use native JSON types — a number is a number, not a string:
|
| 7 |
+
- 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.
|
| 8 |
+
- plaintiff_loosing_share: JSON number between 0 and 1, e.g. 0.6.
|
| 9 |
+
- *_count variables: JSON integer, e.g. 2.
|
| 10 |
+
- Date variables: JSON string in YYYY-MM-DD format, e.g. "2022-07-15".
|
| 11 |
+
- All other text fields (legal_subject_judgement, currencies, ISIC categories): JSON string.
|
| 12 |
+
|
| 13 |
+
## Variable coding rules
|
| 14 |
+
|
| 15 |
+
### case_id
|
| 16 |
+
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.
|
| 17 |
+
|
| 18 |
+
### legal_subject_judgement
|
| 19 |
+
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.
|
| 20 |
+
|
| 21 |
+
### trial_start_date
|
| 22 |
+
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.
|
| 23 |
+
|
| 24 |
+
### trial_end_date
|
| 25 |
+
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.
|
| 26 |
+
|
| 27 |
+
### dispute_value_nominal
|
| 28 |
+
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.
|
| 29 |
+
|
| 30 |
+
### plaintiff_loosing_share
|
| 31 |
+
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.
|
| 32 |
+
|
| 33 |
+
### court_cost_awarded_nominal
|
| 34 |
+
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.
|
| 35 |
+
|
| 36 |
+
### party_compensation_awarded_nominal
|
| 37 |
+
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.
|
| 38 |
+
|
| 39 |
+
### plaintiffs_all_count
|
| 40 |
+
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.
|
| 41 |
+
|
| 42 |
+
### defendants_all_count
|
| 43 |
+
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.
|
| 44 |
+
|
| 45 |
+
### plaintiff_no1_ISIC1_industry_category
|
| 46 |
+
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).
|
| 47 |
+
|
| 48 |
+
Step-by-step:
|
| 49 |
+
(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),
|
| 50 |
+
(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'.
|
| 51 |
+
(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').
|
| 52 |
+
(4) If the judgements contains no information at all about the plaintiff's economic activity, enter the literal 'None'.
|
| 53 |
+
|
| 54 |
+
### defendant_no1_ISIC1_industry_category
|
| 55 |
+
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).
|
| 56 |
+
|
| 57 |
+
Step-by-step:
|
| 58 |
+
(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),
|
| 59 |
+
(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'.
|
| 60 |
+
(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').
|
| 61 |
+
(4) If the judgements contains no information at all about the defendant's economic activity, enter the literal 'None'.
|
| 62 |
+
|
| 63 |
+
## Allowed ISIC industry categories (for *_industry_category variables)
|
| 64 |
+
|
| 65 |
+
- a_agriculture_forestry_fishing — Agriculture, forestry and fishing
|
| 66 |
+
- b_mining_quarrying — Mining and quarrying
|
| 67 |
+
- c_manufacturing — Manufacturing
|
| 68 |
+
- d_electricity_gas_steam_ac — Electricity, gas, steam and air conditioning supply
|
| 69 |
+
- e_water_sewerage_waste_remediation — Water supply; sewerage, waste management and remediation
|
| 70 |
+
- f_construction — Construction
|
| 71 |
+
- g_wholesale_retail_trade — Wholesale and retail trade; repair of motor vehicles
|
| 72 |
+
- h_transportation_storage — Transportation and storage
|
| 73 |
+
- i_accommodation_food_service — Accommodation and food service activities
|
| 74 |
+
- j_publishing_broadcasting_content — Publishing, broadcasting and content production
|
| 75 |
+
- k_telecom_it_info_services — Telecommunications, IT and other information services
|
| 76 |
+
- l_financial_insurance — Financial and insurance activities
|
| 77 |
+
- m_real_estate — Real estate activities
|
| 78 |
+
- n_professional_scientific_technical — Professional, scientific and technical activities
|
| 79 |
+
- o_administrative_support — Administrative and support service activities
|
| 80 |
+
- p_public_admin_defence — Public administration and defence; compulsory social security
|
| 81 |
+
- q_education — Education
|
| 82 |
+
- r_human_health_social_work — Human health and social work activities
|
| 83 |
+
- s_arts_entertainment_recreation — Arts, entertainment and recreation
|
| 84 |
+
- t_other_service_activities — Other service activities
|
| 85 |
+
- u_households_as_employers — Activities of households as employers
|
| 86 |
+
- v_extraterritorial_organisations — Activities of extraterritorial organisations and bodies
|
| 87 |
+
|
| 88 |
+
Fallbacks for the *_industry_category variables: 'no_allocation_possible' or 'None'.
|
| 89 |
+
|
| 90 |
+
## Currency variables
|
| 91 |
+
|
| 92 |
+
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."""
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def build(
|
| 96 |
+
rules: list[tuple[str, str]] | None = None,
|
| 97 |
+
isic: list[tuple[str, str, str]] | None = None,
|
| 98 |
+
) -> str:
|
| 99 |
+
return PROMPT
|
legex/quant_results.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Render the `Quantitative Results` LaTeX section.
|
| 2 |
+
|
| 3 |
+
Reads `data/analysis/per_country_per_column.csv` (produced by
|
| 4 |
+
`legex-analysis`), restricts it to the twelve evaluated jurisdictions
|
| 5 |
+
and the fourteen evaluated fields, then prints the section preamble plus
|
| 6 |
+
the headline table that compares the three systems on Acc / Recall /
|
| 7 |
+
Hallucination / F1, both over all fields and over the four-field cost
|
| 8 |
+
block.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import csv
|
| 13 |
+
import logging
|
| 14 |
+
import sys
|
| 15 |
+
from collections import defaultdict
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
log = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# Jurisdictions that survive the round-2 PDF audit (TW/BR/HK/IN excluded
|
| 22 |
+
# because their source PDFs were incomplete; BE/NP/RS excluded because
|
| 23 |
+
# inference was intentionally skipped for them).
|
| 24 |
+
EVALUATED_COUNTRIES: tuple[str, ...] = (
|
| 25 |
+
"am", "au", "ch", "de", "es", "fr", "ge",
|
| 26 |
+
"nz", "ph", "sg", "uk", "us",
|
| 27 |
+
)
|
| 28 |
+
H2H_COUNTRIES = EVALUATED_COUNTRIES # backwards-compat alias
|
| 29 |
+
|
| 30 |
+
EVAL_FIELDS: tuple[str, ...] = (
|
| 31 |
+
"legal_subject_judgement",
|
| 32 |
+
"trial_start_date",
|
| 33 |
+
"trial_end_date",
|
| 34 |
+
"dispute_value_nominal",
|
| 35 |
+
"plaintiff_loosing_share",
|
| 36 |
+
"court_cost_awarded_nominal",
|
| 37 |
+
"party_compensation_awarded_nominal",
|
| 38 |
+
"plaintiffs_all_count",
|
| 39 |
+
"defendants_all_count",
|
| 40 |
+
"plaintiff_no1_ISIC1_industry_category",
|
| 41 |
+
"defendant_no1_ISIC1_industry_category",
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
COST_BLOCK: tuple[str, ...] = (
|
| 45 |
+
"dispute_value_nominal",
|
| 46 |
+
"plaintiff_loosing_share",
|
| 47 |
+
"court_cost_awarded_nominal",
|
| 48 |
+
"party_compensation_awarded_nominal",
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# (system slug as written by legex-analysis, LaTeX label). Order = row order
|
| 52 |
+
# in the headline table.
|
| 53 |
+
SYSTEMS: tuple[tuple[str, str], ...] = (
|
| 54 |
+
("gemini", r"\texttt{gemini-3.1-flash-lite}"),
|
| 55 |
+
("gpt", r"\texttt{gpt-5.4-mini} "),
|
| 56 |
+
("harvey", r"\textsc{Harvey} "),
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
_BUCKETS = ("tp", "mismatch", "missed", "hallucinated", "tn")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _empty() -> dict[str, int]:
|
| 63 |
+
return {k: 0 for k in _BUCKETS}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _metrics(c: dict[str, int]) -> dict[str, float]:
|
| 67 |
+
tp, mism, miss, hallu, tn = c["tp"], c["mismatch"], c["missed"], c["hallucinated"], c["tn"]
|
| 68 |
+
total = tp + mism + miss + hallu + tn
|
| 69 |
+
filled_gold = tp + mism + miss
|
| 70 |
+
empty_gold = hallu + tn
|
| 71 |
+
p_denom = tp + mism + hallu
|
| 72 |
+
p = tp / p_denom if p_denom else 0.0
|
| 73 |
+
r = tp / filled_gold if filled_gold else 0.0
|
| 74 |
+
f1 = 2 * p * r / (p + r) if (p + r) else 0.0
|
| 75 |
+
return {
|
| 76 |
+
"accuracy": (tp + tn) / total if total else 0.0,
|
| 77 |
+
"recall_when_filled": r,
|
| 78 |
+
"hallucination_rate": hallu / empty_gold if empty_gold else 0.0,
|
| 79 |
+
"f1": f1,
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _aggregate(
|
| 84 |
+
csv_path: Path,
|
| 85 |
+
) -> dict[str, dict[str, dict[str, int]]]:
|
| 86 |
+
"""{ model -> { 'all' | 'cost' -> bucket counter } }."""
|
| 87 |
+
out: dict[str, dict[str, dict[str, int]]] = {
|
| 88 |
+
m: {"all": _empty(), "cost": _empty()} for m, _ in SYSTEMS
|
| 89 |
+
}
|
| 90 |
+
h2h = set(H2H_COUNTRIES)
|
| 91 |
+
eval_fields = set(EVAL_FIELDS)
|
| 92 |
+
cost_fields = set(COST_BLOCK)
|
| 93 |
+
models = {m for m, _ in SYSTEMS}
|
| 94 |
+
|
| 95 |
+
with open(csv_path, encoding="utf-8", newline="") as f:
|
| 96 |
+
for row in csv.DictReader(f):
|
| 97 |
+
if row["country"] not in h2h or row["model"] not in models:
|
| 98 |
+
continue
|
| 99 |
+
col = row["column"]
|
| 100 |
+
if col not in eval_fields:
|
| 101 |
+
continue
|
| 102 |
+
counts = {k: int(row[k]) for k in _BUCKETS}
|
| 103 |
+
for k in _BUCKETS:
|
| 104 |
+
out[row["model"]]["all"][k] += counts[k]
|
| 105 |
+
if col in cost_fields:
|
| 106 |
+
for k in _BUCKETS:
|
| 107 |
+
out[row["model"]]["cost"][k] += counts[k]
|
| 108 |
+
return out
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _fmt_pct(v: float) -> str:
|
| 112 |
+
return f"{v * 100:.1f}\\%"
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _fmt_f1(v: float) -> str:
|
| 116 |
+
return f"{v:.3f}"
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _bold_best(values: list[float], formatter, higher_is_better: bool = True) -> list[str]:
|
| 120 |
+
best = max(values) if higher_is_better else min(values)
|
| 121 |
+
return [
|
| 122 |
+
rf"\textbf{{{formatter(v)}}}" if v == best else formatter(v)
|
| 123 |
+
for v in values
|
| 124 |
+
]
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def render_section(agg: dict[str, dict[str, dict[str, int]]]) -> str:
|
| 128 |
+
lines: list[str] = []
|
| 129 |
+
lines.append(r"% Auto-generated by legex-quant-results — do not edit by hand.")
|
| 130 |
+
lines.append(r"\section{Quantitative Results}")
|
| 131 |
+
lines.append("")
|
| 132 |
+
lines.append(
|
| 133 |
+
r"We score the three systems against the human coded dataset: a commercial"
|
| 134 |
+
)
|
| 135 |
+
lines.append(
|
| 136 |
+
r"review-table product by \textsc{Harvey} and two schema-constrained LLM"
|
| 137 |
+
)
|
| 138 |
+
lines.append(
|
| 139 |
+
r"pipelines (\texttt{gpt-5.4-mini} and \texttt{gemini-3.1-flash-lite})."
|
| 140 |
+
)
|
| 141 |
+
lines.append(
|
| 142 |
+
r"Since the dataset contains missing fields, e.g.\ where a court judgement"
|
| 143 |
+
)
|
| 144 |
+
lines.append(
|
| 145 |
+
r"does not issue costs we evaluate our systems against two metrics:"
|
| 146 |
+
)
|
| 147 |
+
lines.append(r"\begin{itemize}")
|
| 148 |
+
lines.append(
|
| 149 |
+
r" \item \textbf{Accuracy when filled}: how often the system extracts the"
|
| 150 |
+
r" correct value given that the human expert has classified it."
|
| 151 |
+
)
|
| 152 |
+
lines.append(
|
| 153 |
+
r" \item \textbf{Hallucination rate}: how often the system extracts a"
|
| 154 |
+
r" value given that the human expert has left the field empty."
|
| 155 |
+
)
|
| 156 |
+
lines.append(r"\end{itemize}")
|
| 157 |
+
lines.append("")
|
| 158 |
+
|
| 159 |
+
metrics_all = {m: _metrics(agg[m]["all"]) for m, _ in SYSTEMS}
|
| 160 |
+
metrics_cost = {m: _metrics(agg[m]["cost"]) for m, _ in SYSTEMS}
|
| 161 |
+
|
| 162 |
+
def _p(model: str, panel: str, key: str) -> str:
|
| 163 |
+
src = metrics_all if panel == "all" else metrics_cost
|
| 164 |
+
return f"{src[model][key] * 100:.1f}"
|
| 165 |
+
|
| 166 |
+
lines.append(
|
| 167 |
+
r"\Cref{tab:overall} shows the same trade-off on both panels: the two"
|
| 168 |
+
r" LLM pipelines are more eager extractors, while \textsc{Harvey} is"
|
| 169 |
+
r" more conservative. Across all " + str(len(EVAL_FIELDS)) + r" evaluated"
|
| 170 |
+
r" fields \texttt{gpt-5.4-mini} and \texttt{gemini-3.1-flash-lite}"
|
| 171 |
+
r" reach accuracy when filled of "
|
| 172 |
+
+ _p("gpt", "all", "recall_when_filled") + r"\,\% and "
|
| 173 |
+
+ _p("gemini", "all", "recall_when_filled")
|
| 174 |
+
+ r"\,\%, alongside \textsc{Harvey} at "
|
| 175 |
+
+ _p("harvey", "all", "recall_when_filled") + r"\,\%, but the LLM"
|
| 176 |
+
r" pipelines pay for that recall with hallucination rates of "
|
| 177 |
+
+ _p("gpt", "all", "hallucination_rate") + r"\,\% and "
|
| 178 |
+
+ _p("gemini", "all", "hallucination_rate") + r"\,\% against \textsc{Harvey}'s "
|
| 179 |
+
+ _p("harvey", "all", "hallucination_rate") + r"\,\%."
|
| 180 |
+
r" Narrowing to the four cost-block variables, the three systems"
|
| 181 |
+
r" converge on accuracy ("
|
| 182 |
+
+ _p("harvey", "cost", "recall_when_filled") + r"--"
|
| 183 |
+
+ _p("gemini", "cost", "recall_when_filled") + r"\,\%), and the"
|
| 184 |
+
r" hallucination rates land at "
|
| 185 |
+
+ _p("gemini", "cost", "hallucination_rate") + r"\,\% (Gemini), "
|
| 186 |
+
+ _p("harvey", "cost", "hallucination_rate") + r"\,\% (Harvey), and "
|
| 187 |
+
+ _p("gpt", "cost", "hallucination_rate") + r"\,\% (GPT)."
|
| 188 |
+
r" No single system dominates: the LLM pipelines are preferable when"
|
| 189 |
+
r" the downstream task tolerates noisy extractions in exchange for"
|
| 190 |
+
r" coverage, whereas \textsc{Harvey} is preferable when emitted values"
|
| 191 |
+
r" must be trusted on the non-cost variables."
|
| 192 |
+
)
|
| 193 |
+
lines.append("")
|
| 194 |
+
|
| 195 |
+
acc_all = [metrics_all[m]["recall_when_filled"] for m, _ in SYSTEMS]
|
| 196 |
+
hal_all = [metrics_all[m]["hallucination_rate"] for m, _ in SYSTEMS]
|
| 197 |
+
acc_cost = [metrics_cost[m]["recall_when_filled"] for m, _ in SYSTEMS]
|
| 198 |
+
hal_cost = [metrics_cost[m]["hallucination_rate"] for m, _ in SYSTEMS]
|
| 199 |
+
|
| 200 |
+
acc_all_s = _bold_best(acc_all, _fmt_pct, True)
|
| 201 |
+
hal_all_s = _bold_best(hal_all, _fmt_pct, False)
|
| 202 |
+
acc_cost_s = _bold_best(acc_cost, _fmt_pct, True)
|
| 203 |
+
hal_cost_s = _bold_best(hal_cost, _fmt_pct, False)
|
| 204 |
+
|
| 205 |
+
lines.append(r"\begin{table}[h]")
|
| 206 |
+
lines.append(
|
| 207 |
+
r"\caption{Overall metrics on the "
|
| 208 |
+
+ str(len(EVALUATED_COUNTRIES))
|
| 209 |
+
+ r" head-to-head jurisdictions, golden-set rows with no"
|
| 210 |
+
r" expert-filled field excluded."
|
| 211 |
+
r" \emph{Acc.\ when filled} is the share of expert-filled cells the"
|
| 212 |
+
r" system extracts correctly; \emph{Hallu.\ rate} is the share of"
|
| 213 |
+
r" expert-empty cells where the system invented a value."
|
| 214 |
+
r" The right block restricts the same metrics to the four cost-block"
|
| 215 |
+
r" variables. Best per column in \textbf{bold} (lower is better for"
|
| 216 |
+
r" Hallu.\ rate)."
|
| 217 |
+
r"}"
|
| 218 |
+
)
|
| 219 |
+
lines.append(r"\label{tab:overall}")
|
| 220 |
+
lines.append(r"\centering\small")
|
| 221 |
+
lines.append(r"\begin{tabular}{@{}lrr@{\hskip 12pt}rr@{}}")
|
| 222 |
+
lines.append(r"\toprule")
|
| 223 |
+
lines.append(
|
| 224 |
+
r" & \multicolumn{2}{c}{All "
|
| 225 |
+
+ str(len(EVAL_FIELDS))
|
| 226 |
+
+ r" evaluated fields} & \multicolumn{2}{c}{Cost block ("
|
| 227 |
+
+ str(len(COST_BLOCK))
|
| 228 |
+
+ r" fields)} \\"
|
| 229 |
+
)
|
| 230 |
+
lines.append(r"\cmidrule(lr){2-3}\cmidrule(l){4-5}")
|
| 231 |
+
lines.append(
|
| 232 |
+
r"System & Acc.\ when filled & Hallu.\ rate"
|
| 233 |
+
r" & Acc.\ when filled & Hallu.\ rate \\"
|
| 234 |
+
)
|
| 235 |
+
lines.append(r"\midrule")
|
| 236 |
+
for i, (_, label) in enumerate(SYSTEMS):
|
| 237 |
+
lines.append(
|
| 238 |
+
f"{label} & {acc_all_s[i]} & {hal_all_s[i]}"
|
| 239 |
+
f" & {acc_cost_s[i]} & {hal_cost_s[i]} \\\\"
|
| 240 |
+
)
|
| 241 |
+
lines.append(r"\bottomrule")
|
| 242 |
+
lines.append(r"\end{tabular}")
|
| 243 |
+
lines.append(r"\end{table}")
|
| 244 |
+
lines.append("")
|
| 245 |
+
return "\n".join(lines)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _print_console_summary(agg: dict[str, dict[str, dict[str, int]]]) -> None:
|
| 249 |
+
"""Quick human-readable echo so the user sees the numbers in the terminal too."""
|
| 250 |
+
print(f"{'system':<28} {'set':<5} {'Acc.filled':>11} {'Hallu':>6}")
|
| 251 |
+
for model, _ in SYSTEMS:
|
| 252 |
+
for tag in ("all", "cost"):
|
| 253 |
+
m = _metrics(agg[model][tag])
|
| 254 |
+
print(
|
| 255 |
+
f"{model:<28} {tag:<5} "
|
| 256 |
+
f"{m['recall_when_filled']:>11.1%} {m['hallucination_rate']:>6.1%}"
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def main() -> None:
|
| 261 |
+
logging.basicConfig(
|
| 262 |
+
level=logging.INFO,
|
| 263 |
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 264 |
+
handlers=[logging.StreamHandler(sys.stderr)],
|
| 265 |
+
)
|
| 266 |
+
parser = argparse.ArgumentParser(
|
| 267 |
+
prog="legex-quant-results",
|
| 268 |
+
description="Render the Quantitative Results section + headline table.",
|
| 269 |
+
)
|
| 270 |
+
parser.add_argument(
|
| 271 |
+
"--input", type=Path,
|
| 272 |
+
default=Path("data/analysis/per_country_per_column.csv"),
|
| 273 |
+
help="per_country_per_column.csv produced by legex-analysis.",
|
| 274 |
+
)
|
| 275 |
+
parser.add_argument(
|
| 276 |
+
"--out", type=Path,
|
| 277 |
+
default=Path("data/analysis/quant_results.tex"),
|
| 278 |
+
help="Where to write the rendered LaTeX section.",
|
| 279 |
+
)
|
| 280 |
+
args = parser.parse_args()
|
| 281 |
+
|
| 282 |
+
if not args.input.exists():
|
| 283 |
+
raise SystemExit(
|
| 284 |
+
f"{args.input} not found — run `legex-analysis` first to generate it."
|
| 285 |
+
)
|
| 286 |
+
agg = _aggregate(args.input)
|
| 287 |
+
tex = render_section(agg)
|
| 288 |
+
args.out.parent.mkdir(parents=True, exist_ok=True)
|
| 289 |
+
args.out.write_text(tex, encoding="utf-8")
|
| 290 |
+
log.info(f"wrote {args.out}")
|
| 291 |
+
_print_console_summary(agg)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
if __name__ == "__main__":
|
| 295 |
+
main()
|
legex/scrape_full_text.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scrape full text from a goldenset xlsx's GOLDENSET sheet into a JSONL file.
|
| 2 |
+
|
| 3 |
+
For each row of the GOLDENSET sheet, fetches the URL in the ``link`` column
|
| 4 |
+
(HTML or PDF), extracts text, and writes one JSON line in the same shape as
|
| 5 |
+
``data/am/full_text.jsonl``:
|
| 6 |
+
|
| 7 |
+
{"case_id": "<slug>", "full_text": "case_id: <orig> link: <url> Quelle Text: <source> <body>"}
|
| 8 |
+
|
| 9 |
+
``case_id`` (key) is the filesystem-safe slug of the workbook's case_id;
|
| 10 |
+
the body keeps the original case_id and link verbatim. Whitespace in the
|
| 11 |
+
body is collapsed to single spaces so each record stays on one line.
|
| 12 |
+
|
| 13 |
+
Usage:
|
| 14 |
+
uv run python -m legex.scrape_full_text data/am/Goldenset_Armenia_final.xlsx
|
| 15 |
+
uv run python -m legex.scrape_full_text data/gh/Goldenset_Ghana.xlsx --resume
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import json
|
| 22 |
+
import logging
|
| 23 |
+
import re
|
| 24 |
+
import sys
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import openpyxl
|
| 28 |
+
|
| 29 |
+
from legex.pdf_export.core import safe_slug
|
| 30 |
+
from legex.pdf_export.urls import pick_body
|
| 31 |
+
from legex.pdf_export.workbook import cell, header_map
|
| 32 |
+
|
| 33 |
+
log = logging.getLogger("legex.scrape_full_text")
|
| 34 |
+
|
| 35 |
+
_WS_RE = re.compile(r"\s+")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def normalize_ws(text: str) -> str:
|
| 39 |
+
return _WS_RE.sub(" ", text).strip()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def build_full_text(case_id: str, link: str, source: str, body: str) -> str:
|
| 43 |
+
return normalize_ws(
|
| 44 |
+
f"case_id: {case_id} link: {link} Quelle Text: {source} {body}"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _load_existing_case_ids(out_path: Path) -> set[str]:
|
| 49 |
+
seen: set[str] = set()
|
| 50 |
+
with out_path.open("r", encoding="utf-8") as f:
|
| 51 |
+
for line in f:
|
| 52 |
+
line = line.strip()
|
| 53 |
+
if not line:
|
| 54 |
+
continue
|
| 55 |
+
try:
|
| 56 |
+
rec = json.loads(line)
|
| 57 |
+
except json.JSONDecodeError:
|
| 58 |
+
continue
|
| 59 |
+
cid = rec.get("case_id")
|
| 60 |
+
if cid:
|
| 61 |
+
seen.add(cid)
|
| 62 |
+
return seen
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def scrape_xlsx(
|
| 66 |
+
xlsx: Path,
|
| 67 |
+
out_path: Path,
|
| 68 |
+
*,
|
| 69 |
+
pause_s: float,
|
| 70 |
+
req_timeout: float,
|
| 71 |
+
limit: int | None,
|
| 72 |
+
resume: bool,
|
| 73 |
+
) -> int:
|
| 74 |
+
wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True)
|
| 75 |
+
if "GOLDENSET" not in wb.sheetnames:
|
| 76 |
+
wb.close()
|
| 77 |
+
log.error("no GOLDENSET sheet in %s", xlsx)
|
| 78 |
+
return 0
|
| 79 |
+
ws = wb["GOLDENSET"]
|
| 80 |
+
rows = ws.iter_rows(values_only=True)
|
| 81 |
+
header_row = next(rows, None)
|
| 82 |
+
if not header_row:
|
| 83 |
+
wb.close()
|
| 84 |
+
return 0
|
| 85 |
+
h = header_map(header_row)
|
| 86 |
+
idx_case = h.get("case_id")
|
| 87 |
+
idx_link = h.get("link")
|
| 88 |
+
idx_text = h.get("full_text")
|
| 89 |
+
if idx_link is None:
|
| 90 |
+
wb.close()
|
| 91 |
+
log.error("no 'link' column in %s", xlsx)
|
| 92 |
+
return 0
|
| 93 |
+
|
| 94 |
+
existing: set[str] = set()
|
| 95 |
+
mode = "w"
|
| 96 |
+
if resume and out_path.exists():
|
| 97 |
+
existing = _load_existing_case_ids(out_path)
|
| 98 |
+
mode = "a"
|
| 99 |
+
log.info("resume: %d existing case_ids in %s", len(existing), out_path)
|
| 100 |
+
|
| 101 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 102 |
+
written = 0
|
| 103 |
+
row_idx = 1
|
| 104 |
+
label = xlsx.parent.name
|
| 105 |
+
with out_path.open(mode, encoding="utf-8") as out:
|
| 106 |
+
for row in rows:
|
| 107 |
+
row_idx += 1
|
| 108 |
+
if not row:
|
| 109 |
+
continue
|
| 110 |
+
link_val = (cell(row, idx_link) or "").strip()
|
| 111 |
+
case_id_raw = cell(row, idx_case)
|
| 112 |
+
sheet_full = cell(row, idx_text) if idx_text is not None else None
|
| 113 |
+
if (
|
| 114 |
+
not str(case_id_raw or "").strip()
|
| 115 |
+
and not link_val
|
| 116 |
+
and not (sheet_full or "").strip()
|
| 117 |
+
):
|
| 118 |
+
continue
|
| 119 |
+
slug = safe_slug(case_id_raw, link_val or None, row_idx)
|
| 120 |
+
if slug in existing:
|
| 121 |
+
continue
|
| 122 |
+
body, source = pick_body(link_val, sheet_full, pause_s, req_timeout)
|
| 123 |
+
full = build_full_text(
|
| 124 |
+
str(case_id_raw or "").strip(), link_val, source, body
|
| 125 |
+
)
|
| 126 |
+
out.write(
|
| 127 |
+
json.dumps({"case_id": slug, "full_text": full}, ensure_ascii=False)
|
| 128 |
+
)
|
| 129 |
+
out.write("\n")
|
| 130 |
+
out.flush()
|
| 131 |
+
existing.add(slug)
|
| 132 |
+
written += 1
|
| 133 |
+
if written % 10 == 0:
|
| 134 |
+
log.info("[%s] %d written", label, written)
|
| 135 |
+
if limit is not None and written >= limit:
|
| 136 |
+
break
|
| 137 |
+
wb.close()
|
| 138 |
+
log.info("[%s] done: %d written -> %s", label, written, out_path)
|
| 139 |
+
return written
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def main() -> int:
|
| 143 |
+
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
| 144 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 145 |
+
ap.add_argument("xlsx", type=Path, help="Path to Goldenset_*.xlsx")
|
| 146 |
+
ap.add_argument(
|
| 147 |
+
"--out",
|
| 148 |
+
type=Path,
|
| 149 |
+
default=None,
|
| 150 |
+
help="Output jsonl path (default: <xlsx.parent>/full_text.jsonl)",
|
| 151 |
+
)
|
| 152 |
+
ap.add_argument(
|
| 153 |
+
"--pause", type=float, default=0.5, help="Seconds between requests (default: 0.5)"
|
| 154 |
+
)
|
| 155 |
+
ap.add_argument(
|
| 156 |
+
"--timeout", type=float, default=28.0, help="Request timeout in seconds (default: 28)"
|
| 157 |
+
)
|
| 158 |
+
ap.add_argument("--limit", type=int, default=None, help="Max rows to scrape")
|
| 159 |
+
ap.add_argument(
|
| 160 |
+
"--resume",
|
| 161 |
+
action="store_true",
|
| 162 |
+
help="Append to existing jsonl, skipping case_ids already present",
|
| 163 |
+
)
|
| 164 |
+
args = ap.parse_args()
|
| 165 |
+
|
| 166 |
+
if not args.xlsx.is_file():
|
| 167 |
+
log.error("xlsx not found: %s", args.xlsx)
|
| 168 |
+
return 1
|
| 169 |
+
|
| 170 |
+
out_path = args.out or (args.xlsx.parent / "full_text.jsonl")
|
| 171 |
+
scrape_xlsx(
|
| 172 |
+
args.xlsx,
|
| 173 |
+
out_path,
|
| 174 |
+
pause_s=args.pause,
|
| 175 |
+
req_timeout=args.timeout,
|
| 176 |
+
limit=args.limit,
|
| 177 |
+
resume=args.resume,
|
| 178 |
+
)
|
| 179 |
+
return 0
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
if __name__ == "__main__":
|
| 183 |
+
sys.exit(main())
|
legex/scrapers/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Register new scrapers here."""
|
| 2 |
+
|
| 3 |
+
from legex.scrapers.al import ALScraper
|
| 4 |
+
from legex.scrapers.am import AMScraper
|
| 5 |
+
from legex.scrapers.at import ATScraper
|
| 6 |
+
from legex.scrapers.au import AUScraper
|
| 7 |
+
from legex.scrapers.base import BaseScraper
|
| 8 |
+
from legex.scrapers.be import BEScraper
|
| 9 |
+
from legex.scrapers.ch import CHScraper
|
| 10 |
+
from legex.scrapers.de import DEScraper
|
| 11 |
+
from legex.scrapers.fr import FRScraper
|
| 12 |
+
from legex.scrapers.ge import GEScraper
|
| 13 |
+
from legex.scrapers.gh import GHScraper
|
| 14 |
+
from legex.scrapers.in_ import INScraper
|
| 15 |
+
from legex.scrapers.it import ITScraper
|
| 16 |
+
from legex.scrapers.kr import KRScraper
|
| 17 |
+
from legex.scrapers.li import LIScraper
|
| 18 |
+
from legex.scrapers.lu import LUScraper
|
| 19 |
+
from legex.scrapers.nz import NZScraper
|
| 20 |
+
from legex.scrapers.ph import PHScraper
|
| 21 |
+
from legex.scrapers.rs import RSScraper
|
| 22 |
+
from legex.scrapers.sg import SGScraper
|
| 23 |
+
from legex.scrapers.xk import XKScraper
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
SCRAPERS: dict[str, type[BaseScraper]] = {
|
| 27 |
+
"al": ALScraper,
|
| 28 |
+
"am": AMScraper,
|
| 29 |
+
"at": ATScraper,
|
| 30 |
+
"au": AUScraper,
|
| 31 |
+
"ch": CHScraper,
|
| 32 |
+
"de": DEScraper,
|
| 33 |
+
"fr": FRScraper,
|
| 34 |
+
"ge": GEScraper,
|
| 35 |
+
"gh": GHScraper,
|
| 36 |
+
"in": INScraper,
|
| 37 |
+
"it": ITScraper,
|
| 38 |
+
"kr": KRScraper,
|
| 39 |
+
"li": LIScraper,
|
| 40 |
+
"lu": LUScraper,
|
| 41 |
+
"nz": NZScraper,
|
| 42 |
+
"ph": PHScraper,
|
| 43 |
+
"rs": RSScraper,
|
| 44 |
+
"sg": SGScraper,
|
| 45 |
+
"xk": XKScraper,
|
| 46 |
+
}
|
legex/scrapers/al.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Albanian Supreme Court (Gjykata e Lartë) via the Gatsby page-data JSON API.
|
| 2 |
+
|
| 3 |
+
Decisions are published as periodic and thematic bulletins under
|
| 4 |
+
`/sq/lajme/buletini/`. Each bulletin's detail page exposes its decisions
|
| 5 |
+
inline as HTML strings inside `result.data.api.newsArticle.body[].content[].text_sq`,
|
| 6 |
+
so we can extract full text without touching the pre-2020 .doc archive.
|
| 7 |
+
|
| 8 |
+
Civil filter: keep decisions tagged "Kolegji Civil" (Civil College) or
|
| 9 |
+
"Kolegjet e Bashkuara" (United Colleges, mixed civil/penal).
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import html
|
| 13 |
+
import logging
|
| 14 |
+
import re
|
| 15 |
+
import time
|
| 16 |
+
from datetime import date
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
import requests
|
| 20 |
+
|
| 21 |
+
from legex.models.base import Case
|
| 22 |
+
from legex.scrapers.base import BaseScraper
|
| 23 |
+
|
| 24 |
+
log = logging.getLogger(__name__)
|
| 25 |
+
|
| 26 |
+
API_BASE = "https://www.gjykataelarte.gov.al/page-data"
|
| 27 |
+
PUBLIC_BASE = "https://www.gjykataelarte.gov.al"
|
| 28 |
+
USER_AGENT = "legex-research (open-data, friendly)"
|
| 29 |
+
DELAY_SECONDS = 1.0
|
| 30 |
+
MAX_LIST_PAGES = 15
|
| 31 |
+
|
| 32 |
+
# New-format header (periodik/tematik bulletins 2024+) — standalone line:
|
| 33 |
+
# Vendimi nr. 00-2025-1613 (255), datë 21.10.2025 i Kolegjit Penal
|
| 34 |
+
# Followed by Maksima / Fjalë kyçe / Përmbledhje sections.
|
| 35 |
+
_DECISION_HEADER_RE = re.compile(
|
| 36 |
+
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ëÇçë ]+)",
|
| 37 |
+
re.IGNORECASE,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# Old-format mention (informativ/tematik bulletins 2022-2023) — appears inline:
|
| 41 |
+
# Në vendimin nr.00-2022-635, datë 01.04.2022, ...
|
| 42 |
+
# College is set by a section heading above ("Kolegji Civil i Gjykatës së Lartë").
|
| 43 |
+
_OLD_DECISION_RE = re.compile(
|
| 44 |
+
r"N[ëe]\s+vendim(?:in)?\s+nr[\.\s]*([\d\(\)\s\-––]+?)\s*,?\s*dat[ëe]\s+(\d{1,2})[\.,](\d{1,2})[\.,](\d{4})",
|
| 45 |
+
re.IGNORECASE,
|
| 46 |
+
)
|
| 47 |
+
_COLLEGE_HEADING_RE = re.compile(
|
| 48 |
+
r"Kolegj[i]?\s+(Civil|Penal|Administrativ|Administrative|Tregtar|"
|
| 49 |
+
r"Bashkuar)[a-zëçÇË]*\s+(?:i\s+)?Gjykat",
|
| 50 |
+
re.IGNORECASE,
|
| 51 |
+
)
|
| 52 |
+
# Short aliases used inline (KCGJL = Kolegji Civil, KPGJL = Kolegji Penal, KAGJL = Kolegji Administrativ)
|
| 53 |
+
_INLINE_COLLEGE_RE = re.compile(r"\bK(C|P|A)GJL\b")
|
| 54 |
+
_DOC_LINK_RE = re.compile(
|
| 55 |
+
r"https?://gjykata-media\.s3\.eu-central-1\.amazonaws\.com/[\w\-\.\/]+\.doc",
|
| 56 |
+
re.IGNORECASE,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
_DECISION_NUM_RE = re.compile(r"nr\.?\s*([\d\-\(\)\s]+?)\s*,", re.IGNORECASE)
|
| 60 |
+
_DATE_RE = re.compile(r"dat[ëe]\s+(\d{1,2})\.(\d{1,2})\.(\d{4})")
|
| 61 |
+
_KEYWORD_RE = re.compile(
|
| 62 |
+
r"Fjal[ëe]\s*ky[çc]e\s*[-–—]\s*(.+?)(?=P[ëe]rmbledhje|Maksima|$)",
|
| 63 |
+
re.DOTALL | re.IGNORECASE,
|
| 64 |
+
)
|
| 65 |
+
_MAXIMA_RE = re.compile(
|
| 66 |
+
r"Maksima\s*[-–—]\s*(.+?)(?=Fjal[ëe]\s*ky[çc]e|P[ëe]rmbledhje|$)",
|
| 67 |
+
re.DOTALL | re.IGNORECASE,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _strip_html(raw: str) -> str:
|
| 72 |
+
"""Remove HTML tags, decode entities, collapse whitespace."""
|
| 73 |
+
text = re.sub(r"<[^>]+>", "\n", raw)
|
| 74 |
+
text = html.unescape(text)
|
| 75 |
+
text = re.sub(r"\n{3,}", "\n\n", text)
|
| 76 |
+
return text.strip()
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _detect_college(header: str) -> str:
|
| 80 |
+
h = header.lower()
|
| 81 |
+
if "civil" in h:
|
| 82 |
+
return "civil"
|
| 83 |
+
if "penal" in h:
|
| 84 |
+
return "penal"
|
| 85 |
+
if "administrat" in h:
|
| 86 |
+
return "administrative"
|
| 87 |
+
if "bashk" in h:
|
| 88 |
+
return "united"
|
| 89 |
+
return "unknown"
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _parse_iso_date(header: str) -> str | None:
|
| 93 |
+
m = _DATE_RE.search(header)
|
| 94 |
+
if not m:
|
| 95 |
+
return None
|
| 96 |
+
return f"{m.group(3)}-{m.group(2).zfill(2)}-{m.group(1).zfill(2)}"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _parse_decision_number(header: str) -> str | None:
|
| 100 |
+
m = _DECISION_NUM_RE.search(header)
|
| 101 |
+
if not m:
|
| 102 |
+
return None
|
| 103 |
+
return re.sub(r"\s+", "", m.group(1))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _fetch_json(session: requests.Session, url: str) -> dict[str, Any] | None:
|
| 107 |
+
try:
|
| 108 |
+
resp = session.get(url, timeout=30)
|
| 109 |
+
except requests.RequestException as e:
|
| 110 |
+
log.warning("AL request error %s: %s", url, e)
|
| 111 |
+
return None
|
| 112 |
+
if resp.status_code == 404:
|
| 113 |
+
return None
|
| 114 |
+
if resp.status_code != 200:
|
| 115 |
+
log.warning("AL HTTP %d for %s", resp.status_code, url)
|
| 116 |
+
return None
|
| 117 |
+
try:
|
| 118 |
+
return resp.json()
|
| 119 |
+
except ValueError:
|
| 120 |
+
log.warning("AL non-JSON response from %s", url)
|
| 121 |
+
return None
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _list_bulletin_slugs(session: requests.Session) -> list[dict[str, Any]]:
|
| 125 |
+
slugs: list[dict[str, Any]] = []
|
| 126 |
+
for page in range(1, MAX_LIST_PAGES + 1):
|
| 127 |
+
url = (
|
| 128 |
+
f"{API_BASE}/sq/lajme/buletini/page-data.json"
|
| 129 |
+
if page == 1
|
| 130 |
+
else f"{API_BASE}/sq/lajme/buletini/{page}/page-data.json"
|
| 131 |
+
)
|
| 132 |
+
data = _fetch_json(session, url)
|
| 133 |
+
if not data:
|
| 134 |
+
break
|
| 135 |
+
articles = (
|
| 136 |
+
data.get("result", {}).get("pageContext", {}).get("articles", [])
|
| 137 |
+
)
|
| 138 |
+
if not articles:
|
| 139 |
+
break
|
| 140 |
+
for a in articles:
|
| 141 |
+
slug = a.get("slug")
|
| 142 |
+
if not slug:
|
| 143 |
+
continue
|
| 144 |
+
title_obj = a.get("title")
|
| 145 |
+
if isinstance(title_obj, dict):
|
| 146 |
+
title = title_obj.get("text_sq", "") or title_obj.get("text_en", "")
|
| 147 |
+
else:
|
| 148 |
+
title = title_obj or ""
|
| 149 |
+
slugs.append(
|
| 150 |
+
{
|
| 151 |
+
"slug": slug,
|
| 152 |
+
"publish_date": a.get("publishDate"),
|
| 153 |
+
"title": title,
|
| 154 |
+
}
|
| 155 |
+
)
|
| 156 |
+
log.info("AL list page %d: %d bulletins (cumulative %d)", page, len(articles), len(slugs))
|
| 157 |
+
time.sleep(DELAY_SECONDS)
|
| 158 |
+
return slugs
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _fetch_bulletin_html(session: requests.Session, slug: str) -> str:
|
| 162 |
+
url = f"{API_BASE}/sq/lajme/buletini/{slug}/page-data.json"
|
| 163 |
+
data = _fetch_json(session, url)
|
| 164 |
+
if not data:
|
| 165 |
+
return ""
|
| 166 |
+
try:
|
| 167 |
+
body = data["result"]["data"]["api"]["newsArticle"]["body"]
|
| 168 |
+
except (KeyError, TypeError):
|
| 169 |
+
return ""
|
| 170 |
+
chunks: list[str] = []
|
| 171 |
+
for block in body:
|
| 172 |
+
if "Paragraph" not in block.get("__typename", ""):
|
| 173 |
+
continue
|
| 174 |
+
for content in block.get("content", []) or []:
|
| 175 |
+
txt = content.get("text_sq") or content.get("text_en") or ""
|
| 176 |
+
if txt:
|
| 177 |
+
chunks.append(txt)
|
| 178 |
+
return "".join(chunks)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _parse_decisions(
|
| 182 |
+
bulletin_html: str, slug: str, bulletin_title: str
|
| 183 |
+
) -> list[dict[str, Any]]:
|
| 184 |
+
plain = _strip_html(bulletin_html)
|
| 185 |
+
parts = _DECISION_HEADER_RE.split(plain)
|
| 186 |
+
if len(parts) < 3:
|
| 187 |
+
# Fall back to the older bulletin layout where decisions are
|
| 188 |
+
# introduced inline by "Në vendimin nr. X, datë Y" mentions.
|
| 189 |
+
return _parse_old_format(plain, slug, bulletin_title)
|
| 190 |
+
decisions: list[dict[str, Any]] = []
|
| 191 |
+
i = 1
|
| 192 |
+
while i < len(parts) - 1:
|
| 193 |
+
header = parts[i].strip()
|
| 194 |
+
body = parts[i + 1].strip()
|
| 195 |
+
i += 2
|
| 196 |
+
if len(body) < 200:
|
| 197 |
+
continue
|
| 198 |
+
decisions.append(
|
| 199 |
+
{
|
| 200 |
+
"header": header,
|
| 201 |
+
"body": body,
|
| 202 |
+
"decision_number": _parse_decision_number(header),
|
| 203 |
+
"iso_date": _parse_iso_date(header),
|
| 204 |
+
"college": _detect_college(header),
|
| 205 |
+
"maxima": (m.group(1).strip() if (m := _MAXIMA_RE.search(body)) else None),
|
| 206 |
+
"keywords": (
|
| 207 |
+
[k.strip() for k in re.split(r"[,;]", km.group(1)) if k.strip()]
|
| 208 |
+
if (km := _KEYWORD_RE.search(body))
|
| 209 |
+
else []
|
| 210 |
+
),
|
| 211 |
+
"bulletin_slug": slug,
|
| 212 |
+
"bulletin_title": bulletin_title,
|
| 213 |
+
"doc_link": None,
|
| 214 |
+
"format": "new",
|
| 215 |
+
}
|
| 216 |
+
)
|
| 217 |
+
return decisions
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _section_college_at(plain: str, pos: int) -> str:
|
| 221 |
+
"""Return the most recent college heading before pos in plain text."""
|
| 222 |
+
head = plain[:pos]
|
| 223 |
+
last: str = "unknown"
|
| 224 |
+
for m in _COLLEGE_HEADING_RE.finditer(head):
|
| 225 |
+
last = _detect_college(m.group(0))
|
| 226 |
+
return last
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def _inline_college_at(snippet: str) -> str:
|
| 230 |
+
m = _INLINE_COLLEGE_RE.search(snippet)
|
| 231 |
+
if not m:
|
| 232 |
+
return "unknown"
|
| 233 |
+
return {"C": "civil", "P": "penal", "A": "administrative"}.get(m.group(1), "unknown")
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _parse_old_format(
|
| 237 |
+
plain: str, slug: str, bulletin_title: str
|
| 238 |
+
) -> list[dict[str, Any]]:
|
| 239 |
+
matches = list(_OLD_DECISION_RE.finditer(plain))
|
| 240 |
+
if not matches:
|
| 241 |
+
return []
|
| 242 |
+
|
| 243 |
+
decisions: list[dict[str, Any]] = []
|
| 244 |
+
for idx, m in enumerate(matches):
|
| 245 |
+
# body spans from this match to the next, capped at ~3000 chars.
|
| 246 |
+
body_end = matches[idx + 1].start() if idx + 1 < len(matches) else m.end() + 3000
|
| 247 |
+
body = plain[m.start():body_end].strip()
|
| 248 |
+
if len(body) < 150:
|
| 249 |
+
continue
|
| 250 |
+
|
| 251 |
+
decision_num = re.sub(r"\s+", "", m.group(1))
|
| 252 |
+
iso_date = f"{m.group(4)}-{m.group(3).zfill(2)}-{m.group(2).zfill(2)}"
|
| 253 |
+
|
| 254 |
+
# Prefer a college signalled inline (KCGJL / KPGJL / KAGJL inside the
|
| 255 |
+
# summary itself) over the section heading, since some bulletins mix
|
| 256 |
+
# multiple colleges in a single section.
|
| 257 |
+
college = _inline_college_at(body)
|
| 258 |
+
if college == "unknown":
|
| 259 |
+
college = _section_college_at(plain, m.start())
|
| 260 |
+
|
| 261 |
+
doc_link_m = _DOC_LINK_RE.search(body)
|
| 262 |
+
doc_link = doc_link_m.group(0) if doc_link_m else None
|
| 263 |
+
|
| 264 |
+
decisions.append(
|
| 265 |
+
{
|
| 266 |
+
"header": body[:200],
|
| 267 |
+
"body": body,
|
| 268 |
+
"decision_number": decision_num,
|
| 269 |
+
"iso_date": iso_date,
|
| 270 |
+
"college": college,
|
| 271 |
+
"maxima": None,
|
| 272 |
+
"keywords": [],
|
| 273 |
+
"bulletin_slug": slug,
|
| 274 |
+
"bulletin_title": bulletin_title,
|
| 275 |
+
"doc_link": doc_link,
|
| 276 |
+
"format": "old",
|
| 277 |
+
}
|
| 278 |
+
)
|
| 279 |
+
return decisions
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class ALScraper(BaseScraper):
|
| 283 |
+
country = "Albanien"
|
| 284 |
+
|
| 285 |
+
def scrape(
|
| 286 |
+
self,
|
| 287 |
+
start_date: date | None = None,
|
| 288 |
+
end_date: date | None = None,
|
| 289 |
+
) -> list[Case]:
|
| 290 |
+
session = requests.Session()
|
| 291 |
+
session.headers.update(
|
| 292 |
+
{"User-Agent": USER_AGENT, "Accept": "application/json"}
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
slugs = _list_bulletin_slugs(session)
|
| 296 |
+
log.info("AL discovered %d bulletins", len(slugs))
|
| 297 |
+
|
| 298 |
+
seen: set[str] = set()
|
| 299 |
+
cases: list[Case] = []
|
| 300 |
+
for info in slugs:
|
| 301 |
+
raw_html = _fetch_bulletin_html(session, info["slug"])
|
| 302 |
+
time.sleep(DELAY_SECONDS)
|
| 303 |
+
if not raw_html:
|
| 304 |
+
continue
|
| 305 |
+
decisions = _parse_decisions(raw_html, info["slug"], info["title"])
|
| 306 |
+
log.info("AL %s: %d decisions", info["slug"], len(decisions))
|
| 307 |
+
|
| 308 |
+
for d in decisions:
|
| 309 |
+
decision_date: date | None = None
|
| 310 |
+
if d["iso_date"]:
|
| 311 |
+
try:
|
| 312 |
+
decision_date = date.fromisoformat(d["iso_date"])
|
| 313 |
+
except ValueError:
|
| 314 |
+
decision_date = None
|
| 315 |
+
if start_date and decision_date and decision_date < start_date:
|
| 316 |
+
continue
|
| 317 |
+
if end_date and decision_date and decision_date > end_date:
|
| 318 |
+
continue
|
| 319 |
+
|
| 320 |
+
case_id = d["decision_number"] or f"AL-{info['slug']}-{len(cases)}"
|
| 321 |
+
if case_id in seen:
|
| 322 |
+
continue
|
| 323 |
+
seen.add(case_id)
|
| 324 |
+
|
| 325 |
+
full_text = f"{d['header']}\n\n{d['body']}" if d["format"] == "new" else d["body"]
|
| 326 |
+
# Prefer the direct .doc URL on S3 (old-format bulletins expose
|
| 327 |
+
# it); fall back to the bulletin page for new-format entries.
|
| 328 |
+
link = d.get("doc_link") or f"{PUBLIC_BASE}/sq/lajme/buletini/{info['slug']}"
|
| 329 |
+
|
| 330 |
+
cases.append(
|
| 331 |
+
Case(
|
| 332 |
+
case_id=case_id,
|
| 333 |
+
link=link,
|
| 334 |
+
decision_date=decision_date,
|
| 335 |
+
jurisdiction="al",
|
| 336 |
+
language="sq",
|
| 337 |
+
full_text=full_text,
|
| 338 |
+
metadata={
|
| 339 |
+
"college": d["college"],
|
| 340 |
+
"decision_number": d["decision_number"],
|
| 341 |
+
"bulletin_slug": d["bulletin_slug"],
|
| 342 |
+
"bulletin_title": d["bulletin_title"],
|
| 343 |
+
"maxima": d["maxima"],
|
| 344 |
+
"keywords": d["keywords"],
|
| 345 |
+
"format": d["format"],
|
| 346 |
+
"doc_link": d.get("doc_link"),
|
| 347 |
+
},
|
| 348 |
+
)
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 352 |
+
log.info("Collected %d Albania cases", len(cases))
|
| 353 |
+
return cases
|
| 354 |
+
|
| 355 |
+
@staticmethod
|
| 356 |
+
def civil_filter(cases: list[Case]) -> list[Case]:
|
| 357 |
+
kept = [
|
| 358 |
+
c
|
| 359 |
+
for c in cases
|
| 360 |
+
if (c.metadata or {}).get("college") in {"civil", "united"}
|
| 361 |
+
]
|
| 362 |
+
log.info("AL civil_filter kept %d/%d", len(kept), len(cases))
|
| 363 |
+
return kept
|
legex/scrapers/am.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
import urllib.request
|
| 6 |
+
from datetime import date, datetime
|
| 7 |
+
|
| 8 |
+
from legex.models.base import Case
|
| 9 |
+
from legex.scrapers.base import BaseScraper
|
| 10 |
+
|
| 11 |
+
log = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
BASE = "https://www.cassationcourt.am/en/decisions/?chamber=2&page="
|
| 14 |
+
USER_AGENT = "FriendlyResearcher"
|
| 15 |
+
MAX_PAGES = 30
|
| 16 |
+
DELAY_SECONDS = 0.5
|
| 17 |
+
CIVIL_CHAMBER_LABEL = "Քաղաքացիական"
|
| 18 |
+
EMPTY_PAGE_MARKER = "Գրառումներ չկան"
|
| 19 |
+
|
| 20 |
+
_DATE_FMT_RE = re.compile(r"^\d{2}\.\d{2}\.\d{4}$")
|
| 21 |
+
_DIV_RE = re.compile(r"<div>(.*?)</div>", re.DOTALL)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _fetch_page(page: int) -> str | None:
|
| 25 |
+
url = BASE + str(page)
|
| 26 |
+
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
| 27 |
+
try:
|
| 28 |
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
| 29 |
+
return resp.read().decode("utf-8")
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f" ERROR page {page}: {e}", file=sys.stderr)
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _parse_decisions(html: str) -> list[tuple[str, str, str]]:
|
| 36 |
+
"""Extract (iso_date, link, case_number) triples from a listing page."""
|
| 37 |
+
results: list[tuple[str, str, str]] = []
|
| 38 |
+
for block in html.split("resultListBody")[1:]:
|
| 39 |
+
divs = _DIV_RE.findall(block)
|
| 40 |
+
if len(divs) >= 3 and divs[2].strip() == CIVIL_CHAMBER_LABEL:
|
| 41 |
+
date_str = divs[0].strip()
|
| 42 |
+
case_num = divs[1].strip()
|
| 43 |
+
if not _DATE_FMT_RE.match(date_str):
|
| 44 |
+
continue
|
| 45 |
+
try:
|
| 46 |
+
iso_date = datetime.strptime(date_str, "%d.%m.%Y").strftime("%Y-%m-%d")
|
| 47 |
+
except ValueError:
|
| 48 |
+
iso_date = date_str
|
| 49 |
+
case_anchor = case_num.replace("/", "-")
|
| 50 |
+
link = f"https://www.cassationcourt.am/en/decisions/?chamber=2&page=1#case-{case_anchor}"
|
| 51 |
+
results.append((iso_date, link, case_num))
|
| 52 |
+
return results
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class AMScraper(BaseScraper):
|
| 56 |
+
country = "Armenien"
|
| 57 |
+
|
| 58 |
+
def scrape(
|
| 59 |
+
self,
|
| 60 |
+
start_date: date | None = None,
|
| 61 |
+
end_date: date | None = None,
|
| 62 |
+
) -> list[Case]:
|
| 63 |
+
all_decisions: list[tuple[str, str, str]] = []
|
| 64 |
+
for page in range(1, MAX_PAGES + 1):
|
| 65 |
+
log.info("AM fetching page %d", page)
|
| 66 |
+
html = _fetch_page(page)
|
| 67 |
+
if html is None:
|
| 68 |
+
log.warning("AM page %d failed; stopping", page)
|
| 69 |
+
break
|
| 70 |
+
decisions = _parse_decisions(html)
|
| 71 |
+
if not decisions:
|
| 72 |
+
if EMPTY_PAGE_MARKER in html:
|
| 73 |
+
log.info("AM no records on page %d; stopping", page)
|
| 74 |
+
break
|
| 75 |
+
log.info("AM no decisions parsed on page %d; continuing", page)
|
| 76 |
+
continue
|
| 77 |
+
log.info("AM page %d: %d decisions", page, len(decisions))
|
| 78 |
+
all_decisions.extend(decisions)
|
| 79 |
+
time.sleep(DELAY_SECONDS)
|
| 80 |
+
|
| 81 |
+
# Dedupe by case number, preserving first occurrence (newest first).
|
| 82 |
+
seen: set[str] = set()
|
| 83 |
+
unique: list[tuple[str, str, str]] = []
|
| 84 |
+
for entry in all_decisions:
|
| 85 |
+
_, _, case_num = entry
|
| 86 |
+
if case_num in seen:
|
| 87 |
+
continue
|
| 88 |
+
seen.add(case_num)
|
| 89 |
+
unique.append(entry)
|
| 90 |
+
log.info("AM total unique civil decisions: %d", len(unique))
|
| 91 |
+
|
| 92 |
+
cases: list[Case] = []
|
| 93 |
+
for iso_date, link, case_num in unique:
|
| 94 |
+
decision_date: date | None = None
|
| 95 |
+
try:
|
| 96 |
+
decision_date = date.fromisoformat(iso_date)
|
| 97 |
+
except ValueError:
|
| 98 |
+
decision_date = None
|
| 99 |
+
|
| 100 |
+
if start_date and decision_date and decision_date < start_date:
|
| 101 |
+
continue
|
| 102 |
+
if end_date and decision_date and decision_date > end_date:
|
| 103 |
+
continue
|
| 104 |
+
|
| 105 |
+
cases.append(Case(
|
| 106 |
+
case_id=case_num,
|
| 107 |
+
link=link,
|
| 108 |
+
decision_date=decision_date,
|
| 109 |
+
jurisdiction="am",
|
| 110 |
+
language="hy",
|
| 111 |
+
full_text=None,
|
| 112 |
+
metadata={"chamber": "civil"},
|
| 113 |
+
))
|
| 114 |
+
|
| 115 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 116 |
+
log.info("Collected %d Armenia cases", len(cases))
|
| 117 |
+
return cases
|
legex/scrapers/at.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Austria OGH (Oberster Gerichtshof) via RIS OGD API v2.6.
|
| 2 |
+
|
| 3 |
+
Endpoint and field schema discovered via the worldwidelaw/legal-sources project
|
| 4 |
+
(AGPL-3.0). We reimplement the scraping based on the API endpoint (link below).
|
| 5 |
+
|
| 6 |
+
Docs: https://data.bka.gv.at/ris/ogd/v2.6/Documents/Dokumentation_OGD-RIS_API.pdf
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import logging
|
| 10 |
+
import re
|
| 11 |
+
import time
|
| 12 |
+
from datetime import date
|
| 13 |
+
from typing import Any
|
| 14 |
+
from xml.etree import ElementTree as ET
|
| 15 |
+
|
| 16 |
+
import requests
|
| 17 |
+
|
| 18 |
+
from legex.models.base import Case
|
| 19 |
+
from legex.scrapers.base import BaseScraper
|
| 20 |
+
|
| 21 |
+
log = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
API_URL = "https://data.bka.gv.at/ris/api/v2.6/Judikatur"
|
| 24 |
+
RIS_DOCUMENTS_URL = "https://www.ris.bka.gv.at/Dokumente/Justiz"
|
| 25 |
+
PAGE_SIZE = 100
|
| 26 |
+
RATE_DELAY_SECONDS = 1.0
|
| 27 |
+
ENRICH_DELAY_SECONDS = 0.4
|
| 28 |
+
USER_AGENT = "legex-research (open-data, friendly)"
|
| 29 |
+
_DOC_ID_DATE_RE = re.compile(r"^JJ[RT]_(\d{8})_")
|
| 30 |
+
_JJT_NUM_RE = re.compile(r"(JJT_\d{8}_[A-Z0-9_]+)")
|
| 31 |
+
_WS_RE = re.compile(r"\s+")
|
| 32 |
+
_NORM_GZ_RE = re.compile(r"\s+")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _parse_doc_id_date(doc_id: str) -> date | None:
|
| 36 |
+
match = _DOC_ID_DATE_RE.match(doc_id or "")
|
| 37 |
+
if not match:
|
| 38 |
+
return None
|
| 39 |
+
try:
|
| 40 |
+
return date.fromisoformat(
|
| 41 |
+
f"{match.group(1)[:4]}-{match.group(1)[4:6]}-{match.group(1)[6:8]}"
|
| 42 |
+
)
|
| 43 |
+
except ValueError:
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _as_text(obj: Any) -> str:
|
| 48 |
+
"""Flatten RIS `{"item": value}` / list / scalar into a single string."""
|
| 49 |
+
if obj in (None, "", {}):
|
| 50 |
+
return ""
|
| 51 |
+
if isinstance(obj, str):
|
| 52 |
+
return obj
|
| 53 |
+
if isinstance(obj, dict):
|
| 54 |
+
item = obj.get("item", obj.get("#text", ""))
|
| 55 |
+
return _as_text(item)
|
| 56 |
+
if isinstance(obj, list):
|
| 57 |
+
return " | ".join(_as_text(x) for x in obj if x)
|
| 58 |
+
return str(obj)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _first_geschaeftszahl(value: Any) -> str:
|
| 62 |
+
text = _as_text(value)
|
| 63 |
+
for sep in (";", "|"):
|
| 64 |
+
if sep in text:
|
| 65 |
+
text = text.split(sep, 1)[0]
|
| 66 |
+
return text.strip()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class ATScraper(BaseScraper):
|
| 70 |
+
country = "Österreich"
|
| 71 |
+
|
| 72 |
+
def scrape(
|
| 73 |
+
self,
|
| 74 |
+
start_date: date | None = None,
|
| 75 |
+
end_date: date | None = None,
|
| 76 |
+
) -> list[Case]:
|
| 77 |
+
params: dict[str, str] = {
|
| 78 |
+
"Applikation": "Justiz",
|
| 79 |
+
"Gericht": "OGH",
|
| 80 |
+
"DokumenteProSeite": "OneHundred",
|
| 81 |
+
}
|
| 82 |
+
if start_date or end_date:
|
| 83 |
+
params["Entscheidungsdatum.SucheNachDatum"] = "true"
|
| 84 |
+
if start_date:
|
| 85 |
+
params["EntscheidungsdatumVon"] = start_date.isoformat()
|
| 86 |
+
if end_date:
|
| 87 |
+
params["EntscheidungsdatumBis"] = end_date.isoformat()
|
| 88 |
+
|
| 89 |
+
cases: list[Case] = []
|
| 90 |
+
seen_ids: set[str] = set()
|
| 91 |
+
page = 1
|
| 92 |
+
total: int | None = None
|
| 93 |
+
session = requests.Session()
|
| 94 |
+
session.headers.update({"User-Agent": USER_AGENT, "Accept": "application/json"})
|
| 95 |
+
|
| 96 |
+
while True:
|
| 97 |
+
params["Seitennummer"] = str(page)
|
| 98 |
+
try:
|
| 99 |
+
resp = session.get(API_URL, params=params, timeout=60)
|
| 100 |
+
resp.raise_for_status()
|
| 101 |
+
data = resp.json()
|
| 102 |
+
except Exception as e:
|
| 103 |
+
log.warning("AT page %d failed (%s); stopping", page, e)
|
| 104 |
+
break
|
| 105 |
+
|
| 106 |
+
results = data.get("OgdSearchResult", {}).get("OgdDocumentResults", {})
|
| 107 |
+
if total is None:
|
| 108 |
+
hits_text = results.get("Hits", {}).get("#text", "0")
|
| 109 |
+
try:
|
| 110 |
+
total = int(hits_text)
|
| 111 |
+
except ValueError:
|
| 112 |
+
total = 0
|
| 113 |
+
log.info("AT total OGH hits: %d", total)
|
| 114 |
+
if total == 0:
|
| 115 |
+
break
|
| 116 |
+
|
| 117 |
+
docs = results.get("OgdDocumentReference", [])
|
| 118 |
+
if not isinstance(docs, list):
|
| 119 |
+
docs = [docs] if docs else []
|
| 120 |
+
if not docs:
|
| 121 |
+
break
|
| 122 |
+
|
| 123 |
+
for doc in docs:
|
| 124 |
+
case = self._to_case(doc.get("Data", {}))
|
| 125 |
+
if case is None or case.case_id in seen_ids:
|
| 126 |
+
continue
|
| 127 |
+
# Server filter applies to most recent citation date, so include
|
| 128 |
+
# RS that ride along on a recent citation, drop them here.
|
| 129 |
+
if start_date and case.decision_date and case.decision_date < start_date:
|
| 130 |
+
continue
|
| 131 |
+
if end_date and case.decision_date and case.decision_date > end_date:
|
| 132 |
+
continue
|
| 133 |
+
seen_ids.add(case.case_id)
|
| 134 |
+
cases.append(case)
|
| 135 |
+
|
| 136 |
+
fetched = page * PAGE_SIZE
|
| 137 |
+
log.info("AT page %d: %d docs (%d/%d total)", page, len(docs), min(fetched, total), total)
|
| 138 |
+
if fetched >= total:
|
| 139 |
+
break
|
| 140 |
+
page += 1
|
| 141 |
+
time.sleep(RATE_DELAY_SECONDS)
|
| 142 |
+
|
| 143 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 144 |
+
log.info("Collected %d Austria cases", len(cases))
|
| 145 |
+
return cases
|
| 146 |
+
|
| 147 |
+
@staticmethod
|
| 148 |
+
def _to_case(data: dict[str, Any]) -> Case | None:
|
| 149 |
+
meta = data.get("Metadaten", {})
|
| 150 |
+
tech = meta.get("Technisch", {})
|
| 151 |
+
allg = meta.get("Allgemein", {})
|
| 152 |
+
jud = meta.get("Judikatur", {})
|
| 153 |
+
justiz = jud.get("Justiz", {})
|
| 154 |
+
|
| 155 |
+
doc_id = tech.get("ID", "") or ""
|
| 156 |
+
case_id = _first_geschaeftszahl(jud.get("Geschaeftszahl"))
|
| 157 |
+
if not case_id:
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
link = allg.get("DokumentUrl") or ""
|
| 161 |
+
decision_date = _parse_doc_id_date(doc_id)
|
| 162 |
+
latest_citation: str | None = None
|
| 163 |
+
raw_date = jud.get("Entscheidungsdatum")
|
| 164 |
+
if isinstance(raw_date, str) and raw_date:
|
| 165 |
+
latest_citation = raw_date[:10]
|
| 166 |
+
|
| 167 |
+
return Case(
|
| 168 |
+
case_id=case_id,
|
| 169 |
+
link=link,
|
| 170 |
+
decision_date=decision_date,
|
| 171 |
+
jurisdiction="at",
|
| 172 |
+
language="de",
|
| 173 |
+
full_text=None,
|
| 174 |
+
metadata={
|
| 175 |
+
"doc_id": doc_id,
|
| 176 |
+
"ecli": _as_text(jud.get("EuropeanCaseLawIdentifier")),
|
| 177 |
+
"dokumenttyp": _as_text(jud.get("Dokumenttyp")),
|
| 178 |
+
"rechtsgebiete": _as_text(justiz.get("Rechtsgebiete")),
|
| 179 |
+
"rechtssatznummern": _as_text(justiz.get("Rechtssatznummern")),
|
| 180 |
+
"gericht": _as_text(justiz.get("Gericht")),
|
| 181 |
+
"normen": _as_text(jud.get("Normen")),
|
| 182 |
+
"latest_citation_date": latest_citation,
|
| 183 |
+
},
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
@staticmethod
|
| 187 |
+
def civil_filter(cases: list[Case]) -> list[Case]:
|
| 188 |
+
# Justiz application at the OGH classifies cases by Rechtsgebiete. "Zivilrecht"
|
| 189 |
+
# is civil law. Some entries combine fields like "Zivilrecht | Arbeitsrecht".
|
| 190 |
+
return [
|
| 191 |
+
c for c in cases
|
| 192 |
+
if "zivilrecht" in (c.metadata or {}).get("rechtsgebiete", "").lower()
|
| 193 |
+
]
|
| 194 |
+
|
| 195 |
+
@classmethod
|
| 196 |
+
def enrich(cls, cases: list[Case]) -> list[Case]:
|
| 197 |
+
"""Download the JJT decision XML for each sampled case and set full_text.
|
| 198 |
+
|
| 199 |
+
For each Rechtssatz we re-query the RIS API by its Dokumentnummer to
|
| 200 |
+
recover the `Entscheidungstexte` list, pick the entry whose
|
| 201 |
+
Geschaeftszahl matches our `case_id`, then fetch that JJT's XML and
|
| 202 |
+
extract the plain text.
|
| 203 |
+
"""
|
| 204 |
+
session = requests.Session()
|
| 205 |
+
session.headers.update({"User-Agent": USER_AGENT, "Accept": "application/json"})
|
| 206 |
+
|
| 207 |
+
enriched: list[Case] = []
|
| 208 |
+
for i, case in enumerate(cases, 1):
|
| 209 |
+
if case.full_text:
|
| 210 |
+
enriched.append(case)
|
| 211 |
+
continue
|
| 212 |
+
text, jjt = cls._fetch_full_text(session, case)
|
| 213 |
+
if text:
|
| 214 |
+
meta = dict(case.metadata or {})
|
| 215 |
+
if jjt:
|
| 216 |
+
meta["text_doc_num"] = jjt
|
| 217 |
+
enriched.append(case.model_copy(update={"full_text": text, "metadata": meta}))
|
| 218 |
+
log.info("AT enrich %d/%d %s: %d chars", i, len(cases), case.case_id, len(text))
|
| 219 |
+
else:
|
| 220 |
+
enriched.append(case)
|
| 221 |
+
log.warning("AT enrich %d/%d %s: no text", i, len(cases), case.case_id)
|
| 222 |
+
time.sleep(ENRICH_DELAY_SECONDS)
|
| 223 |
+
return enriched
|
| 224 |
+
|
| 225 |
+
@classmethod
|
| 226 |
+
def _fetch_full_text(
|
| 227 |
+
cls, session: requests.Session, case: Case
|
| 228 |
+
) -> tuple[str | None, str | None]:
|
| 229 |
+
doc_id = (case.metadata or {}).get("doc_id") or ""
|
| 230 |
+
if not doc_id:
|
| 231 |
+
return None, None
|
| 232 |
+
jjt = cls._lookup_jjt(session, doc_id, case.case_id or "")
|
| 233 |
+
if not jjt:
|
| 234 |
+
return None, None
|
| 235 |
+
xml_url = f"{RIS_DOCUMENTS_URL}/{jjt}/{jjt}.xml"
|
| 236 |
+
try:
|
| 237 |
+
resp = session.get(xml_url, timeout=60)
|
| 238 |
+
resp.raise_for_status()
|
| 239 |
+
return _extract_text_from_xml(resp.content), jjt
|
| 240 |
+
except Exception as e:
|
| 241 |
+
log.warning("AT JJT %s XML fetch failed (%s)", jjt, e)
|
| 242 |
+
return None, jjt
|
| 243 |
+
|
| 244 |
+
@staticmethod
|
| 245 |
+
def _lookup_jjt(session: requests.Session, rs_doc_id: str, case_id: str) -> str | None:
|
| 246 |
+
# Re-query the RS to get its Entscheidungstexte list, then match to case_id.
|
| 247 |
+
# The Suchworte free-text param actually filters, Dokumentnummer does not.
|
| 248 |
+
params = {"Applikation": "Justiz", "Suchworte": rs_doc_id}
|
| 249 |
+
try:
|
| 250 |
+
resp = session.get(API_URL, params=params, timeout=60)
|
| 251 |
+
resp.raise_for_status()
|
| 252 |
+
data = resp.json()
|
| 253 |
+
except Exception as e:
|
| 254 |
+
log.warning("AT RS %s lookup failed (%s)", rs_doc_id, e)
|
| 255 |
+
return None
|
| 256 |
+
|
| 257 |
+
docs = data.get("OgdSearchResult", {}).get("OgdDocumentResults", {}).get(
|
| 258 |
+
"OgdDocumentReference", []
|
| 259 |
+
)
|
| 260 |
+
if not isinstance(docs, list):
|
| 261 |
+
docs = [docs] if docs else []
|
| 262 |
+
if not docs:
|
| 263 |
+
return None
|
| 264 |
+
|
| 265 |
+
et = (
|
| 266 |
+
docs[0]
|
| 267 |
+
.get("Data", {})
|
| 268 |
+
.get("Metadaten", {})
|
| 269 |
+
.get("Judikatur", {})
|
| 270 |
+
.get("Justiz", {})
|
| 271 |
+
.get("Entscheidungstexte", {})
|
| 272 |
+
)
|
| 273 |
+
items = et.get("item", [])
|
| 274 |
+
if isinstance(items, dict):
|
| 275 |
+
items = [items]
|
| 276 |
+
if not items:
|
| 277 |
+
return None
|
| 278 |
+
|
| 279 |
+
norm_case = _norm_gz(case_id)
|
| 280 |
+
for item in items:
|
| 281 |
+
gz = _norm_gz(item.get("Geschaeftszahl", ""))
|
| 282 |
+
if gz == norm_case:
|
| 283 |
+
m = _JJT_NUM_RE.search(item.get("DokumentUrl", ""))
|
| 284 |
+
if m:
|
| 285 |
+
return m.group(1)
|
| 286 |
+
|
| 287 |
+
# Fallback: first Entscheidungstext.
|
| 288 |
+
first = items[0]
|
| 289 |
+
m = _JJT_NUM_RE.search(first.get("DokumentUrl", ""))
|
| 290 |
+
return m.group(1) if m else None
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def _norm_gz(value: str) -> str:
|
| 294 |
+
"""RIS prints `1 Ob 108/24z` in some payloads and `1Ob108/24z` in others."""
|
| 295 |
+
return _NORM_GZ_RE.sub("", value or "").lower()
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def _extract_text_from_xml(content: bytes) -> str | None:
|
| 299 |
+
try:
|
| 300 |
+
root = ET.fromstring(content)
|
| 301 |
+
except ET.ParseError as e:
|
| 302 |
+
log.warning("AT XML parse failed (%s)", e)
|
| 303 |
+
return None
|
| 304 |
+
parts: list[str] = []
|
| 305 |
+
for elem in root.iter():
|
| 306 |
+
if elem.text and elem.text.strip():
|
| 307 |
+
parts.append(elem.text.strip())
|
| 308 |
+
if not parts:
|
| 309 |
+
return None
|
| 310 |
+
return _WS_RE.sub(" ", " ".join(parts)).strip()
|
legex/scrapers/au.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import re
|
| 3 |
+
from datetime import date
|
| 4 |
+
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
|
| 7 |
+
from legex.models.base import Case
|
| 8 |
+
from legex.scrapers.base import BaseScraper
|
| 9 |
+
|
| 10 |
+
DATASET_NAME = "isaacus/high-court-of-australia-cases"
|
| 11 |
+
log = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
_RE_CITATION = re.compile(r"\[(\d{4})\]\s*HCA\s*(\d+)")
|
| 14 |
+
# HCA docket, for example"S94/2025", "P7/2024", "B15/2024". Registry letters seen: S/B/C/P/M/H/D.
|
| 15 |
+
_RE_DOCKET = re.compile(r"\b([SBCPMHD])(\d+)/(\d{4})\b")
|
| 16 |
+
HCOURT_URL_TEMPLATE = "https://www.hcourt.gov.au/cases-and-judgments/cases/decided/case-{letter}{num}{year}"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class AUScraper(BaseScraper):
|
| 20 |
+
country = "Australia"
|
| 21 |
+
|
| 22 |
+
def scrape(
|
| 23 |
+
self,
|
| 24 |
+
start_date: date | None = None,
|
| 25 |
+
end_date: date | None = None,
|
| 26 |
+
) -> list[Case]:
|
| 27 |
+
log.info(f"Loading {DATASET_NAME} …")
|
| 28 |
+
dataset = load_dataset(DATASET_NAME, split="corpus")
|
| 29 |
+
cases = [self._row_to_case(row) for row in dataset]
|
| 30 |
+
cases = [c for c in cases if c is not None]
|
| 31 |
+
|
| 32 |
+
if start_date or end_date:
|
| 33 |
+
cases = [
|
| 34 |
+
c for c in cases
|
| 35 |
+
if (start_date is None or c.decision_date >= start_date)
|
| 36 |
+
and (end_date is None or c.decision_date <= end_date)
|
| 37 |
+
]
|
| 38 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 39 |
+
log.info(f"{len(cases)} cases after filtering")
|
| 40 |
+
return cases
|
| 41 |
+
|
| 42 |
+
@staticmethod
|
| 43 |
+
def _row_to_case(row: dict) -> Case | None:
|
| 44 |
+
raw_date = row.get("date")
|
| 45 |
+
if not raw_date:
|
| 46 |
+
return None
|
| 47 |
+
citation = row.get("citation") or ""
|
| 48 |
+
m = _RE_CITATION.search(citation)
|
| 49 |
+
case_id = f"[{m.group(1)}] HCA {m.group(2)}" if m else citation or None
|
| 50 |
+
decision_date = raw_date.date() if hasattr(raw_date, "date") else date.fromisoformat(str(raw_date)[:10])
|
| 51 |
+
|
| 52 |
+
# We prefer the authoritative hcourt.gov.au per-case URL, built from the docket
|
| 53 |
+
# number found in the first 2000 chars of the decision text. This gives around 95% hit rate.
|
| 54 |
+
# For the remaining ~5% with no docket match we fall back to the dataset URL.
|
| 55 |
+
text = row.get("text") or ""
|
| 56 |
+
d = _RE_DOCKET.search(text[:2000])
|
| 57 |
+
if d:
|
| 58 |
+
docket = f"{d.group(1)}{d.group(2)}/{d.group(3)}"
|
| 59 |
+
link = HCOURT_URL_TEMPLATE.format(
|
| 60 |
+
letter=d.group(1).lower(), num=d.group(2), year=d.group(3)
|
| 61 |
+
)
|
| 62 |
+
else:
|
| 63 |
+
docket = ""
|
| 64 |
+
link = row.get("url")
|
| 65 |
+
|
| 66 |
+
return Case(
|
| 67 |
+
case_id=case_id,
|
| 68 |
+
link=link,
|
| 69 |
+
decision_date=decision_date,
|
| 70 |
+
jurisdiction="au",
|
| 71 |
+
language="en",
|
| 72 |
+
full_text=text or None,
|
| 73 |
+
metadata={"citation": citation, "docket": docket},
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
@staticmethod
|
| 77 |
+
def civil_filter(cases: list[Case]) -> list[Case]:
|
| 78 |
+
# HCA is mixed civil/criminal/constitutional. Exclude the explicit criminal
|
| 79 |
+
# pattern "v The King" / "v The Queen", everything else we treat as civil.
|
| 80 |
+
return [
|
| 81 |
+
c for c in cases
|
| 82 |
+
if " v The King" not in (c.metadata or {}).get("citation", "")
|
| 83 |
+
and " v The Queen" not in (c.metadata or {}).get("citation", "")
|
| 84 |
+
]
|
legex/scrapers/base.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from datetime import date
|
| 3 |
+
|
| 4 |
+
from legex.models.base import Case
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class BaseScraper(ABC):
|
| 8 |
+
country: str
|
| 9 |
+
|
| 10 |
+
@abstractmethod
|
| 11 |
+
def scrape(
|
| 12 |
+
self,
|
| 13 |
+
start_date: date | None = None,
|
| 14 |
+
end_date: date | None = None,
|
| 15 |
+
) -> list[Case]:
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
@staticmethod
|
| 19 |
+
def civil_filter(cases: list[Case]) -> list[Case]:
|
| 20 |
+
return list(cases)
|
| 21 |
+
|
| 22 |
+
@staticmethod
|
| 23 |
+
def enrich(cases: list[Case]) -> list[Case]:
|
| 24 |
+
"""Post-sampling enrichment hook — runs on the 130 sampled cases only.
|
| 25 |
+
|
| 26 |
+
Default is a no-op. Scrapers that need expensive per-case work
|
| 27 |
+
(e.g. downloading PDFs and extracting text) override this so the cost is
|
| 28 |
+
paid only for the sampled set, not the full corpus.
|
| 29 |
+
"""
|
| 30 |
+
return list(cases)
|
legex/scrapers/be.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
import re
|
| 5 |
+
import time
|
| 6 |
+
from datetime import date
|
| 7 |
+
from html import unescape
|
| 8 |
+
from urllib.parse import urljoin
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
from dateutil import parser as dateutil_parser
|
| 12 |
+
|
| 13 |
+
from legex.models.base import Case
|
| 14 |
+
from legex.scrapers.base import BaseScraper
|
| 15 |
+
|
| 16 |
+
# Data source: https://juportal.be/zoekmachine/zoekformulier
|
| 17 |
+
# We submit the official search form with civil case-number prefix "C." and
|
| 18 |
+
# page through server-side "next_page" form actions.
|
| 19 |
+
|
| 20 |
+
log = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
BASE_URL = "https://juportal.be"
|
| 23 |
+
SEARCH_FORM_URL = f"{BASE_URL}/zoekmachine/zoekformulier"
|
| 24 |
+
SEARCH_RESULTS_URL = f"{BASE_URL}/zoekmachine/zoekresultaten"
|
| 25 |
+
DELAY_SECONDS = 3
|
| 26 |
+
RETRY_DELAY_SECONDS = 30
|
| 27 |
+
MAX_PAGES_PER_QUERY = 300
|
| 28 |
+
|
| 29 |
+
_RE_FORM_TOKEN = re.compile(r'name=["\']TOKEN["\'][^>]*value=["\']([^"\']*)', re.IGNORECASE)
|
| 30 |
+
_RE_ACTION_VALUE = re.compile(
|
| 31 |
+
r'<button[^>]*name=["\']action["\'][^>]*value=["\']([^"\']*)',
|
| 32 |
+
re.IGNORECASE,
|
| 33 |
+
)
|
| 34 |
+
_RE_NEXT_VALUE = re.compile(
|
| 35 |
+
r'<button[^>]*name=["\']next_page["\'][^>]*value=["\']([^"\']*)',
|
| 36 |
+
re.IGNORECASE,
|
| 37 |
+
)
|
| 38 |
+
_RE_CONTENT_LINK = re.compile(r'href=["\'](/content/ECLI:BE:CASS:[^"\']+)["\']', re.IGNORECASE)
|
| 39 |
+
_RE_ROLE = re.compile(r"Rolnummer:\s*([A-Z]\.[0-9]{2}\.[0-9]{4}\.[A-Z])", re.IGNORECASE)
|
| 40 |
+
_RE_DATE = re.compile(r"Vonnis/arrest van\s+([0-9]{1,2}\s+[A-Za-z]+\s+[0-9]{4})", re.IGNORECASE)
|
| 41 |
+
_RE_ECLI = re.compile(r"(ECLI:BE:CASS:[A-Z0-9:.]+)")
|
| 42 |
+
_RE_RESULT_ROW_META = re.compile(
|
| 43 |
+
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])",
|
| 44 |
+
re.IGNORECASE,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _parse_date(text: str | None) -> date | None:
|
| 49 |
+
if not text:
|
| 50 |
+
return None
|
| 51 |
+
cleaned = text.strip()
|
| 52 |
+
try:
|
| 53 |
+
return date.fromisoformat(cleaned)
|
| 54 |
+
except ValueError:
|
| 55 |
+
pass
|
| 56 |
+
try:
|
| 57 |
+
return dateutil_parser.parse(cleaned, dayfirst=True).date()
|
| 58 |
+
except (ValueError, OverflowError, dateutil_parser.ParserError):
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _extract_token(html: str) -> str | None:
|
| 63 |
+
match = _RE_FORM_TOKEN.search(html)
|
| 64 |
+
return match.group(1) if match else None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _extract_action_value(html: str) -> str | None:
|
| 68 |
+
match = _RE_ACTION_VALUE.search(html)
|
| 69 |
+
return match.group(1) if match else None
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _extract_next_value(html: str) -> str | None:
|
| 73 |
+
match = _RE_NEXT_VALUE.search(html)
|
| 74 |
+
return match.group(1) if match else None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _extract_result_links(html: str) -> list[str]:
|
| 78 |
+
links = []
|
| 79 |
+
seen: set[str] = set()
|
| 80 |
+
for raw_link in _RE_CONTENT_LINK.findall(html):
|
| 81 |
+
clean = raw_link.split("#", 1)[0]
|
| 82 |
+
if ":ARR." not in clean:
|
| 83 |
+
continue
|
| 84 |
+
if clean in seen:
|
| 85 |
+
continue
|
| 86 |
+
seen.add(clean)
|
| 87 |
+
links.append(urljoin(BASE_URL, clean))
|
| 88 |
+
return links
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _extract_result_cases(html: str) -> list[Case]:
|
| 92 |
+
cases: list[Case] = []
|
| 93 |
+
seen: set[str] = set()
|
| 94 |
+
chunks = html.split("<tr>")
|
| 95 |
+
for chunk in chunks:
|
| 96 |
+
link_match = _RE_CONTENT_LINK.search(chunk)
|
| 97 |
+
if not link_match:
|
| 98 |
+
continue
|
| 99 |
+
rel = link_match.group(1).split("#", 1)[0]
|
| 100 |
+
if ":ARR." not in rel:
|
| 101 |
+
continue
|
| 102 |
+
link = urljoin(BASE_URL, rel)
|
| 103 |
+
if link in seen:
|
| 104 |
+
continue
|
| 105 |
+
seen.add(link)
|
| 106 |
+
|
| 107 |
+
ecli_match = _RE_ECLI.search(chunk)
|
| 108 |
+
meta_match = _RE_RESULT_ROW_META.search(unescape(re.sub(r"<[^>]+>", " ", chunk)))
|
| 109 |
+
if not meta_match:
|
| 110 |
+
continue
|
| 111 |
+
decision_date = _parse_date(meta_match.group(1))
|
| 112 |
+
case_id = meta_match.group(2).upper()
|
| 113 |
+
if not case_id.startswith("C."):
|
| 114 |
+
continue
|
| 115 |
+
|
| 116 |
+
cases.append(
|
| 117 |
+
Case(
|
| 118 |
+
case_id=case_id,
|
| 119 |
+
link=link,
|
| 120 |
+
decision_date=decision_date,
|
| 121 |
+
jurisdiction="be",
|
| 122 |
+
language="nl",
|
| 123 |
+
full_text=None,
|
| 124 |
+
metadata={
|
| 125 |
+
"ecli": (ecli_match.group(1).upper() if ecli_match else None),
|
| 126 |
+
"source": "juportal.be",
|
| 127 |
+
},
|
| 128 |
+
)
|
| 129 |
+
)
|
| 130 |
+
return cases
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _extract_case_id(page_text: str) -> str | None:
|
| 134 |
+
match = _RE_ROLE.search(page_text)
|
| 135 |
+
return match.group(1).upper() if match else None
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _extract_ecli(page_text: str) -> str | None:
|
| 139 |
+
match = _RE_ECLI.search(page_text)
|
| 140 |
+
return match.group(1).upper() if match else None
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _extract_decision_date(page_text: str) -> date | None:
|
| 144 |
+
match = _RE_DATE.search(page_text)
|
| 145 |
+
return _parse_date(match.group(1) if match else None)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _extract_text(page_html: str) -> str | None:
|
| 149 |
+
text = unescape(re.sub(r"<[^>]+>", "\n", page_html))
|
| 150 |
+
lines = [line.strip() for line in text.splitlines()]
|
| 151 |
+
cleaned = [line for line in lines if line]
|
| 152 |
+
return "\n".join(cleaned) if cleaned else None
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class BEScraper(BaseScraper):
|
| 156 |
+
country = "Belgium"
|
| 157 |
+
|
| 158 |
+
def scrape(
|
| 159 |
+
self,
|
| 160 |
+
start_date: date | None = None,
|
| 161 |
+
end_date: date | None = None,
|
| 162 |
+
) -> list[Case]:
|
| 163 |
+
start = start_date or date(2015, 1, 1)
|
| 164 |
+
end = end_date or date.today()
|
| 165 |
+
cases: list[Case] = []
|
| 166 |
+
seen: set[str] = set()
|
| 167 |
+
session = requests.Session()
|
| 168 |
+
|
| 169 |
+
for year in range(start.year, end.year + 1):
|
| 170 |
+
year_start = max(start, date(year, 1, 1))
|
| 171 |
+
year_end = min(end, date(year, 12, 31))
|
| 172 |
+
if year_start > year_end:
|
| 173 |
+
continue
|
| 174 |
+
year_cases = self._scrape_year(session, year_start, year_end)
|
| 175 |
+
for case in year_cases:
|
| 176 |
+
if not case.link or case.link in seen:
|
| 177 |
+
continue
|
| 178 |
+
seen.add(case.link)
|
| 179 |
+
cases.append(case)
|
| 180 |
+
|
| 181 |
+
return cases
|
| 182 |
+
|
| 183 |
+
def _scrape_year(
|
| 184 |
+
self,
|
| 185 |
+
session: requests.Session,
|
| 186 |
+
start_date: date,
|
| 187 |
+
end_date: date,
|
| 188 |
+
) -> list[Case]:
|
| 189 |
+
log.info("Belgium %s to %s", start_date.isoformat(), end_date.isoformat())
|
| 190 |
+
form_html = self._fetch_text(session, SEARCH_FORM_URL)
|
| 191 |
+
if form_html is None:
|
| 192 |
+
return []
|
| 193 |
+
token = _extract_token(form_html)
|
| 194 |
+
action_value = _extract_action_value(form_html)
|
| 195 |
+
if not token or not action_value:
|
| 196 |
+
return []
|
| 197 |
+
|
| 198 |
+
payload = {
|
| 199 |
+
"TOKEN": token,
|
| 200 |
+
"action": action_value,
|
| 201 |
+
"TRECHNOROLE": "C.",
|
| 202 |
+
"TRECHDECISIONDE": start_date.isoformat(),
|
| 203 |
+
"TRECHDECISIONA": end_date.isoformat(),
|
| 204 |
+
"TRECHNPPAGE": "50",
|
| 205 |
+
"TRECHORDER": "DATEDEC",
|
| 206 |
+
"TRECHDESCASC": "DESC",
|
| 207 |
+
"TRECHOPER": "AND",
|
| 208 |
+
"TRECHLIMIT": "25000",
|
| 209 |
+
"TRECHMODE": "SIMPLE",
|
| 210 |
+
"TRECHSCORE": "1",
|
| 211 |
+
"TRECHSHOWFICHES": "fiches",
|
| 212 |
+
}
|
| 213 |
+
page_html = self._post_text(session, SEARCH_FORM_URL, payload)
|
| 214 |
+
if page_html is None:
|
| 215 |
+
return []
|
| 216 |
+
|
| 217 |
+
results: list[Case] = []
|
| 218 |
+
seen_links: set[str] = set()
|
| 219 |
+
for page_idx in range(1, MAX_PAGES_PER_QUERY + 1):
|
| 220 |
+
links = _extract_result_links(page_html)
|
| 221 |
+
if not links:
|
| 222 |
+
break
|
| 223 |
+
log.info("Belgium page %d: %d decision links", page_idx, len(links))
|
| 224 |
+
page_cases = _extract_result_cases(page_html)
|
| 225 |
+
for case in page_cases:
|
| 226 |
+
if not case.link or case.link in seen_links:
|
| 227 |
+
continue
|
| 228 |
+
seen_links.add(case.link)
|
| 229 |
+
results.append(case)
|
| 230 |
+
|
| 231 |
+
next_value = _extract_next_value(page_html)
|
| 232 |
+
next_token = _extract_token(page_html)
|
| 233 |
+
if not next_value or not next_token:
|
| 234 |
+
break
|
| 235 |
+
time.sleep(DELAY_SECONDS)
|
| 236 |
+
page_html = self._post_text(
|
| 237 |
+
session,
|
| 238 |
+
SEARCH_RESULTS_URL,
|
| 239 |
+
{"TOKEN": next_token, "next_page": next_value},
|
| 240 |
+
)
|
| 241 |
+
if page_html is None:
|
| 242 |
+
break
|
| 243 |
+
|
| 244 |
+
return [
|
| 245 |
+
c for c in results
|
| 246 |
+
if c.decision_date is not None
|
| 247 |
+
and start_date <= c.decision_date <= end_date
|
| 248 |
+
]
|
| 249 |
+
|
| 250 |
+
def _fetch_case(self, link: str) -> Case | None:
|
| 251 |
+
html = self._fetch_url_text(link)
|
| 252 |
+
if html is None:
|
| 253 |
+
return None
|
| 254 |
+
text = _extract_text(html)
|
| 255 |
+
if text is None:
|
| 256 |
+
return None
|
| 257 |
+
|
| 258 |
+
case_id = _extract_case_id(text)
|
| 259 |
+
if not case_id or not case_id.startswith("C."):
|
| 260 |
+
return None
|
| 261 |
+
|
| 262 |
+
decision_date = _extract_decision_date(text)
|
| 263 |
+
ecli = _extract_ecli(text)
|
| 264 |
+
return Case(
|
| 265 |
+
case_id=case_id,
|
| 266 |
+
link=link,
|
| 267 |
+
decision_date=decision_date,
|
| 268 |
+
jurisdiction="be",
|
| 269 |
+
language="nl",
|
| 270 |
+
full_text=text,
|
| 271 |
+
metadata={"ecli": ecli, "source": "juportal.be"} if ecli else {"source": "juportal.be"},
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
@staticmethod
|
| 275 |
+
def civil_filter(cases: list[Case]) -> list[Case]:
|
| 276 |
+
return [c for c in cases if (c.case_id or "").startswith("C.")]
|
| 277 |
+
|
| 278 |
+
def _fetch_text(self, session: requests.Session, url: str) -> str | None:
|
| 279 |
+
try:
|
| 280 |
+
response = session.get(url, timeout=30)
|
| 281 |
+
if response.status_code == 429:
|
| 282 |
+
time.sleep(RETRY_DELAY_SECONDS)
|
| 283 |
+
response = session.get(url, timeout=30)
|
| 284 |
+
if not response.ok:
|
| 285 |
+
return None
|
| 286 |
+
return response.text
|
| 287 |
+
except requests.RequestException:
|
| 288 |
+
return None
|
| 289 |
+
|
| 290 |
+
def _post_text(self, session: requests.Session, url: str, data: dict[str, str]) -> str | None:
|
| 291 |
+
try:
|
| 292 |
+
response = session.post(url, data=data, timeout=30)
|
| 293 |
+
if response.status_code == 429:
|
| 294 |
+
time.sleep(RETRY_DELAY_SECONDS)
|
| 295 |
+
response = session.post(url, data=data, timeout=30)
|
| 296 |
+
if not response.ok:
|
| 297 |
+
return None
|
| 298 |
+
return response.text
|
| 299 |
+
except requests.RequestException:
|
| 300 |
+
return None
|
| 301 |
+
|
legex/scrapers/ch.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import re
|
| 3 |
+
from datetime import date
|
| 4 |
+
from typing import Any
|
| 5 |
+
from urllib.parse import unquote
|
| 6 |
+
|
| 7 |
+
from datasets import load_dataset
|
| 8 |
+
|
| 9 |
+
from legex.models.base import Case
|
| 10 |
+
from legex.scrapers.base import BaseScraper
|
| 11 |
+
|
| 12 |
+
DATASET_NAME = "voilaj/swiss-caselaw"
|
| 13 |
+
log = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
_RE_JUMPCGI = re.compile(r"JumpCGI\?id=\d{2}\.\d{2}\.\d{4}_([0-9][A-Z])_(\d+)/(\d{4})")
|
| 16 |
+
_RE_AZA = re.compile(r"aza://\d{2}-\d{2}-\d{4}-([0-9][A-Z])_(\d+)-(\d{4})")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class CHScraper(BaseScraper):
|
| 20 |
+
country = "Schweiz"
|
| 21 |
+
|
| 22 |
+
def scrape(
|
| 23 |
+
self,
|
| 24 |
+
start_date: date | None = None,
|
| 25 |
+
end_date: date | None = None,
|
| 26 |
+
) -> list[Case]:
|
| 27 |
+
log.info(f"Loading bger shard from {DATASET_NAME} …")
|
| 28 |
+
dataset = load_dataset(DATASET_NAME, data_files="data/bger.parquet", split="train")
|
| 29 |
+
cases = self._to_cases(dataset)
|
| 30 |
+
|
| 31 |
+
if start_date or end_date:
|
| 32 |
+
cases = [
|
| 33 |
+
c for c in cases
|
| 34 |
+
if c.decision_date is not None
|
| 35 |
+
and (start_date is None or c.decision_date >= start_date)
|
| 36 |
+
and (end_date is None or c.decision_date <= end_date)
|
| 37 |
+
]
|
| 38 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 39 |
+
log.info(f"{len(cases)} cases after filtering")
|
| 40 |
+
return cases
|
| 41 |
+
|
| 42 |
+
def _to_cases(self, dataset: Any) -> list[Case]:
|
| 43 |
+
results: list[Case] = []
|
| 44 |
+
seen: set[str] = set()
|
| 45 |
+
for row in dataset:
|
| 46 |
+
link = (row.get("source_url") or "").strip()
|
| 47 |
+
if not link or link in seen:
|
| 48 |
+
continue
|
| 49 |
+
seen.add(link)
|
| 50 |
+
|
| 51 |
+
raw_date = row.get("decision_date")
|
| 52 |
+
decision_date = date.fromisoformat(raw_date) if raw_date else None
|
| 53 |
+
case_id, chamber, division = self.parse_case_id(link)
|
| 54 |
+
|
| 55 |
+
metadata: dict[str, Any] = {
|
| 56 |
+
k: v for k, v in row.items()
|
| 57 |
+
if k not in ("source_url", "decision_date", "language", "full_text") and v is not None
|
| 58 |
+
}
|
| 59 |
+
if chamber is not None:
|
| 60 |
+
metadata["chamber"] = chamber
|
| 61 |
+
metadata["division"] = division
|
| 62 |
+
|
| 63 |
+
results.append(Case(
|
| 64 |
+
case_id=case_id,
|
| 65 |
+
link=link,
|
| 66 |
+
decision_date=decision_date,
|
| 67 |
+
jurisdiction="ch",
|
| 68 |
+
language=(row.get("language") or "").strip().lower() or None,
|
| 69 |
+
full_text=row.get("full_text"),
|
| 70 |
+
metadata=metadata,
|
| 71 |
+
))
|
| 72 |
+
return results
|
| 73 |
+
|
| 74 |
+
@staticmethod
|
| 75 |
+
def parse_case_id(link: str | None) -> tuple[str | None, str | None, str | None]:
|
| 76 |
+
if not link:
|
| 77 |
+
return None, None, None
|
| 78 |
+
m = _RE_JUMPCGI.search(unquote(link)) or _RE_AZA.search(unquote(link))
|
| 79 |
+
if not m:
|
| 80 |
+
return None, None, None
|
| 81 |
+
chamber, num, year = m.group(1), m.group(2), m.group(3)
|
| 82 |
+
return f"{chamber}_{num}/{year}", chamber, chamber[0]
|
| 83 |
+
|
| 84 |
+
@staticmethod
|
| 85 |
+
def civil_filter(cases: list[Case]) -> list[Case]:
|
| 86 |
+
return [c for c in cases if (c.metadata or {}).get("division") in {"4", "5"}]
|
legex/scrapers/de.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import re
|
| 3 |
+
from datetime import date
|
| 4 |
+
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
|
| 7 |
+
from legex.config import settings
|
| 8 |
+
from legex.models.base import Case
|
| 9 |
+
from legex.scrapers.base import BaseScraper
|
| 10 |
+
|
| 11 |
+
DATASET_PATH = "openlegaldata/court-decisions-germany"
|
| 12 |
+
DATASET_NAME = 'dump-20221018'
|
| 13 |
+
# OpenLegalData shifts the `date` field for anonymity. Real year is encoded in
|
| 14 |
+
# file_number as the trailing /YY slash-suffix, for example "XII ZR 17/18" to 2018.
|
| 15 |
+
# Civil BGH senates are numbered with Roman numerals followed by ZR/ZB/ZA.
|
| 16 |
+
_RE_YEAR = re.compile(r"/(\d{2,4})\s*$")
|
| 17 |
+
_RE_CIVIL = re.compile(r"^([IVXLCDM]+)\s+(ZR|ZB|ZA)\b")
|
| 18 |
+
|
| 19 |
+
log = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class DEScraper(BaseScraper):
|
| 23 |
+
country = "Deutschland"
|
| 24 |
+
|
| 25 |
+
def scrape(
|
| 26 |
+
self,
|
| 27 |
+
start_date: date | None = None,
|
| 28 |
+
end_date: date | None = None,
|
| 29 |
+
) -> list[Case]:
|
| 30 |
+
log.info(f"Loading {DATASET_PATH} (gated; requires HF_TOKEN) …")
|
| 31 |
+
dataset = load_dataset(path=DATASET_PATH, name=DATASET_NAME, split="train", token=settings.hf_token or None)
|
| 32 |
+
cases = [
|
| 33 |
+
self._row_to_case(row) for row in dataset
|
| 34 |
+
if (row.get("court") or {}).get("name") == "Bundesgerichtshof"
|
| 35 |
+
]
|
| 36 |
+
cases = [c for c in cases if c is not None]
|
| 37 |
+
|
| 38 |
+
if start_date or end_date:
|
| 39 |
+
start_year = start_date.year if start_date else 0
|
| 40 |
+
end_year = end_date.year if end_date else 9999
|
| 41 |
+
cases = [
|
| 42 |
+
c for c in cases
|
| 43 |
+
if start_year <= (c.decision_date.year if c.decision_date else 0) <= end_year
|
| 44 |
+
]
|
| 45 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 46 |
+
log.info(f"{len(cases)} BGH cases after year filter")
|
| 47 |
+
return cases
|
| 48 |
+
|
| 49 |
+
@staticmethod
|
| 50 |
+
def _row_to_case(row: dict) -> Case | None:
|
| 51 |
+
file_number = row.get("file_number") or ""
|
| 52 |
+
m = _RE_YEAR.search(file_number)
|
| 53 |
+
if not m:
|
| 54 |
+
return None
|
| 55 |
+
year = int(m.group(1))
|
| 56 |
+
if year < 50:
|
| 57 |
+
year += 2000
|
| 58 |
+
elif year < 100:
|
| 59 |
+
year += 1900
|
| 60 |
+
# Use January 1 of the inferred year, the real day/month is shifted.
|
| 61 |
+
decision_date = date(year, 1, 1)
|
| 62 |
+
content = row.get("markdown_content") or row.get("content") or ""
|
| 63 |
+
return Case(
|
| 64 |
+
case_id=file_number,
|
| 65 |
+
link=f"https://de.openlegaldata.io/case/{row.get('id')}",
|
| 66 |
+
decision_date=decision_date,
|
| 67 |
+
jurisdiction="de",
|
| 68 |
+
language="de",
|
| 69 |
+
full_text=content,
|
| 70 |
+
metadata={
|
| 71 |
+
"ecli": row.get("ecli"),
|
| 72 |
+
"type": row.get("type"),
|
| 73 |
+
"slug": row.get("slug"),
|
| 74 |
+
},
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
@staticmethod
|
| 78 |
+
def civil_filter(cases: list[Case]) -> list[Case]:
|
| 79 |
+
return [c for c in cases if _RE_CIVIL.match(c.case_id or "")]
|
legex/scrapers/fr.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""French Cour de cassation scraper via the PISTE Judilibre API.
|
| 2 |
+
|
| 3 |
+
Civil filtering happens pre-download at the API level (``CIVIL_CHAMBERS``),
|
| 4 |
+
so the default passthrough ``BaseScraper.civil_filter`` suffices.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
import os
|
| 9 |
+
import time
|
| 10 |
+
from datetime import date
|
| 11 |
+
|
| 12 |
+
import requests
|
| 13 |
+
|
| 14 |
+
from legex.models.base import Case
|
| 15 |
+
from legex.scrapers.base import BaseScraper
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
log = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
PROD_BASE_URL = "https://api.piste.gouv.fr/cassation/judilibre/v1.0"
|
| 21 |
+
PISTE_TOKEN_URL = "https://oauth.piste.gouv.fr/api/oauth/token"
|
| 22 |
+
DECISION_URL_TEMPLATE = "https://www.courdecassation.fr/decision/{decision_id}"
|
| 23 |
+
|
| 24 |
+
CIVIL_CHAMBERS = ["civ1", "civ2", "civ3"]
|
| 25 |
+
CHAMBER_LABELS = {"civ1": "1re civile", "civ2": "2e civile", "civ3": "3e civile"}
|
| 26 |
+
METADATA_KEYS = ("number", "chamber", "jurisdiction", "ecli", "solution", "formation", "publication", "type")
|
| 27 |
+
|
| 28 |
+
BATCH_SIZE = 1000
|
| 29 |
+
DELAY_SECONDS = 3
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class FRScraper(BaseScraper):
|
| 33 |
+
country = "Frankreich"
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
client_id: str = "",
|
| 38 |
+
client_secret: str = "",
|
| 39 |
+
base_url: str = PROD_BASE_URL,
|
| 40 |
+
) -> None:
|
| 41 |
+
self.client_id = client_id or os.environ.get("JUDILIBRE_CLIENT_ID", "")
|
| 42 |
+
self.client_secret = client_secret or os.environ.get("JUDILIBRE_CLIENT_SECRET", "")
|
| 43 |
+
self.base_url = base_url
|
| 44 |
+
|
| 45 |
+
if not self.client_id or not self.client_secret:
|
| 46 |
+
raise ValueError(
|
| 47 |
+
"FRScraper requires JUDILIBRE_CLIENT_ID and JUDILIBRE_CLIENT_SECRET. "
|
| 48 |
+
"Set them in .env or pass as constructor arguments."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
self.session = requests.Session()
|
| 52 |
+
self.session.headers.update({
|
| 53 |
+
"Accept": "application/json",
|
| 54 |
+
"Authorization": f"Bearer {self._obtain_access_token()}",
|
| 55 |
+
})
|
| 56 |
+
|
| 57 |
+
def scrape(
|
| 58 |
+
self,
|
| 59 |
+
start_date: date | None = None,
|
| 60 |
+
end_date: date | None = None,
|
| 61 |
+
) -> list[Case]:
|
| 62 |
+
# Judilibre /export caps at 10 batches × 1000 = 10 000 results per query,
|
| 63 |
+
# so we chunk by year to stay under the cap.
|
| 64 |
+
start_date = start_date or date(2015, 1, 1)
|
| 65 |
+
end_date = end_date or date.today()
|
| 66 |
+
|
| 67 |
+
all_cases: list[Case] = []
|
| 68 |
+
seen_links: set[str] = set()
|
| 69 |
+
|
| 70 |
+
for year in range(start_date.year, end_date.year + 1):
|
| 71 |
+
year_start = max(start_date, date(year, 1, 1)).isoformat()
|
| 72 |
+
year_end = min(end_date, date(year, 12, 31)).isoformat()
|
| 73 |
+
log.info(f"Scraping year {year} ({year_start} to {year_end})")
|
| 74 |
+
for chamber in CIVIL_CHAMBERS:
|
| 75 |
+
for case in self._scrape_chamber(year, chamber, year_start, year_end):
|
| 76 |
+
if case.link not in seen_links:
|
| 77 |
+
seen_links.add(case.link)
|
| 78 |
+
all_cases.append(case)
|
| 79 |
+
time.sleep(DELAY_SECONDS)
|
| 80 |
+
|
| 81 |
+
return all_cases
|
| 82 |
+
|
| 83 |
+
def _obtain_access_token(self) -> str:
|
| 84 |
+
resp = requests.post(
|
| 85 |
+
PISTE_TOKEN_URL,
|
| 86 |
+
data={
|
| 87 |
+
"grant_type": "client_credentials",
|
| 88 |
+
"client_id": self.client_id,
|
| 89 |
+
"client_secret": self.client_secret,
|
| 90 |
+
"scope": "openid",
|
| 91 |
+
},
|
| 92 |
+
timeout=15,
|
| 93 |
+
)
|
| 94 |
+
resp.raise_for_status()
|
| 95 |
+
token = resp.json().get("access_token", "")
|
| 96 |
+
if not token:
|
| 97 |
+
raise ValueError(f"No access_token in response: {resp.text[:200]}")
|
| 98 |
+
return token
|
| 99 |
+
|
| 100 |
+
def _fetch_json(self, url: str, params: dict | None = None) -> dict:
|
| 101 |
+
response = self.session.get(url, params=params, timeout=15)
|
| 102 |
+
if response.status_code == 429:
|
| 103 |
+
time.sleep(30)
|
| 104 |
+
return self._fetch_json(url, params)
|
| 105 |
+
response.raise_for_status()
|
| 106 |
+
return response.json()
|
| 107 |
+
|
| 108 |
+
def _fetch_export_batch(
|
| 109 |
+
self,
|
| 110 |
+
chamber: str,
|
| 111 |
+
batch: int,
|
| 112 |
+
date_start: str | None,
|
| 113 |
+
date_end: str | None,
|
| 114 |
+
) -> dict:
|
| 115 |
+
params: dict = {
|
| 116 |
+
"chamber": chamber,
|
| 117 |
+
"batch": batch,
|
| 118 |
+
"batch_size": BATCH_SIZE,
|
| 119 |
+
"resolve_references": "false",
|
| 120 |
+
}
|
| 121 |
+
if date_start:
|
| 122 |
+
params["date_start"] = date_start
|
| 123 |
+
if date_end:
|
| 124 |
+
params["date_end"] = date_end
|
| 125 |
+
return self._fetch_json(f"{self.base_url}/export", params=params)
|
| 126 |
+
|
| 127 |
+
def _scrape_chamber(
|
| 128 |
+
self,
|
| 129 |
+
year: int,
|
| 130 |
+
chamber: str,
|
| 131 |
+
date_start: str | None,
|
| 132 |
+
date_end: str | None,
|
| 133 |
+
) -> list[Case]:
|
| 134 |
+
results: list[Case] = []
|
| 135 |
+
label = CHAMBER_LABELS.get(chamber, chamber)
|
| 136 |
+
batch = 0
|
| 137 |
+
|
| 138 |
+
while True:
|
| 139 |
+
data = self._fetch_export_batch(chamber, batch, date_start, date_end)
|
| 140 |
+
decisions = data.get("results", [])
|
| 141 |
+
log.info(f"[{year}] {label}: batch {batch} — {len(decisions)} decisions (total: {data.get('total', '?')})")
|
| 142 |
+
|
| 143 |
+
for decision in decisions:
|
| 144 |
+
case = self._decision_to_case(decision)
|
| 145 |
+
if case is not None:
|
| 146 |
+
results.append(case)
|
| 147 |
+
|
| 148 |
+
if not decisions or data.get("next_batch") is None:
|
| 149 |
+
log.info(f"[{year}] {label}: done at batch {batch} ({len(results)} total)")
|
| 150 |
+
break
|
| 151 |
+
|
| 152 |
+
batch += 1
|
| 153 |
+
time.sleep(DELAY_SECONDS)
|
| 154 |
+
|
| 155 |
+
return results
|
| 156 |
+
|
| 157 |
+
@staticmethod
|
| 158 |
+
def _normalize_date(raw_date: str | None) -> date | None:
|
| 159 |
+
if not raw_date:
|
| 160 |
+
return None
|
| 161 |
+
try:
|
| 162 |
+
return date.fromisoformat(raw_date.strip())
|
| 163 |
+
except ValueError:
|
| 164 |
+
return None
|
| 165 |
+
|
| 166 |
+
@classmethod
|
| 167 |
+
def _decision_to_case(cls, decision: dict) -> Case | None:
|
| 168 |
+
decision_id = decision.get("id")
|
| 169 |
+
if not decision_id:
|
| 170 |
+
return None
|
| 171 |
+
parsed_date = cls._normalize_date(decision.get("decision_date"))
|
| 172 |
+
if parsed_date is None:
|
| 173 |
+
return None
|
| 174 |
+
return Case(
|
| 175 |
+
case_id=decision.get("number") or decision.get("ecli"),
|
| 176 |
+
link=DECISION_URL_TEMPLATE.format(decision_id=decision_id),
|
| 177 |
+
decision_date=parsed_date,
|
| 178 |
+
jurisdiction="fr",
|
| 179 |
+
language="fr",
|
| 180 |
+
full_text=decision.get("text"),
|
| 181 |
+
metadata={k: decision.get(k) for k in METADATA_KEYS if decision.get(k)},
|
| 182 |
+
)
|
legex/scrapers/ge.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import re
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
import urllib.request
|
| 6 |
+
from datetime import date
|
| 7 |
+
|
| 8 |
+
from legex.models.base import Case
|
| 9 |
+
from legex.scrapers.base import BaseScraper
|
| 10 |
+
|
| 11 |
+
log = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
USER_AGENT = "FriendyResearcher"
|
| 14 |
+
DELAY_SECONDS = 0.3
|
| 15 |
+
URL_TEMPLATE = "https://www.supremecourt.ge/ka/fullcase/{nid}/1"
|
| 16 |
+
|
| 17 |
+
# Note: the sample is not random; it was assembled from manual searches across
|
| 18 |
+
# multiple supreme-court listings. See the paper for sampling caveats.
|
| 19 |
+
_EXISTING_29 = {75795, 76240, 76234, 76198, 76209, 76215, 76205, 76201, 76238,
|
| 20 |
+
76202, 76203, 76204, 76211, 76218, 76219, 76220, 76221, 76225,
|
| 21 |
+
76188, 76190, 76187, 76182, 76185, 76186, 76177, 76178, 76191, 76199, 76200}
|
| 22 |
+
|
| 23 |
+
_SEARCH_19 = {75596, 70414, 33102, 72758, 73910, 75109, 73341, 74047, 73589,
|
| 24 |
+
73919, 70283, 73640, 69240, 69940, 66739, 67977, 70199, 73785, 72004}
|
| 25 |
+
|
| 26 |
+
_PROBE_76177 = {76179, 76180, 76181, 76183, 76184, 76189, 76192, 76193, 76194,
|
| 27 |
+
76195, 76196, 76197, 76206, 76207, 76208, 76212, 76213, 76214,
|
| 28 |
+
76216, 76228, 76229, 76230, 76231, 76232, 76233, 76236, 76237, 76239}
|
| 29 |
+
|
| 30 |
+
_PROBE_75500 = {75500, 75501, 75504, 75505, 75506, 75508, 75509, 75510, 75511,
|
| 31 |
+
75512, 75513, 75514, 75515, 75516, 75517, 75518, 75519, 75520,
|
| 32 |
+
75521, 75522, 75523, 75524, 75525, 75526, 75527, 75528, 75529,
|
| 33 |
+
75530, 75531, 75532, 75533, 75534, 75535, 75536, 75537, 75538,
|
| 34 |
+
75539, 75540, 75541, 75542, 75543, 75544, 75545, 75546, 75547,
|
| 35 |
+
75548, 75549, 75550, 75551, 75552, 75556, 75557, 75559, 75560,
|
| 36 |
+
75561, 75562, 75563, 75564, 75565, 75566, 75567, 75568, 75569,
|
| 37 |
+
75570, 75571, 75572, 75573, 75574, 75575, 75576, 75577, 75578,
|
| 38 |
+
75579, 75580, 75581, 75582, 75583, 75584, 75585, 75586}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _all_case_ids() -> list[int]:
|
| 42 |
+
ids = _EXISTING_29 | _SEARCH_19 | _PROBE_76177 | _PROBE_75500
|
| 43 |
+
# 33102 historically returns 500 — drop both string and int forms defensively.
|
| 44 |
+
ids.discard("33102") # type: ignore[arg-type]
|
| 45 |
+
ids.discard(33102)
|
| 46 |
+
return sorted(int(x) for x in ids)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
_GEO_MONTHS = {
|
| 50 |
+
"იანვარი": "01", "თებერვალი": "02", "მარტი": "03", "აპრილი": "04",
|
| 51 |
+
"მაისი": "05", "ივნისი": "06", "ივლისი": "07", "აგვისტო": "08",
|
| 52 |
+
"სექტემბერი": "09", "ოქტომბერი": "10", "ნოემბერი": "11", "დეკემბერი": "12",
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
_CASE_RE_PRIMARY = re.compile(r"(?:საქმე\s*N?:?\s*|საქმე\s*№)(ას-\d+-\d+)", re.DOTALL)
|
| 56 |
+
_CASE_RE_FALLBACK = re.compile(r"(ას-\d+-\d+)")
|
| 57 |
+
_DATE_DMY = re.compile(
|
| 58 |
+
r"(\d{1,2})\s*(იანვარი|თებერვალი|მარტი|აპრილი|მაისი|ივნისი|ივლისი|აგვისტო|"
|
| 59 |
+
r"სექტემბერი|ოქტომბერი|ნოემბერი|დეკემბერი)\s*,?\s*(\d{4})"
|
| 60 |
+
)
|
| 61 |
+
_DATE_YDM = re.compile(
|
| 62 |
+
r"(\d{4})\s*წელი\s*[,.]?\s*(\d{1,2})\s*(იანვარი|თებერვალი|მარტი|აპრილი|მაისი|"
|
| 63 |
+
r"ივნისი|ივლისი|აგვისტო|სექტემბერი|ოქტომბერი|ნოემბერი|დეკემბერი)"
|
| 64 |
+
)
|
| 65 |
+
_DATE_DMY_SPACED = re.compile(
|
| 66 |
+
r"(\d{1,2})\s+(იანვარი|თებერვალი|მარტი|აპრილი|მაისი|ივნისი|ივლისი|აგვისტო|"
|
| 67 |
+
r"სექტემბერი|ოქტომბერი|ნოემბერი|დეკემბერი)\s*,?\s*(\d{4})"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _fetch_case(nid: int) -> tuple[str, str] | None:
|
| 72 |
+
"""Return (iso_date, case_number) for a case page, or None on error."""
|
| 73 |
+
url = URL_TEMPLATE.format(nid=nid)
|
| 74 |
+
try:
|
| 75 |
+
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
| 76 |
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
| 77 |
+
html = resp.read().decode("utf-8", errors="replace")
|
| 78 |
+
except Exception as e:
|
| 79 |
+
sys.stderr.write(f" {nid}: ERROR - {e}\n")
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
case_m = _CASE_RE_PRIMARY.search(html) or _CASE_RE_FALLBACK.search(html[:5000])
|
| 83 |
+
case_id = case_m.group(1) if case_m else f"case_{nid}"
|
| 84 |
+
|
| 85 |
+
iso_date = ""
|
| 86 |
+
date_m = _DATE_DMY.search(html)
|
| 87 |
+
if date_m:
|
| 88 |
+
iso_date = f"{date_m.group(3)}-{_GEO_MONTHS.get(date_m.group(2), '01')}-{date_m.group(1).zfill(2)}"
|
| 89 |
+
else:
|
| 90 |
+
date_m = _DATE_YDM.search(html)
|
| 91 |
+
if date_m:
|
| 92 |
+
year = date_m.group(1)
|
| 93 |
+
day = date_m.group(2).zfill(2)
|
| 94 |
+
month = _GEO_MONTHS.get(date_m.group(3), "01")
|
| 95 |
+
iso_date = f"{year}-{month}-{day}"
|
| 96 |
+
if not iso_date:
|
| 97 |
+
date_m = _DATE_DMY_SPACED.search(html)
|
| 98 |
+
if date_m:
|
| 99 |
+
iso_date = f"{date_m.group(3)}-{_GEO_MONTHS.get(date_m.group(2), '01')}-{date_m.group(1).zfill(2)}"
|
| 100 |
+
|
| 101 |
+
return iso_date, case_id
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class GEScraper(BaseScraper):
|
| 105 |
+
country = "Georgien"
|
| 106 |
+
|
| 107 |
+
def scrape(
|
| 108 |
+
self,
|
| 109 |
+
start_date: date | None = None,
|
| 110 |
+
end_date: date | None = None,
|
| 111 |
+
) -> list[Case]:
|
| 112 |
+
ids = _all_case_ids()
|
| 113 |
+
log.info("GE total candidate case IDs: %d", len(ids))
|
| 114 |
+
|
| 115 |
+
cases: list[Case] = []
|
| 116 |
+
for nid in ids:
|
| 117 |
+
res = _fetch_case(nid)
|
| 118 |
+
if res is None:
|
| 119 |
+
time.sleep(DELAY_SECONDS)
|
| 120 |
+
continue
|
| 121 |
+
iso_date, case_id = res
|
| 122 |
+
|
| 123 |
+
decision_date: date | None = None
|
| 124 |
+
if iso_date:
|
| 125 |
+
try:
|
| 126 |
+
decision_date = date.fromisoformat(iso_date)
|
| 127 |
+
except ValueError:
|
| 128 |
+
decision_date = None
|
| 129 |
+
|
| 130 |
+
if start_date and decision_date and decision_date < start_date:
|
| 131 |
+
time.sleep(DELAY_SECONDS)
|
| 132 |
+
continue
|
| 133 |
+
if end_date and decision_date and decision_date > end_date:
|
| 134 |
+
time.sleep(DELAY_SECONDS)
|
| 135 |
+
continue
|
| 136 |
+
|
| 137 |
+
cases.append(Case(
|
| 138 |
+
case_id=case_id,
|
| 139 |
+
link=URL_TEMPLATE.format(nid=nid),
|
| 140 |
+
decision_date=decision_date,
|
| 141 |
+
jurisdiction="ge",
|
| 142 |
+
language="ka",
|
| 143 |
+
full_text=None,
|
| 144 |
+
metadata={"site_id": nid},
|
| 145 |
+
))
|
| 146 |
+
sys.stderr.write(f" {nid}: date={iso_date}, case={case_id}\n")
|
| 147 |
+
time.sleep(DELAY_SECONDS)
|
| 148 |
+
|
| 149 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 150 |
+
log.info("Collected %d Georgia cases", len(cases))
|
| 151 |
+
return cases
|
legex/scrapers/gh.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Ghana Supreme Court via GhaLII (https://ghalii.org).
|
| 2 |
+
|
| 3 |
+
GhaLII publishes Supreme Court judgments under `/judgments/GHASC/`. Each entry exposes its
|
| 4 |
+
citation and decision date in the listing markup, so we can build a Goldenset from metadata alone.
|
| 5 |
+
Full text is PDF-only on GhaLII and not extracted here, the labelers click the link to read the judgment.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import html
|
| 9 |
+
import logging
|
| 10 |
+
import re
|
| 11 |
+
import time
|
| 12 |
+
from datetime import date
|
| 13 |
+
from typing import Iterable
|
| 14 |
+
|
| 15 |
+
import requests
|
| 16 |
+
|
| 17 |
+
from legex.models.base import Case
|
| 18 |
+
from legex.scrapers.base import BaseScraper
|
| 19 |
+
|
| 20 |
+
log = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
BASE_URL = "https://ghalii.org"
|
| 23 |
+
PAGE_DELAY_SECONDS = 0.5
|
| 24 |
+
USER_AGENT = "legex-research (open-data, friendly)"
|
| 25 |
+
MAX_PAGES_PER_YEAR = 20
|
| 26 |
+
|
| 27 |
+
_LINK_RE = re.compile(
|
| 28 |
+
r'href="(/akn/gh[^"]*?/judgment/ghasc/(\d{4})/(\d+)/eng@(\d{4}-\d{2}-\d{2}))"'
|
| 29 |
+
r'[^>]*data-key-link="document"[^>]*>([^<]+)</a>'
|
| 30 |
+
)
|
| 31 |
+
_CRIMINAL_RE = re.compile(r"^\s*(the\s+)?republic\s+v(rs?|\.)?\b", re.IGNORECASE)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class GHScraper(BaseScraper):
|
| 35 |
+
country = "Ghana"
|
| 36 |
+
|
| 37 |
+
def scrape(
|
| 38 |
+
self,
|
| 39 |
+
start_date: date | None = None,
|
| 40 |
+
end_date: date | None = None,
|
| 41 |
+
) -> list[Case]:
|
| 42 |
+
session = requests.Session()
|
| 43 |
+
session.headers.update({"User-Agent": USER_AGENT})
|
| 44 |
+
|
| 45 |
+
# Per-year URLs give much better historical coverage than the global listing
|
| 46 |
+
start_year = (start_date or date(2015, 1, 1)).year
|
| 47 |
+
end_year = (end_date or date(2025, 12, 31)).year
|
| 48 |
+
|
| 49 |
+
cases: list[Case] = []
|
| 50 |
+
seen: set[str] = set()
|
| 51 |
+
for year in range(start_year, end_year + 1):
|
| 52 |
+
year_cases = self._scrape_year(session, year, start_date, end_date, seen)
|
| 53 |
+
cases.extend(year_cases)
|
| 54 |
+
|
| 55 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 56 |
+
log.info("Collected %d Ghana cases", len(cases))
|
| 57 |
+
return cases
|
| 58 |
+
|
| 59 |
+
def _scrape_year(
|
| 60 |
+
self,
|
| 61 |
+
session: requests.Session,
|
| 62 |
+
year: int,
|
| 63 |
+
start_date: date | None,
|
| 64 |
+
end_date: date | None,
|
| 65 |
+
seen: set[str],
|
| 66 |
+
) -> list[Case]:
|
| 67 |
+
out: list[Case] = []
|
| 68 |
+
for page in range(1, MAX_PAGES_PER_YEAR + 1):
|
| 69 |
+
url = f"{BASE_URL}/judgments/GHASC/{year}/?page={page}"
|
| 70 |
+
try:
|
| 71 |
+
resp = session.get(url, timeout=30)
|
| 72 |
+
except Exception as e:
|
| 73 |
+
log.warning("GH %d page %d request failed (%s); stopping year", year, page, e)
|
| 74 |
+
break
|
| 75 |
+
if resp.status_code == 404:
|
| 76 |
+
break
|
| 77 |
+
if resp.status_code != 200:
|
| 78 |
+
log.warning("GH %d page %d HTTP %d; stopping year", year, page, resp.status_code)
|
| 79 |
+
break
|
| 80 |
+
|
| 81 |
+
entries = list(self._parse_listing(resp.text))
|
| 82 |
+
if not entries:
|
| 83 |
+
break
|
| 84 |
+
|
| 85 |
+
new_on_page = 0
|
| 86 |
+
for path, ent_year, number, iso_date, title in entries:
|
| 87 |
+
try:
|
| 88 |
+
decision_date = date.fromisoformat(iso_date)
|
| 89 |
+
except ValueError:
|
| 90 |
+
continue
|
| 91 |
+
if start_date and decision_date < start_date:
|
| 92 |
+
continue
|
| 93 |
+
if end_date and decision_date > end_date:
|
| 94 |
+
continue
|
| 95 |
+
case_id = f"[{ent_year}] GHASC {number}"
|
| 96 |
+
if case_id in seen:
|
| 97 |
+
continue
|
| 98 |
+
seen.add(case_id)
|
| 99 |
+
new_on_page += 1
|
| 100 |
+
out.append(
|
| 101 |
+
Case(
|
| 102 |
+
case_id=case_id,
|
| 103 |
+
link=f"{BASE_URL}{path}",
|
| 104 |
+
decision_date=decision_date,
|
| 105 |
+
jurisdiction="gh",
|
| 106 |
+
language="en",
|
| 107 |
+
full_text=None,
|
| 108 |
+
metadata={
|
| 109 |
+
"title": html.unescape(title).strip(),
|
| 110 |
+
"year": ent_year,
|
| 111 |
+
"number": number,
|
| 112 |
+
},
|
| 113 |
+
)
|
| 114 |
+
)
|
| 115 |
+
log.info("GH %d page %d: %d entries (%d new)", year, page, len(entries), new_on_page)
|
| 116 |
+
if new_on_page == 0:
|
| 117 |
+
break
|
| 118 |
+
time.sleep(PAGE_DELAY_SECONDS)
|
| 119 |
+
return out
|
| 120 |
+
|
| 121 |
+
@staticmethod
|
| 122 |
+
def _parse_listing(html_text: str) -> Iterable[tuple[str, str, str, str, str]]:
|
| 123 |
+
for match in _LINK_RE.finditer(html_text):
|
| 124 |
+
yield match.group(1), match.group(2), match.group(3), match.group(4), match.group(5)
|
| 125 |
+
|
| 126 |
+
@staticmethod
|
| 127 |
+
def civil_filter(cases: list[Case]) -> list[Case]:
|
| 128 |
+
# Heuristic: drop criminal prosecutions "(The) Republic v(rs) X".
|
| 129 |
+
kept = [c for c in cases if not _CRIMINAL_RE.match((c.metadata or {}).get("title", ""))]
|
| 130 |
+
log.info("GH civil_filter kept %d/%d", len(kept), len(cases))
|
| 131 |
+
return kept
|
legex/scrapers/in_.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import csv
|
| 3 |
+
import logging
|
| 4 |
+
import random
|
| 5 |
+
import re
|
| 6 |
+
import shutil
|
| 7 |
+
import tarfile
|
| 8 |
+
import tempfile
|
| 9 |
+
import time
|
| 10 |
+
import urllib.request
|
| 11 |
+
import zipfile
|
| 12 |
+
from collections import defaultdict
|
| 13 |
+
from datetime import date, datetime
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
import pandas as pd
|
| 18 |
+
|
| 19 |
+
from legex.config import settings
|
| 20 |
+
from legex.models.base import Case
|
| 21 |
+
from legex.scrapers.base import BaseScraper
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
S3_BASE = "https://indian-supreme-court-judgments.s3.amazonaws.com"
|
| 26 |
+
S3_URI_PREFIX = "s3://indian-supreme-court-judgments/"
|
| 27 |
+
S3_HTTP_PREFIX = "https://indian-supreme-court-judgments.s3.amazonaws.com/"
|
| 28 |
+
|
| 29 |
+
PARQUET_CACHE = settings.data_dir / "cache" / "in" / "parquet_cache"
|
| 30 |
+
TARGET_ROWS = 130
|
| 31 |
+
CIVIL_RATIO = 0.75
|
| 32 |
+
RANDOM_SEED = 42
|
| 33 |
+
|
| 34 |
+
SAMPLE_YEARS = [
|
| 35 |
+
1950, 1955, 1960, 1965, 1970, 1975, 1980, 1985,
|
| 36 |
+
1990, 1995, 2000, 2005, 2010, 2013, 2015, 2017,
|
| 37 |
+
2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026,
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
USER_AGENT_METADATA = "LegEx/1.0 (legal research project; CC-BY-4.0 dataset)"
|
| 41 |
+
USER_AGENT_EXTRACT = "LegEx/1.0 (selected AWS open-data extraction)"
|
| 42 |
+
|
| 43 |
+
_CIVIL_CASE_NO_RE = re.compile(
|
| 44 |
+
r"CIVIL\s+APPEAL|CIVIL\s+ORIGINAL|CIVIL\s+WRIT|CIVIL\s+REVIEW|CIVIL\s+SUIT|"
|
| 45 |
+
r"CIVIL\s+SPECIAL|CIVIL\s+TRANSFER|CIVIL\s+CONTEMPT",
|
| 46 |
+
re.IGNORECASE,
|
| 47 |
+
)
|
| 48 |
+
_CRIMINAL_CASE_NO_RE = re.compile(
|
| 49 |
+
r"CRIMINAL\s+APPEAL|CRIMINAL\s+ORIGINAL|CRIMINAL\s+WRIT|CRIMINAL\s+REVIEW|CRIMINAL\s+MISC",
|
| 50 |
+
re.IGNORECASE,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
_CRIMINAL_KEYWORDS = (
|
| 54 |
+
"murder", "homicide", "rape", "narcotic", "ndps", "penal code",
|
| 55 |
+
"ipc section 302", "ipc 302", "offence under section",
|
| 56 |
+
"punishable under section", "conviction", "sentence of",
|
| 57 |
+
"life imprisonment", "acquittal", "criminal conspiracy",
|
| 58 |
+
"arms act", "explosive", "terrorist", "tada",
|
| 59 |
+
"prevention of corruption", "pocso", "dowry death",
|
| 60 |
+
"culpable homicide", "kidnapping", "abduction",
|
| 61 |
+
)
|
| 62 |
+
_CIVIL_KEYWORDS = (
|
| 63 |
+
"arbitration", "contract", "property", "tax", "insurance",
|
| 64 |
+
"compensation", "damages", "negligence", "motor accident",
|
| 65 |
+
"service matter", "land acquisition", "tenancy", "rent",
|
| 66 |
+
"family", "divorce", "succession", "inheritance", "will",
|
| 67 |
+
"company", "corporate", "insolvency", "bankruptcy",
|
| 68 |
+
"consumer", "labour", "employment", "pension",
|
| 69 |
+
"writ petition", "constitution", "administrative",
|
| 70 |
+
"revenue", "customs", "excise", "gst", "vat",
|
| 71 |
+
"intellectual property", "trademark", "patent", "copyright",
|
| 72 |
+
"environment", "forest", "mining", "electricity",
|
| 73 |
+
"telecom", "competition", "securities", "exchange",
|
| 74 |
+
"banking", "debt recovery", "sarfaesi",
|
| 75 |
+
"education", "admission", "examination",
|
| 76 |
+
"election", "defamation",
|
| 77 |
+
"motor vehicles", "mact", "accident claim",
|
| 78 |
+
"specific performance", "injunction", "possession",
|
| 79 |
+
"partition", "easement", "adverse possession",
|
| 80 |
+
"specific relief", "declaration", "mandamus",
|
| 81 |
+
)
|
| 82 |
+
_CIVIL_DISPOSAL = ("allowed", "partly allowed", "directions issued", "reference answered", "disposed off")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _download_parquet(year: int) -> str | None:
|
| 86 |
+
cache_path = PARQUET_CACHE / str(year) / "metadata.parquet"
|
| 87 |
+
if cache_path.exists():
|
| 88 |
+
log.info("IN %d parquet cached (%d bytes)", year, cache_path.stat().st_size)
|
| 89 |
+
return str(cache_path)
|
| 90 |
+
|
| 91 |
+
url = f"{S3_BASE}/metadata/parquet/year={year}/metadata.parquet"
|
| 92 |
+
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT_METADATA})
|
| 93 |
+
|
| 94 |
+
for attempt in range(3):
|
| 95 |
+
try:
|
| 96 |
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
| 97 |
+
data = resp.read()
|
| 98 |
+
cache_path.parent.mkdir(parents=True, exist_ok=True)
|
| 99 |
+
cache_path.write_bytes(data)
|
| 100 |
+
log.info("IN %d parquet downloaded (%d bytes)", year, len(data))
|
| 101 |
+
return str(cache_path)
|
| 102 |
+
except Exception as e:
|
| 103 |
+
log.warning("IN %d parquet attempt %d failed: %s", year, attempt + 1, e)
|
| 104 |
+
if attempt < 2:
|
| 105 |
+
time.sleep(2 ** attempt)
|
| 106 |
+
return None
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _is_likely_civil(disposal_nature: str | None, raw_html: str | None, title: str | None) -> bool:
|
| 110 |
+
raw_html = raw_html if isinstance(raw_html, str) else ""
|
| 111 |
+
has_civil_cno = bool(_CIVIL_CASE_NO_RE.search(raw_html))
|
| 112 |
+
has_criminal_cno = bool(_CRIMINAL_CASE_NO_RE.search(raw_html))
|
| 113 |
+
|
| 114 |
+
if has_civil_cno and not has_criminal_cno:
|
| 115 |
+
return True
|
| 116 |
+
if has_criminal_cno and not has_civil_cno:
|
| 117 |
+
return False
|
| 118 |
+
|
| 119 |
+
dn_lower = (disposal_nature or "").lower()
|
| 120 |
+
title_lower = (title or "").lower()
|
| 121 |
+
|
| 122 |
+
is_criminal_kw = any(kw in title_lower or kw in dn_lower for kw in _CRIMINAL_KEYWORDS)
|
| 123 |
+
is_civil_kw = any(kw in title_lower or kw in dn_lower for kw in _CIVIL_KEYWORDS)
|
| 124 |
+
|
| 125 |
+
if is_criminal_kw and not is_civil_kw:
|
| 126 |
+
return False
|
| 127 |
+
if is_civil_kw:
|
| 128 |
+
return True
|
| 129 |
+
|
| 130 |
+
return any(d in dn_lower for d in _CIVIL_DISPOSAL)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _build_link(year: str, path_str: str) -> str | None:
|
| 134 |
+
if not path_str or pd.isna(path_str):
|
| 135 |
+
return None
|
| 136 |
+
path_str = str(path_str).strip()
|
| 137 |
+
tarball_name = path_str + "_EN.pdf"
|
| 138 |
+
return f"s3://indian-supreme-court-judgments/data/tar/year={year}/english/english.tar#{tarball_name}"
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _parse_decision_date(date_val: Any) -> str | None:
|
| 142 |
+
if pd.isna(date_val) or not date_val:
|
| 143 |
+
return None
|
| 144 |
+
date_str = str(date_val).strip()
|
| 145 |
+
for fmt in ("%d-%m-%Y", "%Y-%m-%d", "%d/%m/%Y", "%m/%d/%Y", "%d.%m.%Y"):
|
| 146 |
+
try:
|
| 147 |
+
return datetime.strptime(date_str, fmt).strftime("%Y-%m-%d")
|
| 148 |
+
except ValueError:
|
| 149 |
+
continue
|
| 150 |
+
return date_str
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _stratified_sample(pool: list[dict[str, Any]], n: int, rng: random.Random) -> list[dict[str, Any]]:
|
| 154 |
+
if n <= 0 or not pool:
|
| 155 |
+
return []
|
| 156 |
+
if n >= len(pool):
|
| 157 |
+
return list(pool)
|
| 158 |
+
|
| 159 |
+
decades: dict[int, list[dict[str, Any]]] = {}
|
| 160 |
+
for item in pool:
|
| 161 |
+
decade = (item["year"] // 10) * 10
|
| 162 |
+
decades.setdefault(decade, []).append(item)
|
| 163 |
+
|
| 164 |
+
total = len(pool)
|
| 165 |
+
decades_sorted = sorted(decades.keys())
|
| 166 |
+
allocated: dict[int, int] = {}
|
| 167 |
+
for decade in decades_sorted:
|
| 168 |
+
prop = len(decades[decade]) / total
|
| 169 |
+
alloc = max(1, round(prop * n))
|
| 170 |
+
allocated[decade] = min(alloc, len(decades[decade]))
|
| 171 |
+
|
| 172 |
+
diff = n - sum(allocated.values())
|
| 173 |
+
while diff != 0:
|
| 174 |
+
for decade in sorted(decades_sorted, key=lambda d: len(decades[d]), reverse=True):
|
| 175 |
+
if diff == 0:
|
| 176 |
+
break
|
| 177 |
+
if diff > 0 and allocated.get(decade, 0) < len(decades[decade]):
|
| 178 |
+
allocated[decade] += 1
|
| 179 |
+
diff -= 1
|
| 180 |
+
elif diff < 0 and allocated.get(decade, 0) > 1:
|
| 181 |
+
allocated[decade] -= 1
|
| 182 |
+
diff += 1
|
| 183 |
+
|
| 184 |
+
result: list[dict[str, Any]] = []
|
| 185 |
+
for decade in decades_sorted:
|
| 186 |
+
count = allocated.get(decade, 0)
|
| 187 |
+
if count > 0:
|
| 188 |
+
rng.shuffle(decades[decade])
|
| 189 |
+
result.extend(decades[decade][:count])
|
| 190 |
+
|
| 191 |
+
rng.shuffle(result)
|
| 192 |
+
return result[:n]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class INScraper(BaseScraper):
|
| 196 |
+
country = "Indien"
|
| 197 |
+
|
| 198 |
+
def scrape(
|
| 199 |
+
self,
|
| 200 |
+
start_date: date | None = None,
|
| 201 |
+
end_date: date | None = None,
|
| 202 |
+
) -> list[Case]:
|
| 203 |
+
rng = random.Random(RANDOM_SEED)
|
| 204 |
+
years = SAMPLE_YEARS
|
| 205 |
+
if start_date is not None:
|
| 206 |
+
years = [y for y in years if y >= start_date.year]
|
| 207 |
+
if end_date is not None:
|
| 208 |
+
years = [y for y in years if y <= end_date.year]
|
| 209 |
+
|
| 210 |
+
PARQUET_CACHE.mkdir(parents=True, exist_ok=True)
|
| 211 |
+
|
| 212 |
+
log.info("IN downloading metadata parquets for %d years", len(years))
|
| 213 |
+
parquet_paths: list[str] = []
|
| 214 |
+
for year in years:
|
| 215 |
+
path = _download_parquet(year)
|
| 216 |
+
if path:
|
| 217 |
+
parquet_paths.append(path)
|
| 218 |
+
time.sleep(0.3)
|
| 219 |
+
|
| 220 |
+
if not parquet_paths:
|
| 221 |
+
log.warning("IN no parquet metadata downloaded")
|
| 222 |
+
return []
|
| 223 |
+
|
| 224 |
+
all_dfs: list[pd.DataFrame] = []
|
| 225 |
+
for pp in parquet_paths:
|
| 226 |
+
try:
|
| 227 |
+
df = pd.read_parquet(pp)
|
| 228 |
+
year = int(Path(pp).parent.name)
|
| 229 |
+
if "year" not in df.columns:
|
| 230 |
+
df["year"] = str(year)
|
| 231 |
+
all_dfs.append(df)
|
| 232 |
+
log.info("IN %d: %d rows", year, len(df))
|
| 233 |
+
except Exception as e:
|
| 234 |
+
log.warning("IN parquet %s load failed: %s", pp, e)
|
| 235 |
+
|
| 236 |
+
if not all_dfs:
|
| 237 |
+
return []
|
| 238 |
+
|
| 239 |
+
combined = pd.concat(all_dfs, ignore_index=True)
|
| 240 |
+
log.info("IN total combined rows: %d", len(combined))
|
| 241 |
+
|
| 242 |
+
candidates: list[dict[str, Any]] = []
|
| 243 |
+
seen_paths: set[str] = set()
|
| 244 |
+
for _, row in combined.iterrows():
|
| 245 |
+
path_val = row.get("path", "")
|
| 246 |
+
path_str = str(path_val).strip() if not pd.isna(path_val) else ""
|
| 247 |
+
if not path_str or path_str in seen_paths:
|
| 248 |
+
continue
|
| 249 |
+
seen_paths.add(path_str)
|
| 250 |
+
|
| 251 |
+
year_val = str(row.get("year", "")).strip()
|
| 252 |
+
if not year_val:
|
| 253 |
+
continue
|
| 254 |
+
try:
|
| 255 |
+
year_int = int(year_val)
|
| 256 |
+
except ValueError:
|
| 257 |
+
continue
|
| 258 |
+
|
| 259 |
+
link = _build_link(year_val, path_str)
|
| 260 |
+
iso_date = _parse_decision_date(row.get("decision_date"))
|
| 261 |
+
|
| 262 |
+
case_id_val = row.get("case_id", "")
|
| 263 |
+
case_id = str(case_id_val).strip() if not pd.isna(case_id_val) else ""
|
| 264 |
+
if not case_id:
|
| 265 |
+
case_id = path_str
|
| 266 |
+
|
| 267 |
+
disposal_nature = str(row.get("disposal_nature", "")) if not pd.isna(row.get("disposal_nature", "")) else ""
|
| 268 |
+
raw_html = str(row.get("raw_html", "")) if not pd.isna(row.get("raw_html", "")) else ""
|
| 269 |
+
title_val = row.get("title", "")
|
| 270 |
+
title = str(title_val) if not pd.isna(title_val) else ""
|
| 271 |
+
|
| 272 |
+
candidates.append({
|
| 273 |
+
"decision_date": iso_date,
|
| 274 |
+
"link": link,
|
| 275 |
+
"case_id": case_id,
|
| 276 |
+
"year": year_int,
|
| 277 |
+
"civil": _is_likely_civil(disposal_nature, raw_html, title),
|
| 278 |
+
"disposal_nature": disposal_nature,
|
| 279 |
+
"title": title[:120],
|
| 280 |
+
})
|
| 281 |
+
|
| 282 |
+
log.info("IN total candidates: %d", len(candidates))
|
| 283 |
+
|
| 284 |
+
civil_target = int(TARGET_ROWS * CIVIL_RATIO)
|
| 285 |
+
mixed_target = TARGET_ROWS - civil_target
|
| 286 |
+
|
| 287 |
+
civil_pool = [c for c in candidates if c["civil"]]
|
| 288 |
+
other_pool = [c for c in candidates if not c["civil"]]
|
| 289 |
+
|
| 290 |
+
if len(civil_pool) < civil_target:
|
| 291 |
+
civil_target = min(len(civil_pool), TARGET_ROWS)
|
| 292 |
+
mixed_target = TARGET_ROWS - civil_target
|
| 293 |
+
mixed_target = min(mixed_target, len(other_pool))
|
| 294 |
+
civil_target = TARGET_ROWS - mixed_target
|
| 295 |
+
civil_target = min(civil_target, len(civil_pool))
|
| 296 |
+
|
| 297 |
+
civil_sampled = _stratified_sample(civil_pool, civil_target, rng)
|
| 298 |
+
other_sampled = _stratified_sample(other_pool, mixed_target, rng)
|
| 299 |
+
|
| 300 |
+
sampled = civil_sampled + other_sampled
|
| 301 |
+
rng.shuffle(sampled)
|
| 302 |
+
log.info("IN sampled %d (%d civil + %d other)", len(sampled), len(civil_sampled), len(other_sampled))
|
| 303 |
+
|
| 304 |
+
cases: list[Case] = []
|
| 305 |
+
for item in sampled:
|
| 306 |
+
decision_date: date | None = None
|
| 307 |
+
if item["decision_date"]:
|
| 308 |
+
try:
|
| 309 |
+
decision_date = date.fromisoformat(item["decision_date"])
|
| 310 |
+
except ValueError:
|
| 311 |
+
decision_date = None
|
| 312 |
+
|
| 313 |
+
if start_date and decision_date and decision_date < start_date:
|
| 314 |
+
continue
|
| 315 |
+
if end_date and decision_date and decision_date > end_date:
|
| 316 |
+
continue
|
| 317 |
+
|
| 318 |
+
cases.append(Case(
|
| 319 |
+
case_id=item["case_id"],
|
| 320 |
+
link=item["link"],
|
| 321 |
+
decision_date=decision_date,
|
| 322 |
+
jurisdiction="in",
|
| 323 |
+
language="en",
|
| 324 |
+
full_text=None,
|
| 325 |
+
metadata={
|
| 326 |
+
"year": item["year"],
|
| 327 |
+
"civil": item["civil"],
|
| 328 |
+
"disposal_nature": item["disposal_nature"],
|
| 329 |
+
"title": item["title"],
|
| 330 |
+
},
|
| 331 |
+
))
|
| 332 |
+
|
| 333 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 334 |
+
log.info("Collected %d India cases", len(cases))
|
| 335 |
+
return cases
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
# ── PDF extraction (post-step CLI: legex-india-extract) ───────────────
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def _parse_s3_link(link: str) -> tuple[str, str]:
|
| 342 |
+
if "#" not in link:
|
| 343 |
+
raise ValueError(f"Missing TAR member fragment: {link}")
|
| 344 |
+
tar_uri, member = link.split("#", 1)
|
| 345 |
+
if not tar_uri.startswith(S3_URI_PREFIX):
|
| 346 |
+
raise ValueError(f"Unexpected S3 URI: {tar_uri}")
|
| 347 |
+
return tar_uri[len(S3_URI_PREFIX):], member
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def _safe_name(value: str) -> str:
|
| 351 |
+
return re.sub(r"[^A-Za-z0-9_.-]+", "_", value.strip()).strip("_") or "case"
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _download(url: str, dest: Path) -> None:
|
| 355 |
+
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT_EXTRACT})
|
| 356 |
+
with urllib.request.urlopen(req, timeout=600) as response, dest.open("wb") as out:
|
| 357 |
+
shutil.copyfileobj(response, out)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def extract_judgment_pdfs(
|
| 361 |
+
sample_csv: Path,
|
| 362 |
+
out_zip: Path,
|
| 363 |
+
work_dir: Path | None = None,
|
| 364 |
+
dry_run: bool = False,
|
| 365 |
+
) -> int:
|
| 366 |
+
"""Extract selected judgment PDFs from year-level S3 TAR archives.
|
| 367 |
+
|
| 368 |
+
Reads a CSV with a `link` column of the form
|
| 369 |
+
`s3://indian-supreme-court-judgments/.../english.tar#file.pdf`,
|
| 370 |
+
downloads each unique TAR once, extracts only the requested members into
|
| 371 |
+
`out_zip`, and writes a `manifest.csv` member alongside them.
|
| 372 |
+
|
| 373 |
+
Returns the number of PDFs written.
|
| 374 |
+
"""
|
| 375 |
+
out_zip.parent.mkdir(parents=True, exist_ok=True)
|
| 376 |
+
rows = list(csv.DictReader(sample_csv.open(encoding="utf-8-sig", newline="")))
|
| 377 |
+
grouped: dict[str, list[dict]] = defaultdict(list)
|
| 378 |
+
for row in rows:
|
| 379 |
+
tar_rel, member = _parse_s3_link(row["link"])
|
| 380 |
+
row["_tar_rel"] = tar_rel
|
| 381 |
+
row["_member"] = member
|
| 382 |
+
grouped[tar_rel].append(row)
|
| 383 |
+
|
| 384 |
+
log.info("IN extract: %d judgments across %d TAR archives", len(rows), len(grouped))
|
| 385 |
+
for tar_rel, tar_rows in sorted(grouped.items()):
|
| 386 |
+
log.info(" %s: %d PDFs", tar_rel, len(tar_rows))
|
| 387 |
+
if dry_run:
|
| 388 |
+
return 0
|
| 389 |
+
|
| 390 |
+
work_root = work_dir if work_dir else Path(tempfile.mkdtemp(prefix="india_extract_"))
|
| 391 |
+
work_root.mkdir(parents=True, exist_ok=True)
|
| 392 |
+
manifest_rows: list[dict[str, str]] = []
|
| 393 |
+
|
| 394 |
+
try:
|
| 395 |
+
with zipfile.ZipFile(out_zip, "w", zipfile.ZIP_DEFLATED) as zf:
|
| 396 |
+
for tar_rel, tar_rows in sorted(grouped.items()):
|
| 397 |
+
tar_url = S3_HTTP_PREFIX + tar_rel
|
| 398 |
+
tar_path = work_root / _safe_name(tar_rel)
|
| 399 |
+
log.info("IN extract: downloading %s", tar_url)
|
| 400 |
+
_download(tar_url, tar_path)
|
| 401 |
+
wanted = {row["_member"]: row for row in tar_rows}
|
| 402 |
+
extracted = 0
|
| 403 |
+
with tarfile.open(tar_path) as tf:
|
| 404 |
+
members = {m.name.rsplit("/", 1)[-1]: m for m in tf.getmembers() if m.isfile()}
|
| 405 |
+
for member_name, row in wanted.items():
|
| 406 |
+
member = members.get(member_name)
|
| 407 |
+
if member is None:
|
| 408 |
+
log.warning("IN extract: missing %s in %s", member_name, tar_rel)
|
| 409 |
+
continue
|
| 410 |
+
src = tf.extractfile(member)
|
| 411 |
+
if src is None:
|
| 412 |
+
log.warning("IN extract: cannot extract %s", member_name)
|
| 413 |
+
continue
|
| 414 |
+
case_id = _safe_name(row.get("case_id") or member_name.removesuffix(".pdf"))
|
| 415 |
+
arcname = f"pdf/{case_id}.pdf"
|
| 416 |
+
zf.writestr(arcname, src.read())
|
| 417 |
+
manifest_rows.append({
|
| 418 |
+
"case_id": row.get("case_id", ""),
|
| 419 |
+
"decision_date": row.get("decision_date", ""),
|
| 420 |
+
"source_tar": tar_rel,
|
| 421 |
+
"source_member": member_name,
|
| 422 |
+
"zip_path": arcname,
|
| 423 |
+
})
|
| 424 |
+
extracted += 1
|
| 425 |
+
log.info("IN extract: %d/%d from %s", extracted, len(tar_rows), tar_rel)
|
| 426 |
+
tar_path.unlink(missing_ok=True)
|
| 427 |
+
|
| 428 |
+
manifest = "case_id,decision_date,source_tar,source_member,zip_path\n"
|
| 429 |
+
for row in manifest_rows:
|
| 430 |
+
manifest += ",".join(
|
| 431 |
+
'"' + str(row[k]).replace('"', '""') + '"'
|
| 432 |
+
for k in ("case_id", "decision_date", "source_tar", "source_member", "zip_path")
|
| 433 |
+
) + "\n"
|
| 434 |
+
zf.writestr("manifest.csv", manifest)
|
| 435 |
+
finally:
|
| 436 |
+
try:
|
| 437 |
+
work_root.rmdir()
|
| 438 |
+
except OSError:
|
| 439 |
+
pass
|
| 440 |
+
|
| 441 |
+
log.info("IN extract: wrote %s with %d PDFs", out_zip, len(manifest_rows))
|
| 442 |
+
return len(manifest_rows)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def _extract_cli() -> None:
|
| 446 |
+
"""Entry point for the `legex-india-extract` console script."""
|
| 447 |
+
parser = argparse.ArgumentParser(
|
| 448 |
+
description="Extract selected Indian Supreme Court PDFs from AWS Open Data TAR archives.",
|
| 449 |
+
)
|
| 450 |
+
parser.add_argument("--sample", required=True, help="sample_links.csv")
|
| 451 |
+
parser.add_argument("--out", required=True, help="output zip path")
|
| 452 |
+
parser.add_argument("--work-dir", default=None, help="temporary work directory")
|
| 453 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 454 |
+
args = parser.parse_args()
|
| 455 |
+
|
| 456 |
+
extract_judgment_pdfs(
|
| 457 |
+
sample_csv=Path(args.sample),
|
| 458 |
+
out_zip=Path(args.out),
|
| 459 |
+
work_dir=Path(args.work_dir) if args.work_dir else None,
|
| 460 |
+
dry_run=args.dry_run,
|
| 461 |
+
)
|
legex/scrapers/it.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Italy Corte di Cassazione (civil sections) via the public SentenzeWeb Solr API.
|
| 2 |
+
|
| 3 |
+
Endpoint and field schema discovered via the worldwidelaw/legal-sources project
|
| 4 |
+
(AGPL-3.0). We reimplement the scraping based on this API.
|
| 5 |
+
|
| 6 |
+
The SentenzeWeb index is a rolling window. As of probing in 2026 the earliest
|
| 7 |
+
deposit-date with civil decisions (`kind:snciv`) is 2021.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import html
|
| 11 |
+
import logging
|
| 12 |
+
import re
|
| 13 |
+
from datetime import date, datetime
|
| 14 |
+
from typing import Any
|
| 15 |
+
from urllib.parse import urlencode
|
| 16 |
+
|
| 17 |
+
import requests
|
| 18 |
+
import urllib3
|
| 19 |
+
|
| 20 |
+
from legex.models.base import Case
|
| 21 |
+
from legex.scrapers.base import BaseScraper
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
SOLR_URL = (
|
| 26 |
+
"https://www.italgiure.giustizia.it/sncass/isapi/hc.dll/sn.solr/sn-collection/select"
|
| 27 |
+
)
|
| 28 |
+
PAGE_SIZE = 100
|
| 29 |
+
FIELDS = (
|
| 30 |
+
"id,ocr,kind,numdec,anno,datdep,datdec,tipoprov,szdec,"
|
| 31 |
+
"presidente,relatore,materia,filename"
|
| 32 |
+
)
|
| 33 |
+
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _first(value: Any) -> str:
|
| 37 |
+
if isinstance(value, list):
|
| 38 |
+
return str(value[0]) if value else ""
|
| 39 |
+
return str(value) if value else ""
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _parse_solr_date(value: Any) -> date | None:
|
| 43 |
+
text = _first(value)
|
| 44 |
+
if not text or len(text) < 8:
|
| 45 |
+
return None
|
| 46 |
+
try:
|
| 47 |
+
if "-" in text:
|
| 48 |
+
return date.fromisoformat(text[:10])
|
| 49 |
+
return datetime.strptime(text[:8], "%Y%m%d").date()
|
| 50 |
+
except ValueError:
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
_OCR_WS = re.compile(r"[ \t]+")
|
| 55 |
+
_OCR_BLANK = re.compile(r"\n{3,}")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _clean_ocr(text: str) -> str:
|
| 59 |
+
if not text:
|
| 60 |
+
return ""
|
| 61 |
+
text = html.unescape(text)
|
| 62 |
+
text = _OCR_WS.sub(" ", text)
|
| 63 |
+
text = _OCR_BLANK.sub("\n\n", text)
|
| 64 |
+
return text.strip()
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class ITScraper(BaseScraper):
|
| 68 |
+
country = "Italia"
|
| 69 |
+
|
| 70 |
+
def scrape(
|
| 71 |
+
self,
|
| 72 |
+
start_date: date | None = None,
|
| 73 |
+
end_date: date | None = None,
|
| 74 |
+
) -> list[Case]:
|
| 75 |
+
# Iterate year by year
|
| 76 |
+
start = start_date or date(2015, 1, 1)
|
| 77 |
+
end = end_date or date(2025, 12, 31)
|
| 78 |
+
|
| 79 |
+
session = requests.Session()
|
| 80 |
+
session.headers.update(
|
| 81 |
+
{
|
| 82 |
+
"User-Agent": "legex-research (open-data, friendly)",
|
| 83 |
+
"Accept": "application/json",
|
| 84 |
+
}
|
| 85 |
+
)
|
| 86 |
+
session.verify = False
|
| 87 |
+
|
| 88 |
+
cases: list[Case] = []
|
| 89 |
+
seen: set[str] = set()
|
| 90 |
+
for year in range(start.year, end.year + 1):
|
| 91 |
+
ystart = max(date(year, 1, 1), start).strftime("%Y%m%d")
|
| 92 |
+
yend = min(date(year, 12, 31), end).strftime("%Y%m%d")
|
| 93 |
+
query = f"kind:snciv AND pd:[{ystart} TO {yend}]"
|
| 94 |
+
|
| 95 |
+
total = self._count(session, query)
|
| 96 |
+
log.info("IT %d hits: %d", year, total)
|
| 97 |
+
if total == 0:
|
| 98 |
+
continue
|
| 99 |
+
|
| 100 |
+
offset = 0
|
| 101 |
+
while offset < total:
|
| 102 |
+
params = {
|
| 103 |
+
"q": query,
|
| 104 |
+
"start": str(offset),
|
| 105 |
+
"rows": str(PAGE_SIZE),
|
| 106 |
+
"wt": "json",
|
| 107 |
+
"fl": FIELDS,
|
| 108 |
+
"sort": "pd desc",
|
| 109 |
+
}
|
| 110 |
+
try:
|
| 111 |
+
resp = session.get(SOLR_URL + "?" + urlencode(params), timeout=120)
|
| 112 |
+
resp.raise_for_status()
|
| 113 |
+
docs = resp.json().get("response", {}).get("docs", [])
|
| 114 |
+
except Exception as e:
|
| 115 |
+
log.warning("IT %d offset=%d failed (%s); skipping rest of year", year, offset, e)
|
| 116 |
+
break
|
| 117 |
+
|
| 118 |
+
if not docs:
|
| 119 |
+
break
|
| 120 |
+
|
| 121 |
+
for doc in docs:
|
| 122 |
+
case = self._to_case(doc)
|
| 123 |
+
if case is None or case.case_id in seen:
|
| 124 |
+
continue
|
| 125 |
+
seen.add(case.case_id)
|
| 126 |
+
cases.append(case)
|
| 127 |
+
|
| 128 |
+
offset += len(docs)
|
| 129 |
+
log.info("IT %d done: %d cumulative cases", year, len(cases))
|
| 130 |
+
|
| 131 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 132 |
+
log.info("Collected %d Italy civil cases", len(cases))
|
| 133 |
+
return cases
|
| 134 |
+
|
| 135 |
+
@staticmethod
|
| 136 |
+
def _count(session: requests.Session, query: str) -> int:
|
| 137 |
+
params = {"q": query, "rows": "0", "wt": "json"}
|
| 138 |
+
try:
|
| 139 |
+
resp = session.get(SOLR_URL + "?" + urlencode(params), timeout=60)
|
| 140 |
+
resp.raise_for_status()
|
| 141 |
+
return int(resp.json().get("response", {}).get("numFound", 0))
|
| 142 |
+
except Exception as e:
|
| 143 |
+
log.warning("IT count query failed (%s)", e)
|
| 144 |
+
return 0
|
| 145 |
+
|
| 146 |
+
@staticmethod
|
| 147 |
+
def _to_case(doc: dict[str, Any]) -> Case | None:
|
| 148 |
+
doc_id = _first(doc.get("id"))
|
| 149 |
+
numdec = _first(doc.get("numdec"))
|
| 150 |
+
anno = _first(doc.get("anno"))
|
| 151 |
+
if not numdec or not anno:
|
| 152 |
+
return None
|
| 153 |
+
case_id = f"{numdec}/{anno}"
|
| 154 |
+
|
| 155 |
+
# SentenzeWeb exposes PDFs through the xway "attach" endpoint with the
|
| 156 |
+
# filename rewritten to `.clean.pdf`. The plain `/sncass/{filename}` path
|
| 157 |
+
# returns 404; the JS SPA constructs the URL below when a result is opened.
|
| 158 |
+
filename = _first(doc.get("filename"))
|
| 159 |
+
link: str | None = None
|
| 160 |
+
if filename.endswith(".pdf"):
|
| 161 |
+
clean_id = filename[:-4].lstrip("./") + ".clean.pdf"
|
| 162 |
+
kind = _first(doc.get("kind")) or "snciv"
|
| 163 |
+
link = (
|
| 164 |
+
"https://www.italgiure.giustizia.it/xway/application/nif/clean/hc.dll"
|
| 165 |
+
f"?verbo=attach&db={kind}&id={clean_id}"
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
decision_date = _parse_solr_date(doc.get("datdep")) or _parse_solr_date(
|
| 169 |
+
doc.get("datdec")
|
| 170 |
+
)
|
| 171 |
+
full_text = _clean_ocr(_first(doc.get("ocr")))
|
| 172 |
+
|
| 173 |
+
return Case(
|
| 174 |
+
case_id=case_id,
|
| 175 |
+
link=link,
|
| 176 |
+
decision_date=decision_date,
|
| 177 |
+
jurisdiction="it",
|
| 178 |
+
language="it",
|
| 179 |
+
full_text=full_text or None,
|
| 180 |
+
metadata={
|
| 181 |
+
"doc_id": doc_id,
|
| 182 |
+
"ecli": f"ECLI:IT:CASS:{anno}:{doc_id}" if doc_id and anno else "",
|
| 183 |
+
"filename": filename,
|
| 184 |
+
"tipoprov": _first(doc.get("tipoprov")),
|
| 185 |
+
"szdec": _first(doc.get("szdec")),
|
| 186 |
+
"presidente": _first(doc.get("presidente")),
|
| 187 |
+
"relatore": _first(doc.get("relatore")),
|
| 188 |
+
"materia": _first(doc.get("materia")),
|
| 189 |
+
},
|
| 190 |
+
)
|
legex/scrapers/kr.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
import urllib.parse
|
| 6 |
+
import urllib.request
|
| 7 |
+
from datetime import date
|
| 8 |
+
|
| 9 |
+
from legex.models.base import Case
|
| 10 |
+
from legex.scrapers.base import BaseScraper
|
| 11 |
+
|
| 12 |
+
log = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
API = "https://www.law.go.kr/DRF/lawSearch.do"
|
| 15 |
+
USER_AGENT = "LegEx/1.0 South Korea precedent API"
|
| 16 |
+
DEFAULT_QUERY = "손해배상"
|
| 17 |
+
DEFAULT_DISPLAY = 100
|
| 18 |
+
MAX_RESULTS = 130
|
| 19 |
+
DELAY_SECONDS = 0.2
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _request_json(params: dict[str, str]) -> dict:
|
| 23 |
+
query = urllib.parse.urlencode(params)
|
| 24 |
+
req = urllib.request.Request(
|
| 25 |
+
f"{API}?{query}",
|
| 26 |
+
headers={"User-Agent": USER_AGENT},
|
| 27 |
+
)
|
| 28 |
+
with urllib.request.urlopen(req, timeout=60) as response:
|
| 29 |
+
return json.loads(response.read().decode("utf-8"))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _normalize_date(raw: str) -> str:
|
| 33 |
+
if len(raw) == 8 and raw.isdigit():
|
| 34 |
+
return f"{raw[:4]}-{raw[4:6]}-{raw[6:]}"
|
| 35 |
+
return raw
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class KRScraper(BaseScraper):
|
| 39 |
+
country = "Südkorea"
|
| 40 |
+
|
| 41 |
+
def __init__(self) -> None:
|
| 42 |
+
self._oc = os.environ.get("LAW_GO_KR_OC", "").strip()
|
| 43 |
+
if not self._oc:
|
| 44 |
+
raise ValueError("LAW_GO_KR_OC is required. Set a registered law.go.kr Open API OC value.")
|
| 45 |
+
self._query = os.environ.get("LAW_GO_KR_QUERY", DEFAULT_QUERY)
|
| 46 |
+
|
| 47 |
+
def scrape(
|
| 48 |
+
self,
|
| 49 |
+
start_date: date | None = None,
|
| 50 |
+
end_date: date | None = None,
|
| 51 |
+
) -> list[Case]:
|
| 52 |
+
cases: list[Case] = []
|
| 53 |
+
page = 1
|
| 54 |
+
while len(cases) < MAX_RESULTS:
|
| 55 |
+
params = {
|
| 56 |
+
"OC": self._oc,
|
| 57 |
+
"target": "prec",
|
| 58 |
+
"type": "JSON",
|
| 59 |
+
"query": self._query,
|
| 60 |
+
"display": str(DEFAULT_DISPLAY),
|
| 61 |
+
"page": str(page),
|
| 62 |
+
}
|
| 63 |
+
data = _request_json(params)
|
| 64 |
+
if "result" in data and "실패" in str(data.get("result")):
|
| 65 |
+
raise RuntimeError(json.dumps(data, ensure_ascii=False))
|
| 66 |
+
|
| 67 |
+
prec = data.get("PrecSearch") or data.get("precSearch") or data
|
| 68 |
+
items = prec.get("prec") or prec.get("items") or []
|
| 69 |
+
if isinstance(items, dict):
|
| 70 |
+
items = [items]
|
| 71 |
+
if not items:
|
| 72 |
+
break
|
| 73 |
+
|
| 74 |
+
for item in items:
|
| 75 |
+
court = str(item.get("법원명") or item.get("courtName") or "")
|
| 76 |
+
if court and "대법원" not in court:
|
| 77 |
+
continue
|
| 78 |
+
|
| 79 |
+
raw_date = str(item.get("선고일자") or item.get("decisionDate") or "")
|
| 80 |
+
iso_date = _normalize_date(raw_date)
|
| 81 |
+
decision_date: date | None = None
|
| 82 |
+
if iso_date:
|
| 83 |
+
try:
|
| 84 |
+
decision_date = date.fromisoformat(iso_date)
|
| 85 |
+
except ValueError:
|
| 86 |
+
decision_date = None
|
| 87 |
+
|
| 88 |
+
if start_date and decision_date and decision_date < start_date:
|
| 89 |
+
continue
|
| 90 |
+
if end_date and decision_date and decision_date > end_date:
|
| 91 |
+
continue
|
| 92 |
+
|
| 93 |
+
case_no = str(item.get("사건번호") or item.get("caseNo") or item.get("판례일련번호") or "")
|
| 94 |
+
title = str(item.get("사건명") or item.get("caseName") or item.get("판례명") or "")
|
| 95 |
+
serial = str(item.get("판례일련번호") or item.get("ID") or "")
|
| 96 |
+
link = f"https://www.law.go.kr/precInfoP.do?precSeq={serial}" if serial else ""
|
| 97 |
+
|
| 98 |
+
cases.append(Case(
|
| 99 |
+
case_id=case_no or serial or None,
|
| 100 |
+
link=link or None,
|
| 101 |
+
decision_date=decision_date,
|
| 102 |
+
jurisdiction="kr",
|
| 103 |
+
language="ko",
|
| 104 |
+
full_text=None,
|
| 105 |
+
metadata={"case_title": title} if title else {},
|
| 106 |
+
))
|
| 107 |
+
if len(cases) >= MAX_RESULTS:
|
| 108 |
+
break
|
| 109 |
+
|
| 110 |
+
page += 1
|
| 111 |
+
time.sleep(DELAY_SECONDS)
|
| 112 |
+
|
| 113 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 114 |
+
log.info("Collected %d South Korea Supreme Court cases", len(cases))
|
| 115 |
+
return cases
|
legex/scrapers/li.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Liechtenstein Oberster Gerichtshof (OGH) via gerichtsentscheidungen.li.
|
| 2 |
+
|
| 3 |
+
Endpoints discovered via the worldwidelaw/legal-sources project (AGPL-3.0).
|
| 4 |
+
We reimplement the scraping based on the public AJAX endpoints.
|
| 5 |
+
|
| 6 |
+
Flow:
|
| 7 |
+
1. POST /methods.aspx/getAkten {"s": "OGH.<year>"} → list of (case_number, listing_url).
|
| 8 |
+
2. GET <listing_url> → results page with onclick="…default.aspx?z=…" per record.
|
| 9 |
+
3. GET <detail_url> → metadata divs (hEIItem, aktenzeichen) and the decision text (`<div class='eintrag'>`).
|
| 10 |
+
|
| 11 |
+
The OGH hears both civil and criminal appeals; the source has no civil/criminal
|
| 12 |
+
flag, so `civil_filter()` is a text heuristic (presence of civil-law markers
|
| 13 |
+
like ABGB / ZPO and absence of criminal markers like StGB / StPO).
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import html
|
| 17 |
+
import logging
|
| 18 |
+
import re
|
| 19 |
+
import time
|
| 20 |
+
from datetime import date
|
| 21 |
+
from typing import Any
|
| 22 |
+
|
| 23 |
+
import requests
|
| 24 |
+
|
| 25 |
+
from legex.models.base import Case
|
| 26 |
+
from legex.scrapers.base import BaseScraper
|
| 27 |
+
|
| 28 |
+
log = logging.getLogger(__name__)
|
| 29 |
+
|
| 30 |
+
BASE_URL = "https://www.gerichtsentscheidungen.li"
|
| 31 |
+
AKTEN_URL = f"{BASE_URL}/methods.aspx/getAkten"
|
| 32 |
+
USER_AGENT = "legex-research (open-data, friendly)"
|
| 33 |
+
REQUEST_DELAY_SECONDS = 1.0
|
| 34 |
+
|
| 35 |
+
_ONCLICK_RE = re.compile(r"onclick=\"window\.location='(default\.aspx\?z=[^']+)'\"")
|
| 36 |
+
_HEI_RE = re.compile(r"<div class='fL hEIItem'>([^<]+)</div>")
|
| 37 |
+
_AKTEN_RE = re.compile(
|
| 38 |
+
r"<div[^>]*class=['\"][^'\"]*aktenzeichen[^'\"]*['\"][^>]*>\s*([^<]+?)\s*</div>",
|
| 39 |
+
re.IGNORECASE,
|
| 40 |
+
)
|
| 41 |
+
_EINTRAG_RE = re.compile(
|
| 42 |
+
r"<div class=['\"]eintrag['\"][^>]*>(.*?)</div>\s*</td>",
|
| 43 |
+
re.DOTALL,
|
| 44 |
+
)
|
| 45 |
+
_TAG_RE = re.compile(r"<[^>]+>")
|
| 46 |
+
_XML_DECL_RE = re.compile(r"<\?xml[^>]*\?>")
|
| 47 |
+
_WS_RE = re.compile(r"[ \t]+")
|
| 48 |
+
_BLANK_LINES_RE = re.compile(r"\n{3,}")
|
| 49 |
+
_DATE_RE = re.compile(r"^(\d{1,2})\.(\d{1,2})\.(\d{4})$")
|
| 50 |
+
|
| 51 |
+
CIVIL_MARKERS = ("ABGB", "ZPO", "Zivilrechtssache", "Klagsführer", "Beklagte")
|
| 52 |
+
CRIMINAL_MARKERS = ("StGB", "StPO", "Angeklagte", "Strafsache")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _parse_date(text: str) -> date | None:
|
| 56 |
+
m = _DATE_RE.match((text or "").strip())
|
| 57 |
+
if not m:
|
| 58 |
+
return None
|
| 59 |
+
try:
|
| 60 |
+
return date(int(m.group(3)), int(m.group(2)), int(m.group(1)))
|
| 61 |
+
except ValueError:
|
| 62 |
+
return None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _clean_text(raw_html: str) -> str:
|
| 66 |
+
text = _XML_DECL_RE.sub("", raw_html)
|
| 67 |
+
text = _TAG_RE.sub(" ", text)
|
| 68 |
+
text = html.unescape(text)
|
| 69 |
+
text = _WS_RE.sub(" ", text)
|
| 70 |
+
text = re.sub(r" ?\n ?", "\n", text)
|
| 71 |
+
text = _BLANK_LINES_RE.sub("\n\n", text)
|
| 72 |
+
return text.strip()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class LIScraper(BaseScraper):
|
| 76 |
+
country = "Liechtenstein"
|
| 77 |
+
|
| 78 |
+
def scrape(
|
| 79 |
+
self,
|
| 80 |
+
start_date: date | None = None,
|
| 81 |
+
end_date: date | None = None,
|
| 82 |
+
) -> list[Case]:
|
| 83 |
+
start = start_date or date(2015, 1, 1)
|
| 84 |
+
end = end_date or date(2025, 12, 31)
|
| 85 |
+
|
| 86 |
+
session = requests.Session()
|
| 87 |
+
session.headers.update({"User-Agent": USER_AGENT})
|
| 88 |
+
|
| 89 |
+
cases: list[Case] = []
|
| 90 |
+
seen: set[str] = set()
|
| 91 |
+
|
| 92 |
+
for year in range(start.year, end.year + 1):
|
| 93 |
+
rows = self._get_akten(session, f"OGH.{year}")
|
| 94 |
+
log.info("LI OGH.%d: %d rows", year, len(rows))
|
| 95 |
+
for row in rows:
|
| 96 |
+
if not isinstance(row, list) or len(row) < 2:
|
| 97 |
+
continue
|
| 98 |
+
case_number = (row[0] or "").strip()
|
| 99 |
+
listing_path = (row[1] or "").strip()
|
| 100 |
+
if not case_number or not listing_path or case_number in seen:
|
| 101 |
+
continue
|
| 102 |
+
detail_path = self._find_detail_path(session, listing_path)
|
| 103 |
+
if not detail_path:
|
| 104 |
+
continue
|
| 105 |
+
case = self._fetch_detail(session, case_number, detail_path)
|
| 106 |
+
if case is None:
|
| 107 |
+
continue
|
| 108 |
+
if start_date and case.decision_date and case.decision_date < start_date:
|
| 109 |
+
continue
|
| 110 |
+
if end_date and case.decision_date and case.decision_date > end_date:
|
| 111 |
+
continue
|
| 112 |
+
seen.add(case_number)
|
| 113 |
+
cases.append(case)
|
| 114 |
+
|
| 115 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 116 |
+
log.info("Collected %d Liechtenstein OGH cases", len(cases))
|
| 117 |
+
return cases
|
| 118 |
+
|
| 119 |
+
@staticmethod
|
| 120 |
+
def _get_akten(session: requests.Session, prefix: str) -> list[Any]:
|
| 121 |
+
try:
|
| 122 |
+
resp = session.post(
|
| 123 |
+
AKTEN_URL,
|
| 124 |
+
json={"s": prefix},
|
| 125 |
+
headers={"Content-Type": "application/json; charset=utf-8"},
|
| 126 |
+
timeout=60,
|
| 127 |
+
)
|
| 128 |
+
resp.raise_for_status()
|
| 129 |
+
data = resp.json()
|
| 130 |
+
except Exception as e:
|
| 131 |
+
log.warning("LI getAkten(%s) failed (%s)", prefix, e)
|
| 132 |
+
return []
|
| 133 |
+
time.sleep(REQUEST_DELAY_SECONDS)
|
| 134 |
+
return data.get("d", []) or []
|
| 135 |
+
|
| 136 |
+
@staticmethod
|
| 137 |
+
def _find_detail_path(session: requests.Session, listing_path: str) -> str | None:
|
| 138 |
+
url = f"{BASE_URL}/{listing_path.lstrip('/')}"
|
| 139 |
+
try:
|
| 140 |
+
resp = session.get(url, timeout=60)
|
| 141 |
+
resp.raise_for_status()
|
| 142 |
+
except Exception as e:
|
| 143 |
+
log.warning("LI listing fetch failed %s (%s)", listing_path, e)
|
| 144 |
+
return None
|
| 145 |
+
time.sleep(REQUEST_DELAY_SECONDS)
|
| 146 |
+
for m in _ONCLICK_RE.finditer(resp.text):
|
| 147 |
+
target = m.group(1)
|
| 148 |
+
if "z=" in target and len(target) > 30:
|
| 149 |
+
return target
|
| 150 |
+
return None
|
| 151 |
+
|
| 152 |
+
def _fetch_detail(
|
| 153 |
+
self,
|
| 154 |
+
session: requests.Session,
|
| 155 |
+
case_number: str,
|
| 156 |
+
detail_path: str,
|
| 157 |
+
) -> Case | None:
|
| 158 |
+
url = f"{BASE_URL}/{detail_path.lstrip('/')}"
|
| 159 |
+
try:
|
| 160 |
+
resp = session.get(url, timeout=60)
|
| 161 |
+
resp.raise_for_status()
|
| 162 |
+
except Exception as e:
|
| 163 |
+
log.warning("LI detail fetch failed %s (%s)", case_number, e)
|
| 164 |
+
return None
|
| 165 |
+
time.sleep(REQUEST_DELAY_SECONDS)
|
| 166 |
+
page = resp.text
|
| 167 |
+
|
| 168 |
+
items = _HEI_RE.findall(page)
|
| 169 |
+
decision_date: date | None = None
|
| 170 |
+
decision_type: str | None = None
|
| 171 |
+
court: str | None = None
|
| 172 |
+
for item in items:
|
| 173 |
+
item = item.strip()
|
| 174 |
+
if decision_date is None:
|
| 175 |
+
d = _parse_date(item)
|
| 176 |
+
if d is not None:
|
| 177 |
+
decision_date = d
|
| 178 |
+
continue
|
| 179 |
+
if item in ("OGH", "StGH", "OG", "LG", "VGH"):
|
| 180 |
+
court = item
|
| 181 |
+
continue
|
| 182 |
+
if item in ("Urteil", "Beschluss", "Entscheidung", "Gutachten"):
|
| 183 |
+
decision_type = item
|
| 184 |
+
|
| 185 |
+
# Use the OGH decision number as the unique case_id. The underlying LG
|
| 186 |
+
# `aktenzeichen` (e.g. "09 CG. 2011.232") is the case file at first
|
| 187 |
+
# instance — it can repeat when one underlying case spawns multiple OGH
|
| 188 |
+
# decisions (different appellants, split rulings) on the same day.
|
| 189 |
+
akten_match = _AKTEN_RE.search(page)
|
| 190 |
+
aktenzeichen = akten_match.group(1).strip() if akten_match else ""
|
| 191 |
+
|
| 192 |
+
text_match = _EINTRAG_RE.search(page)
|
| 193 |
+
full_text = _clean_text(text_match.group(1)) if text_match else None
|
| 194 |
+
|
| 195 |
+
return Case(
|
| 196 |
+
case_id=case_number,
|
| 197 |
+
link=url,
|
| 198 |
+
decision_date=decision_date,
|
| 199 |
+
jurisdiction="li",
|
| 200 |
+
language="de",
|
| 201 |
+
full_text=full_text or None,
|
| 202 |
+
metadata={
|
| 203 |
+
"court": court or "OGH",
|
| 204 |
+
"decision_type": decision_type or "",
|
| 205 |
+
"aktenzeichen": aktenzeichen,
|
| 206 |
+
},
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
@staticmethod
|
| 210 |
+
def civil_filter(cases: list[Case]) -> list[Case]:
|
| 211 |
+
kept: list[Case] = []
|
| 212 |
+
for c in cases:
|
| 213 |
+
text = c.full_text or ""
|
| 214 |
+
if not text:
|
| 215 |
+
continue
|
| 216 |
+
if any(marker in text for marker in CRIMINAL_MARKERS):
|
| 217 |
+
continue
|
| 218 |
+
if not any(marker in text for marker in CIVIL_MARKERS):
|
| 219 |
+
continue
|
| 220 |
+
kept.append(c)
|
| 221 |
+
log.info("LI civil_filter kept %d/%d", len(kept), len(cases))
|
| 222 |
+
return kept
|
legex/scrapers/lu.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Luxembourg Cour de cassation via data.public.lu open-data API.
|
| 2 |
+
|
| 3 |
+
Endpoint and dataset slug discovered via the worldwidelaw/legal-sources project
|
| 4 |
+
(AGPL-3.0). We reimplement the scraping based on the public API.
|
| 5 |
+
|
| 6 |
+
The dataset (cour-de-cassation) ships PDF files whose names encode both the
|
| 7 |
+
decision date (YYYYMMDD prefix) and the civil/criminal split: criminal cassation
|
| 8 |
+
PDFs are prefixed `penal`, civil/general cassation PDFs start with the date.
|
| 9 |
+
We rely on that filename flag for `civil_filter()`.
|
| 10 |
+
|
| 11 |
+
Bandwidth optimisation: the Goldenset only needs `sample_n` cases (130). We
|
| 12 |
+
list all metadata up front and pre-sample 130 civil candidates using the same
|
| 13 |
+
seed as the downstream pipeline, then download + OCR PDFs only for that
|
| 14 |
+
shortlist. Downstream `random_sample(seed=0)` is deterministic, so it picks the
|
| 15 |
+
same 130 — and those 130 are the only Cases that carry `full_text`.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import logging
|
| 19 |
+
import random
|
| 20 |
+
import re
|
| 21 |
+
import time
|
| 22 |
+
from datetime import date
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import pdfplumber
|
| 26 |
+
import requests
|
| 27 |
+
|
| 28 |
+
from legex.config import settings
|
| 29 |
+
from legex.models.base import Case
|
| 30 |
+
from legex.scrapers.base import BaseScraper
|
| 31 |
+
|
| 32 |
+
log = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
DATASET_URL = "https://data.public.lu/api/1/datasets/cour-de-cassation/"
|
| 35 |
+
USER_AGENT = "legex-research (open-data, friendly)"
|
| 36 |
+
DOWNLOAD_DELAY_SECONDS = 0.5
|
| 37 |
+
PDF_TIMEOUT = 90
|
| 38 |
+
|
| 39 |
+
_FILENAME_RE = re.compile(r"^(penal)?(\d{4})(\d{2})(\d{2})-")
|
| 40 |
+
_STRIP_SUFFIXES = (
|
| 41 |
+
"-pseudonymise-accessible.pdf",
|
| 42 |
+
"-accessible.pdf",
|
| 43 |
+
".pdf",
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _case_id_from_title(title: str) -> str:
|
| 48 |
+
name = title
|
| 49 |
+
for suffix in _STRIP_SUFFIXES:
|
| 50 |
+
if name.endswith(suffix):
|
| 51 |
+
name = name[: -len(suffix)]
|
| 52 |
+
break
|
| 53 |
+
return name
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _extract_pdf_text(path: Path) -> str | None:
|
| 57 |
+
try:
|
| 58 |
+
with pdfplumber.open(path) as pdf:
|
| 59 |
+
pages = [page.extract_text() or "" for page in pdf.pages]
|
| 60 |
+
text = "\n".join(p for p in pages if p).strip()
|
| 61 |
+
return text or None
|
| 62 |
+
except Exception as e:
|
| 63 |
+
log.warning("LU pdfplumber failed for %s (%s)", path.name, e)
|
| 64 |
+
return None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class LUScraper(BaseScraper):
|
| 68 |
+
country = "Luxemburg"
|
| 69 |
+
|
| 70 |
+
def scrape(
|
| 71 |
+
self,
|
| 72 |
+
start_date: date | None = None,
|
| 73 |
+
end_date: date | None = None,
|
| 74 |
+
) -> list[Case]:
|
| 75 |
+
session = requests.Session()
|
| 76 |
+
session.headers.update({"User-Agent": USER_AGENT, "Accept": "application/json"})
|
| 77 |
+
|
| 78 |
+
try:
|
| 79 |
+
resp = session.get(DATASET_URL, timeout=60)
|
| 80 |
+
resp.raise_for_status()
|
| 81 |
+
dataset = resp.json()
|
| 82 |
+
except Exception as e:
|
| 83 |
+
log.warning("LU dataset fetch failed (%s); returning empty", e)
|
| 84 |
+
return []
|
| 85 |
+
|
| 86 |
+
resources = dataset.get("resources", []) or []
|
| 87 |
+
log.info("LU resources listed: %d", len(resources))
|
| 88 |
+
|
| 89 |
+
cases: list[Case] = []
|
| 90 |
+
seen: set[str] = set()
|
| 91 |
+
|
| 92 |
+
for res in resources:
|
| 93 |
+
title = res.get("title") or ""
|
| 94 |
+
url = res.get("url") or ""
|
| 95 |
+
if not title or not url:
|
| 96 |
+
continue
|
| 97 |
+
m = _FILENAME_RE.match(title)
|
| 98 |
+
if not m:
|
| 99 |
+
continue
|
| 100 |
+
criminal = m.group(1) is not None
|
| 101 |
+
try:
|
| 102 |
+
decision_date = date(int(m.group(2)), int(m.group(3)), int(m.group(4)))
|
| 103 |
+
except ValueError:
|
| 104 |
+
continue
|
| 105 |
+
if start_date and decision_date < start_date:
|
| 106 |
+
continue
|
| 107 |
+
if end_date and decision_date > end_date:
|
| 108 |
+
continue
|
| 109 |
+
|
| 110 |
+
case_id = _case_id_from_title(title)
|
| 111 |
+
if case_id in seen:
|
| 112 |
+
continue
|
| 113 |
+
seen.add(case_id)
|
| 114 |
+
|
| 115 |
+
cases.append(
|
| 116 |
+
Case(
|
| 117 |
+
case_id=case_id,
|
| 118 |
+
link=url,
|
| 119 |
+
decision_date=decision_date,
|
| 120 |
+
jurisdiction="lu",
|
| 121 |
+
language="fr",
|
| 122 |
+
full_text=None,
|
| 123 |
+
metadata={
|
| 124 |
+
"filename": title,
|
| 125 |
+
"criminal_prefix": criminal,
|
| 126 |
+
"resource_id": res.get("id"),
|
| 127 |
+
},
|
| 128 |
+
)
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 132 |
+
|
| 133 |
+
# Pre-sample the civil shortlist using the same seed as the downstream
|
| 134 |
+
# pipeline (legex.processing.filter_and_sample). Both samples operate on
|
| 135 |
+
# the same ordered list, so the picks match — and we only need to
|
| 136 |
+
# download/OCR PDFs for this shortlist.
|
| 137 |
+
civil_cases = [c for c in cases if not c.metadata.get("criminal_prefix")]
|
| 138 |
+
n = min(settings.sample_n, len(civil_cases))
|
| 139 |
+
shortlist = random.Random(settings.sample_seed).sample(civil_cases, n)
|
| 140 |
+
shortlist_ids = {c.case_id for c in shortlist}
|
| 141 |
+
log.info(
|
| 142 |
+
"LU candidates: %d total (%d civil); downloading PDFs for %d sampled",
|
| 143 |
+
len(cases),
|
| 144 |
+
len(civil_cases),
|
| 145 |
+
len(shortlist_ids),
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
cache_dir = settings.data_dir / "cache" / "lu"
|
| 149 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 150 |
+
downloaded = 0
|
| 151 |
+
for case in cases:
|
| 152 |
+
if case.case_id not in shortlist_ids:
|
| 153 |
+
continue
|
| 154 |
+
pdf_path = cache_dir / f"{case.case_id}.pdf"
|
| 155 |
+
if not pdf_path.exists():
|
| 156 |
+
try:
|
| 157 |
+
r = session.get(case.link, timeout=PDF_TIMEOUT)
|
| 158 |
+
r.raise_for_status()
|
| 159 |
+
pdf_path.write_bytes(r.content)
|
| 160 |
+
downloaded += 1
|
| 161 |
+
if downloaded % 25 == 0:
|
| 162 |
+
log.info("LU downloaded %d PDFs", downloaded)
|
| 163 |
+
time.sleep(DOWNLOAD_DELAY_SECONDS)
|
| 164 |
+
except Exception as e:
|
| 165 |
+
log.warning("LU PDF download failed %s (%s)", case.case_id, e)
|
| 166 |
+
continue
|
| 167 |
+
case.full_text = _extract_pdf_text(pdf_path)
|
| 168 |
+
|
| 169 |
+
log.info(
|
| 170 |
+
"Collected %d Luxembourg cases (%d with full_text, %d criminal-prefixed)",
|
| 171 |
+
len(cases),
|
| 172 |
+
sum(1 for c in cases if c.full_text),
|
| 173 |
+
sum(1 for c in cases if c.metadata.get("criminal_prefix")),
|
| 174 |
+
)
|
| 175 |
+
return cases
|
| 176 |
+
|
| 177 |
+
@staticmethod
|
| 178 |
+
def civil_filter(cases: list[Case]) -> list[Case]:
|
| 179 |
+
kept = [c for c in cases if not (c.metadata or {}).get("criminal_prefix")]
|
| 180 |
+
log.info("LU civil_filter kept %d/%d", len(kept), len(cases))
|
| 181 |
+
return kept
|
legex/scrapers/nz.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import hashlib
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import time
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 9 |
+
from datetime import date
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
import pypdf
|
| 13 |
+
import requests
|
| 14 |
+
from dateutil import parser as dateutil_parser
|
| 15 |
+
|
| 16 |
+
from legex.config import settings
|
| 17 |
+
from legex.models.base import Case
|
| 18 |
+
from legex.scrapers.base import BaseScraper
|
| 19 |
+
|
| 20 |
+
# Data source: https://www.justice.govt.nz/jdo-search-api
|
| 21 |
+
# This is the JSON API backing the JDO React frontend (justice.govt.nz/courts/decisions/jdo/).
|
| 22 |
+
# No official public API exists; this endpoint is used by the site's own search UI.
|
| 23 |
+
# Court filter: "SUPREME COURT".
|
| 24 |
+
# Date is embedded in caseName: e.g. "... [2026] NZSC 18 _x000b_[20 March 2026]"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
log = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
BASE_URL = "https://www.justice.govt.nz"
|
| 30 |
+
API_URL = f"{BASE_URL}/jdo-search-api"
|
| 31 |
+
PAGE_SIZE = 50
|
| 32 |
+
USER_AGENT = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:149.0) Gecko/20100101 Firefox/149.0"
|
| 33 |
+
DELAY_SECONDS = 1
|
| 34 |
+
RETRY_DELAY_SECONDS = 30
|
| 35 |
+
PDF_CACHE_DIR = settings.data_dir / "pdfs" / "nz"
|
| 36 |
+
PDF_WORKERS = 8
|
| 37 |
+
|
| 38 |
+
_DATE_RE = re.compile(r"\[(\d{1,2}\s+\w+\s+\d{4})\]\s*$")
|
| 39 |
+
_CITATION_RE = re.compile(r"\[(\d{4})\]\s*NZSC\s*(\d+)")
|
| 40 |
+
|
| 41 |
+
_API_PARAMS: dict = {
|
| 42 |
+
"court": "SUPREME COURT",
|
| 43 |
+
"location": "All",
|
| 44 |
+
"judge": "",
|
| 45 |
+
"counsel": "",
|
| 46 |
+
"caseName": "",
|
| 47 |
+
"fileNumber": "",
|
| 48 |
+
"citation": "",
|
| 49 |
+
"judgmentDate": "All",
|
| 50 |
+
"minuteReference": "",
|
| 51 |
+
"searchTerms": "",
|
| 52 |
+
"sort": "judgmentdate desc",
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _parse_date(text: str) -> date | None:
|
| 57 |
+
text = text.strip()
|
| 58 |
+
if not text:
|
| 59 |
+
return None
|
| 60 |
+
try:
|
| 61 |
+
return date.fromisoformat(text)
|
| 62 |
+
except ValueError:
|
| 63 |
+
pass
|
| 64 |
+
try:
|
| 65 |
+
return dateutil_parser.parse(text, dayfirst=True).date()
|
| 66 |
+
except (ValueError, OverflowError, dateutil_parser.ParserError):
|
| 67 |
+
return None
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _pdf_cache_path(url: str) -> Path:
|
| 71 |
+
h = hashlib.sha1(url.encode()).hexdigest()[:16]
|
| 72 |
+
return PDF_CACHE_DIR / f"{h}.pdf"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _fetch_pdf_text(url: str) -> str:
|
| 76 |
+
pdf_path = _pdf_cache_path(url)
|
| 77 |
+
if not pdf_path.exists():
|
| 78 |
+
pdf_path.parent.mkdir(parents=True, exist_ok=True)
|
| 79 |
+
resp = requests.get(url, timeout=60)
|
| 80 |
+
resp.raise_for_status()
|
| 81 |
+
pdf_path.write_bytes(resp.content)
|
| 82 |
+
reader = pypdf.PdfReader(str(pdf_path))
|
| 83 |
+
parts = [t for p in reader.pages if (t := (p.extract_text() or "").strip())]
|
| 84 |
+
return "\n\n".join(parts)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _fetch_page(session: requests.Session, page_num: int) -> list[dict] | None:
|
| 88 |
+
params = {**_API_PARAMS, "page": page_num}
|
| 89 |
+
try:
|
| 90 |
+
resp = session.get(API_URL, params=params, timeout=15)
|
| 91 |
+
if resp.status_code == 429:
|
| 92 |
+
log.warning(
|
| 93 |
+
"HTTP 429 on page %d — sleeping %ds then retrying", page_num, RETRY_DELAY_SECONDS
|
| 94 |
+
)
|
| 95 |
+
time.sleep(RETRY_DELAY_SECONDS)
|
| 96 |
+
resp = session.get(API_URL, params=params, timeout=15)
|
| 97 |
+
if not resp.ok:
|
| 98 |
+
log.warning("HTTP %d on page %d", resp.status_code, page_num)
|
| 99 |
+
return None
|
| 100 |
+
data = resp.json()
|
| 101 |
+
return data if isinstance(data, list) else data.get("results", [])
|
| 102 |
+
except (requests.RequestException, ValueError) as exc:
|
| 103 |
+
log.warning("Error fetching page %d: %s", page_num, exc)
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class NZScraper(BaseScraper):
|
| 108 |
+
country = "New Zealand"
|
| 109 |
+
|
| 110 |
+
def __init__(self) -> None:
|
| 111 |
+
self._cookie = os.getenv("NZ_WAF_COOKIE", "").strip()
|
| 112 |
+
if not self._cookie:
|
| 113 |
+
raise ValueError("NZ_WAF_COOKIE is required. Set the token from justice.govt.nz.")
|
| 114 |
+
|
| 115 |
+
def scrape(
|
| 116 |
+
self,
|
| 117 |
+
start_date: date | None = None,
|
| 118 |
+
end_date: date | None = None,
|
| 119 |
+
) -> list[Case]:
|
| 120 |
+
session = requests.Session()
|
| 121 |
+
session.headers.update(
|
| 122 |
+
{
|
| 123 |
+
"Accept": "*/*",
|
| 124 |
+
"Accept-Language": "en-US,en;q=0.9",
|
| 125 |
+
"Cookie": self._cookie,
|
| 126 |
+
"Referer": "https://www.justice.govt.nz/courts/decisions/jdo/",
|
| 127 |
+
"Sec-Fetch-Dest": "empty",
|
| 128 |
+
"Sec-Fetch-Mode": "cors",
|
| 129 |
+
"Sec-Fetch-Site": "same-origin",
|
| 130 |
+
"User-Agent": USER_AGENT,
|
| 131 |
+
}
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
cases: list[Case] = []
|
| 135 |
+
seen: set[str] = set()
|
| 136 |
+
|
| 137 |
+
page_num = 1
|
| 138 |
+
while True:
|
| 139 |
+
log.info("Fetching page %d", page_num)
|
| 140 |
+
items = _fetch_page(session, page_num)
|
| 141 |
+
|
| 142 |
+
if not items:
|
| 143 |
+
log.info("Empty or failed page %d — stopping", page_num)
|
| 144 |
+
break
|
| 145 |
+
|
| 146 |
+
all_before_start = True # for early termination when sorted desc
|
| 147 |
+
for item in items:
|
| 148 |
+
url_path = item.get("url", "")
|
| 149 |
+
if not url_path:
|
| 150 |
+
continue
|
| 151 |
+
link = BASE_URL + url_path
|
| 152 |
+
if link in seen:
|
| 153 |
+
continue
|
| 154 |
+
|
| 155 |
+
case_name: str = item.get("caseName", "")
|
| 156 |
+
decision_date: date | None = None
|
| 157 |
+
m = _DATE_RE.search(case_name)
|
| 158 |
+
if m:
|
| 159 |
+
decision_date = _parse_date(m.group(1))
|
| 160 |
+
c = _CITATION_RE.search(case_name)
|
| 161 |
+
case_id = f"[{c.group(1)}] NZSC {c.group(2)}" if c else None
|
| 162 |
+
|
| 163 |
+
if end_date and decision_date and decision_date > end_date:
|
| 164 |
+
continue
|
| 165 |
+
if start_date and decision_date and decision_date >= start_date:
|
| 166 |
+
all_before_start = False
|
| 167 |
+
if start_date and decision_date and decision_date < start_date:
|
| 168 |
+
continue
|
| 169 |
+
|
| 170 |
+
seen.add(link)
|
| 171 |
+
cases.append(
|
| 172 |
+
Case(
|
| 173 |
+
case_id=case_id,
|
| 174 |
+
link=link,
|
| 175 |
+
decision_date=decision_date,
|
| 176 |
+
jurisdiction="nz",
|
| 177 |
+
language="en",
|
| 178 |
+
full_text=None,
|
| 179 |
+
metadata={"caseName": case_name},
|
| 180 |
+
)
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
# Results sorted newest-first: once every item on a page predates
|
| 184 |
+
# start_date, all subsequent pages will too.
|
| 185 |
+
if start_date and all_before_start:
|
| 186 |
+
log.info("All items on page %d predate start_date — stopping early", page_num)
|
| 187 |
+
break
|
| 188 |
+
|
| 189 |
+
if len(items) < PAGE_SIZE:
|
| 190 |
+
log.info("Last page at %d (%d items)", page_num, len(items))
|
| 191 |
+
break
|
| 192 |
+
|
| 193 |
+
time.sleep(DELAY_SECONDS)
|
| 194 |
+
page_num += 1
|
| 195 |
+
|
| 196 |
+
log.info("Collected %d NZ Supreme Court cases", len(cases))
|
| 197 |
+
|
| 198 |
+
todo = [c for c in cases if c.link and not c.full_text]
|
| 199 |
+
log.info("Fetching full_text for %d PDFs", len(todo))
|
| 200 |
+
done = failed = 0
|
| 201 |
+
with ThreadPoolExecutor(max_workers=PDF_WORKERS) as pool:
|
| 202 |
+
futures = {pool.submit(_fetch_pdf_text, c.link): c for c in todo}
|
| 203 |
+
for fut in as_completed(futures):
|
| 204 |
+
case = futures[fut]
|
| 205 |
+
try:
|
| 206 |
+
case.full_text = fut.result()
|
| 207 |
+
done += 1
|
| 208 |
+
except Exception as exc:
|
| 209 |
+
failed += 1
|
| 210 |
+
log.warning("PDF fetch failed for %s: %s", case.case_id, exc)
|
| 211 |
+
if (done + failed) % 25 == 0:
|
| 212 |
+
log.info("PDF progress %d/%d (failed=%d)", done + failed, len(todo), failed)
|
| 213 |
+
log.info("Hydrated %d PDFs (failed=%d)", done, failed)
|
| 214 |
+
return cases
|
legex/scrapers/ph.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import re
|
| 3 |
+
import time
|
| 4 |
+
from datetime import date, datetime
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
import requests
|
| 8 |
+
|
| 9 |
+
from legex.models.base import Case
|
| 10 |
+
from legex.scrapers.base import BaseScraper
|
| 11 |
+
|
| 12 |
+
log = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
HEADERS = {"User-Agent": "Mozilla/5.0 (compatible; LegalResearch/1.0)"}
|
| 15 |
+
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
| 16 |
+
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
|
| 17 |
+
DEFAULT_YEARS = list(range(2026, 2004, -1))
|
| 18 |
+
MAX_CANDIDATES = 500
|
| 19 |
+
DELAY_SECONDS = 0.3
|
| 20 |
+
|
| 21 |
+
_LINK_RE = re.compile(r"<a\s+href='[^']*showdocs/(\d+)/(\d+)'[^>]*>(.*?)</a>", re.DOTALL)
|
| 22 |
+
_CASE_NO_RE = re.compile(r"<STRONG>\s*(.*?)\s*</STRONG>", re.DOTALL)
|
| 23 |
+
_DATE_RE = re.compile(
|
| 24 |
+
r"((?:January|February|March|April|May|June|July|August|September|October|November|December)"
|
| 25 |
+
r"\s+\d{1,2},\s+\d{4})"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _scrape_month(mon: str, year: int) -> tuple[list[dict[str, Any]], str | None]:
|
| 30 |
+
"""Scrape a single month's decisions page."""
|
| 31 |
+
url = f"https://elibrary.judiciary.gov.ph/thebookshelf/docmonth/{mon}/{year}/1"
|
| 32 |
+
cases: list[dict[str, Any]] = []
|
| 33 |
+
try:
|
| 34 |
+
r = requests.get(url, headers=HEADERS, timeout=30)
|
| 35 |
+
r.raise_for_status()
|
| 36 |
+
except Exception as e:
|
| 37 |
+
return cases, str(e)
|
| 38 |
+
|
| 39 |
+
for doc_type, doc_id, inner_html in _LINK_RE.findall(r.text):
|
| 40 |
+
cn_match = _CASE_NO_RE.search(inner_html)
|
| 41 |
+
case_no = cn_match.group(1).strip() if cn_match else ""
|
| 42 |
+
|
| 43 |
+
date_str = ""
|
| 44 |
+
d_match = _DATE_RE.search(inner_html)
|
| 45 |
+
if d_match:
|
| 46 |
+
try:
|
| 47 |
+
dt = datetime.strptime(d_match.group(1), "%B %d, %Y")
|
| 48 |
+
date_str = dt.strftime("%Y-%m-%d")
|
| 49 |
+
except ValueError:
|
| 50 |
+
pass
|
| 51 |
+
|
| 52 |
+
link = f"https://elibrary.judiciary.gov.ph/thebookshelf/showdocsfriendly/{doc_type}/{doc_id}"
|
| 53 |
+
cases.append({"decision_date": date_str, "link": link, "case_id": case_no})
|
| 54 |
+
return cases, None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class PHScraper(BaseScraper):
|
| 58 |
+
country = "Philippinen"
|
| 59 |
+
|
| 60 |
+
def scrape(
|
| 61 |
+
self,
|
| 62 |
+
start_date: date | None = None,
|
| 63 |
+
end_date: date | None = None,
|
| 64 |
+
) -> list[Case]:
|
| 65 |
+
years = DEFAULT_YEARS
|
| 66 |
+
if end_date is not None:
|
| 67 |
+
years = [y for y in years if y <= end_date.year]
|
| 68 |
+
if start_date is not None:
|
| 69 |
+
years = [y for y in years if y >= start_date.year]
|
| 70 |
+
|
| 71 |
+
rows: list[dict[str, Any]] = []
|
| 72 |
+
seen: set[str] = set()
|
| 73 |
+
for year in years:
|
| 74 |
+
if len(rows) >= MAX_CANDIDATES:
|
| 75 |
+
break
|
| 76 |
+
for mon in MONTHS:
|
| 77 |
+
if len(rows) >= MAX_CANDIDATES:
|
| 78 |
+
break
|
| 79 |
+
month_rows, err = _scrape_month(mon, year)
|
| 80 |
+
if err:
|
| 81 |
+
log.warning("PH %s %s: %s", mon, year, err)
|
| 82 |
+
else:
|
| 83 |
+
for row in month_rows:
|
| 84 |
+
if row["link"] in seen:
|
| 85 |
+
continue
|
| 86 |
+
seen.add(row["link"])
|
| 87 |
+
rows.append(row)
|
| 88 |
+
log.info("PH %s %s: %d new (running %d)", mon, year, len(month_rows), len(rows))
|
| 89 |
+
time.sleep(DELAY_SECONDS)
|
| 90 |
+
|
| 91 |
+
cases: list[Case] = []
|
| 92 |
+
for row in rows:
|
| 93 |
+
decision_date: date | None = None
|
| 94 |
+
if row["decision_date"]:
|
| 95 |
+
try:
|
| 96 |
+
decision_date = date.fromisoformat(row["decision_date"])
|
| 97 |
+
except ValueError:
|
| 98 |
+
decision_date = None
|
| 99 |
+
|
| 100 |
+
if start_date and decision_date and decision_date < start_date:
|
| 101 |
+
continue
|
| 102 |
+
if end_date and decision_date and decision_date > end_date:
|
| 103 |
+
continue
|
| 104 |
+
|
| 105 |
+
cases.append(Case(
|
| 106 |
+
case_id=row["case_id"] or None,
|
| 107 |
+
link=row["link"],
|
| 108 |
+
decision_date=decision_date,
|
| 109 |
+
jurisdiction="ph",
|
| 110 |
+
language="en",
|
| 111 |
+
full_text=None,
|
| 112 |
+
metadata={},
|
| 113 |
+
))
|
| 114 |
+
|
| 115 |
+
cases.sort(key=lambda c: c.decision_date or date.min, reverse=True)
|
| 116 |
+
log.info("Collected %d Philippines cases", len(cases))
|
| 117 |
+
return cases
|