File size: 6,196 Bytes
2e511b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 | """Loaders for the published LEGEX JSONL bundles (HF ``legexbenchmark``).
The released datasets carry everything the evaluation needs:
- ``goldensets/data/<cc>/goldenset_<cc>.jsonl`` — the first row per
``case_id`` is the primary gold annotation; further rows for the same
``case_id`` are independent reannotations, keyed by their salted
``annotator_id``.
- ``inference-results/data/<cc>/inference_<name>.jsonl`` — one file per
system run, same record layout as ``legex.inference`` output.
These loaders let scoring, IAA, and the AAT run directly on the published
files (pass ``--gold-dir`` / ``--inference-dir`` to the CLIs). The XLSX
workbook mode remains the maintainers' path.
"""
import json
import logging
from pathlib import Path
from legex.evaluation.comparison import is_label_column, normalise
from legex.utils import norm_case_id
log = logging.getLogger(__name__)
# Role label for the primary (gold) annotation, shared with legex.analysis.iaa.
PRIMARY = "primary"
# The 14 schema fields, in template order (see legex/models/classification.py).
SCHEMA_FIELDS: tuple[str, ...] = (
"legal_subject_judgement",
"trial_start_date",
"trial_end_date",
"dispute_value_nominal",
"Currency_dispute_value_nominal",
"plaintiff_loosing_share",
"court_cost_awarded_nominal",
"Currency_court_cost_awarded_nominal",
"party_compensation_awarded_nominal",
"Currency_party_compensation_awarded_nominal",
"plaintiffs_all_count",
"defendants_all_count",
"plaintiff_no1_ISIC1_industry_category",
"defendant_no1_ISIC1_industry_category",
)
# The 11 evaluated fields (currencies are scored via their amount field).
LABEL_FIELDS: tuple[str, ...] = tuple(f for f in SCHEMA_FIELDS if is_label_column(f))
# model id (as used throughout the analysis) -> published file name part.
MODEL_FILES: dict[str, str] = {
"gemini/gemini-3.1-flash-lite": "gemini",
"gpt-5.4-mini": "gpt",
"harvey": "harvey",
"harvey-2": "harvey_2",
"legora-1": "legora_1",
"legora-2": "legora_2",
}
def default_gold_dir(repo_root: Path) -> Path:
"""``submission/goldensets/data`` in the working repo; the sibling
``goldensets`` clone next to the published code bundle."""
for cand in (
repo_root / "submission" / "goldensets" / "data",
repo_root.parent / "goldensets" / "data",
):
if cand.is_dir():
return cand
raise SystemExit(
"no published goldensets found — clone "
"https://huggingface.co/datasets/legexbenchmark/goldensets next to this "
"repository or pass --gold-dir"
)
def default_inference_dir(repo_root: Path) -> Path:
"""``submission/inference-results/data`` in the working repo; the sibling
``inference-results`` clone next to the published code bundle."""
for cand in (
repo_root / "submission" / "inference-results" / "data",
repo_root.parent / "inference-results" / "data",
):
if cand.is_dir():
return cand
raise SystemExit(
"no published inference results found — clone "
"https://huggingface.co/datasets/legexbenchmark/inference-results next to "
"this repository or pass --inference-dir"
)
def gold_file(gold_dir: Path, cc: str) -> Path:
return Path(gold_dir) / cc / f"goldenset_{cc}.jsonl"
def inference_file(inference_dir: Path, cc: str, model: str) -> Path:
name = MODEL_FILES.get(model)
if name is None:
raise KeyError(f"no published inference file for model {model!r}")
return Path(inference_dir) / cc / f"inference_{name}.jsonl"
def countries_with_gold(gold_dir: Path) -> list[str]:
return sorted(p.parent.name for p in Path(gold_dir).glob("*/goldenset_*.jsonl"))
def iter_gold_rows(gold_dir: Path, cc: str) -> list[dict]:
"""Raw records of one published goldenset file, in file order."""
path = gold_file(gold_dir, cc)
# split("\n"), not splitlines(): some full_text values contain U+0085,
# which splitlines() treats as a line break, splitting records in two.
return [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n") if line.strip()]
def load_gold_labels(gold_dir: Path, cc: str) -> tuple[list[str], dict[str, dict[str, str]]]:
"""Return ``(label_columns, {case_id: {field: normalised value}})``.
The first row per ``case_id`` is the primary gold annotation; reannotation
rows appended later in the file are ignored here (use
``load_annotator_labels`` for those). Same return shape and normalisation
as ``legex.evaluation.scoring._read_goldenset_rows``.
"""
by_id: dict[str, dict[str, str]] = {}
for rec in iter_gold_rows(gold_dir, cc):
case_id = normalise(rec.get("case_id"))
if not case_id or case_id in by_id:
continue
by_id[case_id] = {f: normalise(rec.get(f)) for f in LABEL_FIELDS}
return list(LABEL_FIELDS), by_id
def load_annotator_labels(
gold_dir: Path, countries: list[str]
) -> dict[tuple[str, str, str], dict[str, str]]:
"""IAA label map ``{(annotator, cc, norm_case_id): {field: value}}``.
The first row per ``case_id`` carries the role label ``primary`` (matching
the XLSX mode of ``legex.analysis.iaa``); reannotation rows keep their
salted ``annotator_id``. Reannotation rows with no label at all are
dropped, mirroring the XLSX loader.
"""
labels: dict[tuple[str, str, str], dict[str, str]] = {}
for cc in countries:
path = gold_file(gold_dir, cc)
if not path.exists():
log.warning("[%s] no published goldenset at %s", cc, path)
continue
seen: set[str] = set()
for rec in iter_gold_rows(gold_dir, cc):
case_id = normalise(rec.get("case_id"))
if not case_id:
continue
fields = {f: normalise(rec.get(f)) for f in LABEL_FIELDS}
key = norm_case_id(case_id)
if case_id not in seen:
seen.add(case_id)
labels[(PRIMARY, cc, key)] = fields
elif any(fields.values()):
labels[(str(rec.get("annotator_id")), cc, key)] = fields
return labels
|