code / legex /analysis /iaa.py
anonymous
[code] Reproduction bundle.
2e511b5
Raw
History Blame Contribute Delete
18 kB
"""Inter-annotator agreement (IAA).
How much do human experts agree? We collect, per core jurisdiction, the
primary expert labels and the secondary labels of the independent
reannotators, then report per-field exact agreement, tolerant agreement
(numeric/date aware, reusing the evaluation comparator), and Cohen's kappa
for every annotator pair. Annotators are identified by the same salted
``annotator_id`` hashes as the published goldensets (the primary annotation
carries the role label ``primary``).
Inputs
------
- Published mode (``--gold-dir``): the released
``goldensets/data/<cc>/goldenset_<cc>.jsonl`` files — the first row per
``case_id`` is the primary annotation, further rows are reannotations.
- Maintainer mode (default): primary labels from ``data/<cc>/Goldenset_*.xlsx``
plus the returned re-annotation workbooks under
``data/reannotation/incoming/<annotator>/<Country>/`` (folder names are
mapped to hashes via the local ``annotators.json`` + ``ANNOTATOR_SALT``).
- Candidate (system) labels: inference JSONL — loaded here for
``scripts/alt_test_reference.py`` and ``scripts/alt_test_decomposition.py``.
Usage
-----
uv run legex-iaa # human-human agreement
uv run legex-iaa --countries ch,de,br --out data/analysis/iaa
uv run legex-iaa --gold-dir ../goldensets/data # from the published data
"""
import argparse
import csv
import hashlib
import json
import logging
import os
import sys
from collections import defaultdict
from dataclasses import dataclass
from itertools import combinations
from pathlib import Path
from openpyxl import load_workbook
from legex import published
from legex.analysis.countries import CORE_COUNTRIES
from legex.config import settings
from legex.evaluation import is_label_column, normalise, values_agree
from legex.inference import inference_output_path
from legex.published import PRIMARY
from legex.utils import goldenset_path, goldenset_sheet, norm_case_id, read_inference_jsonl
log = logging.getLogger("legex.iaa")
# Folder name (as shipped in the re-annotation pack) -> country code.
FOLDER_TO_CODE: dict[str, str] = {
"Armenia": "am",
"Australia": "au",
"Belgium": "be",
"Brazil": "br",
"France": "fr",
"Georgia": "ge",
"Germany": "de",
"New_Zealand": "nz",
"Philippines": "ph",
"Serbia": "rs",
"Singapore": "sg",
"Spain": "es",
"Switzerland": "ch",
"Taiwan": "tw",
"United_Kingdom": "uk",
"United_States": "us",
}
# (annotator, country, case_id) -> {field: normalised value}
LabelKey = tuple[str, str, str]
LabelMap = dict[LabelKey, dict[str, str]]
def _read_xlsx_labels(path: Path) -> dict[str, dict[str, str]]:
"""case_id -> {label_field: normalised value} from a Goldenset-shaped xlsx."""
wb = load_workbook(path, read_only=True, data_only=True)
try:
ws = goldenset_sheet(wb)
rows = ws.iter_rows(values_only=True)
header = [str(c) if c is not None else "" for c in next(rows)]
# The reannotation pack capitalises the link column ("Link"); both are
# non-label and dropped by is_label_column anyway.
label_cols = [h for h in header if is_label_column(h)]
id_idx = header.index("case_id") if "case_id" in header else 0
out: dict[str, dict[str, str]] = {}
for row in rows:
if not any(c not in (None, "") for c in row):
continue
cells = dict(zip(header, row))
case_id = normalise(row[id_idx])
if not case_id:
continue
labels = {c: normalise(cells.get(c)) for c in label_cols}
out[norm_case_id(case_id)] = labels
return out
finally:
wb.close()
def _read_inference_labels(path: Path) -> dict[str, dict[str, str]]:
"""case_id -> {field: normalised value} from an inference JSONL."""
out: dict[str, dict[str, str]] = {}
for row in read_inference_jsonl(path):
case_id = normalise(row.get("case_id"))
if not case_id:
continue
labels = {k: normalise(v) for k, v in row.items() if is_label_column(k)}
# Failed inference (error set, or nothing extracted at all) is treated
# like absent inference — same rule as evaluation/scoring.py.
if normalise(row.get("error")) or not any(labels.values()):
continue
out[norm_case_id(case_id)] = labels
return out
def incoming_root() -> Path:
return settings.data_dir / "reannotation" / "incoming"
def _annotator_hashes() -> dict[str, str]:
"""``incoming/<folder>`` name -> salted ``annotator_id``, so the maintainer
mode emits the same pseudonymous ids as the published goldensets.
Reads the gitignored ``data/reannotation/annotators.json`` and
``ANNOTATOR_SALT`` (same recipe as ``submission/convert_goldenset_to_jsonl.py``).
"""
path = settings.data_dir / "reannotation" / "annotators.json"
if not path.exists():
return {}
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
salt = os.environ.get("ANNOTATOR_SALT", "")
if not salt:
raise RuntimeError(
"annotators.json found but ANNOTATOR_SALT is unset — refusing to emit "
"annotator names; set the salt so ids match the published goldensets"
)
data = json.loads(path.read_text(encoding="utf-8"))
out: dict[str, str] = {}
for entry in data.get("reannotations", []):
parts = Path(entry["file"]).parts
if "incoming" not in parts:
continue
folder = parts[parts.index("incoming") + 1]
out[folder] = hashlib.sha256(f"{salt}|{entry['name']}".encode("utf-8")).hexdigest()[:10]
return out
def load_human_annotations(countries: list[str], gold_dir: Path | None = None) -> LabelMap:
"""Primary labels + every secondary annotation.
With ``gold_dir`` both come from the published goldenset JSONL; otherwise
from the maintainers' XLSX workbooks (primary) and the returned
re-annotation workbooks under ``data/reannotation/incoming/``.
"""
if gold_dir is not None:
return published.load_annotator_labels(gold_dir, countries)
labels: LabelMap = {}
for cc in countries:
gs = goldenset_path(cc)
if not gs.exists():
log.warning("[%s] no primary goldenset at %s", cc, gs)
continue
for case_id, fields in _read_xlsx_labels(gs).items():
labels[(PRIMARY, cc, case_id)] = fields
root = incoming_root()
if not root.is_dir():
log.info("no returned re-annotations yet (%s absent)", root)
return labels
hashes = _annotator_hashes()
for annotator_dir in sorted(root.iterdir()):
if not annotator_dir.is_dir():
continue
annotator = hashes.get(annotator_dir.name)
if annotator is None:
log.warning(
"[%s] not in annotators.json — skipping (the converter would skip "
"it too, so keeping it here would break XLSX/JSONL parity)",
annotator_dir.name,
)
continue
for country_dir in sorted(annotator_dir.iterdir()):
if not country_dir.is_dir():
continue
cc = FOLDER_TO_CODE.get(country_dir.name, country_dir.name.lower())
if cc not in countries:
continue
wbs = sorted(country_dir.glob("*Reannotate*.xlsx")) or sorted(
country_dir.glob("*Goldenset*.xlsx")
)
if not wbs:
continue
for case_id, fields in _read_xlsx_labels(wbs[0]).items():
# Only keep rows the re-annotator actually filled.
if any(fields.values()):
labels[(annotator, cc, case_id)] = fields
return labels
def load_candidate_annotations(
countries: list[str],
prompt_version: str,
source: str,
model: str,
inference_dir: Path | None = None,
) -> LabelMap:
labels: LabelMap = {}
for cc in countries:
path = (
published.inference_file(inference_dir, cc, model)
if inference_dir is not None
else inference_output_path(cc, prompt_version, source, model)
)
if not path.exists():
log.debug("[%s] no candidate predictions %s", cc, path)
continue
for case_id, fields in _read_inference_labels(path).items():
labels[(model, cc, case_id)] = fields
return labels
def cohen_kappa(pairs: list[tuple[str, str]]) -> float | None:
"""Cohen's kappa on categorical labels (empty string is its own category).
Returns None when fewer than two items or only a single category appears
(kappa undefined / degenerate).
"""
n = len(pairs)
if n < 2:
return None
categories = {a for a, _ in pairs} | {b for _, b in pairs}
if len(categories) < 2:
return None
po = sum(1 for a, b in pairs if a == b) / n
marg_a: dict[str, int] = defaultdict(int)
marg_b: dict[str, int] = defaultdict(int)
for a, b in pairs:
marg_a[a] += 1
marg_b[b] += 1
pe = sum((marg_a[c] / n) * (marg_b[c] / n) for c in categories)
if pe >= 1.0:
return None
return (po - pe) / (1 - pe)
@dataclass
class PairAgreement:
annotator_a: str
annotator_b: str
country: str
field: str
n: int
n_agree_exact: int
n_agree_tolerant: int
kappa: float | None
@property
def pct_exact(self) -> float:
return self.n_agree_exact / self.n if self.n else 0.0
@property
def pct_tolerant(self) -> float:
return self.n_agree_tolerant / self.n if self.n else 0.0
def _shared_cases(
labels: LabelMap, a: str, b: str, country: str
) -> list[str]:
cases_a = {cid for (an, cc, cid) in labels if an == a and cc == country}
cases_b = {cid for (an, cc, cid) in labels if an == b and cc == country}
return sorted(cases_a & cases_b)
def _label_fields(labels: LabelMap) -> list[str]:
fields: list[str] = []
for fmap in labels.values():
for k in fmap:
if k not in fields:
fields.append(k)
return fields
def pairwise_agreement(labels: LabelMap) -> list[PairAgreement]:
annotators = sorted({an for (an, _, _) in labels})
countries = sorted({cc for (_, cc, _) in labels})
fields = _label_fields(labels)
out: list[PairAgreement] = []
for country in countries:
for a, b in combinations(annotators, 2):
shared = _shared_cases(labels, a, b, country)
if not shared:
continue
for field in fields:
pairs: list[tuple[str, str]] = []
n_exact = n_tol = 0
for cid in shared:
av = labels[(a, country, cid)].get(field, "")
bv = labels[(b, country, cid)].get(field, "")
pairs.append((av, bv))
if av == bv:
n_exact += 1
if values_agree(av, bv, field):
n_tol += 1
out.append(
PairAgreement(
annotator_a=a,
annotator_b=b,
country=country,
field=field,
n=len(shared),
n_agree_exact=n_exact,
n_agree_tolerant=n_tol,
kappa=cohen_kappa(pairs),
)
)
return out
# Shared with scripts/alt_test_reference.py (the adapter that runs the
# original authors' Alternative Annotator Test implementation on LEGEX data):
# free-text fields have no meaningful exact/tolerant agreement and are
# excluded from the alt-test.
FREE_TEXT_FIELDS = {"legal_subject_judgement", "translated_full_text"}
# Minimum judgements per annotator for a location test; the reference adapter
# passes this as min_instances_per_human.
MIN_INSTANCES_TEST = 10
def write_pairwise_csv(rows: list[PairAgreement], path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8", newline="") as f:
w = csv.writer(f)
w.writerow(
["annotator_a", "annotator_b", "country", "field", "n",
"pct_exact", "pct_tolerant", "cohen_kappa"]
)
for r in rows:
w.writerow([
r.annotator_a, r.annotator_b, r.country, r.field, r.n,
f"{r.pct_exact:.4f}", f"{r.pct_tolerant:.4f}",
"" if r.kappa is None else f"{r.kappa:.4f}",
])
def write_kappa_audit_csv(labels: LabelMap, path: Path) -> int:
"""Per-cell audit behind the pairwise kappa.
One row per (country, annotator pair, shared case, label field): both
annotators' raw values plus the exact and tolerant agreement decisions. This
is the cell-level detail that ``pairwise_agreement.csv`` aggregates, kept for
inspecting individual disagreements. Returns the number of data rows written.
"""
path.parent.mkdir(parents=True, exist_ok=True)
annotators_by_cc: dict[str, set[str]] = defaultdict(set)
for (an, cc, _cid) in labels:
annotators_by_cc[cc].add(an)
n = 0
with path.open("w", encoding="utf-8", newline="") as f:
w = csv.writer(f)
w.writerow(
["country", "case_id", "annotator_a", "annotator_b", "field",
"value1", "value2", "decision_exact", "decision_tolerant"]
)
for cc in sorted(annotators_by_cc):
for a, b in combinations(sorted(annotators_by_cc[cc]), 2):
for cid in _shared_cases(labels, a, b, cc):
fa = labels[(a, cc, cid)]
fb = labels[(b, cc, cid)]
for field in sorted(set(fa) | set(fb)):
if not is_label_column(field):
continue
va = fa.get(field, "")
vb = fb.get(field, "")
w.writerow([
cc, cid, a, b, field, va, vb,
"yes" if va == vb else "no",
"yes" if values_agree(va, vb, field) else "no",
])
n += 1
return n
def summarise_by_field(rows: list[PairAgreement]) -> dict[str, dict[str, float]]:
"""Weighted (by n) mean exact/tolerant agreement and mean kappa per field."""
acc: dict[str, dict[str, float]] = defaultdict(
lambda: {"n": 0.0, "exact": 0.0, "tol": 0.0, "k_sum": 0.0, "k_n": 0.0}
)
for r in rows:
a = acc[r.field]
a["n"] += r.n
a["exact"] += r.n_agree_exact
a["tol"] += r.n_agree_tolerant
if r.kappa is not None:
a["k_sum"] += r.kappa
a["k_n"] += 1
out: dict[str, dict[str, float]] = {}
for field, a in acc.items():
out[field] = {
"n": a["n"],
"pct_exact": a["exact"] / a["n"] if a["n"] else 0.0,
"pct_tolerant": a["tol"] / a["n"] if a["n"] else 0.0,
"mean_kappa": a["k_sum"] / a["k_n"] if a["k_n"] else float("nan"),
}
return out
def print_field_summary(summary: dict[str, dict[str, float]]) -> None:
width = max((len(f) for f in summary), default=len("field"))
width = max(width, len("field"))
print(f"\n{'field'.ljust(width)} {'n':>6} {'exact':>7} {'tolerant':>9} {'kappa':>7}")
for field, s in summary.items():
k = s["mean_kappa"]
k_s = " - " if k != k else f"{k:>7.3f}" # NaN check
print(
f"{field.ljust(width)} {int(s['n']):>6} "
f"{s['pct_exact']:>7.2%} {s['pct_tolerant']:>9.2%} {k_s}"
)
# CLI
def main(argv: list[str] | None = None) -> int:
logging.basicConfig(level=logging.INFO, format="%(message)s")
parser = argparse.ArgumentParser(description="Inter-annotator agreement.")
parser.add_argument(
"--countries", default=None,
help="Comma-separated country codes (default: the 8 core jurisdictions).",
)
parser.add_argument(
"--out", type=Path, default=None,
help="Output dir (default data/analysis/iaa).",
)
parser.add_argument(
"--gold-dir", type=Path, default=None,
help="Read all annotations from published goldenset JSONL under this "
"directory instead of the XLSX workbooks.",
)
args = parser.parse_args(argv)
countries = (
[c.strip() for c in args.countries.split(",") if c.strip()]
if args.countries else list(CORE_COUNTRIES)
)
out_dir = args.out or (settings.data_dir / "analysis" / "iaa")
humans = load_human_annotations(countries, gold_dir=args.gold_dir)
annotators = sorted({an for (an, _, _) in humans})
secondary = [a for a in annotators if a != PRIMARY]
log.info(
"loaded %d annotation records; annotators=%s",
len(humans), ", ".join(annotators) or "(none)",
)
rows = pairwise_agreement(humans)
if rows:
write_pairwise_csv(rows, out_dir / "pairwise_agreement.csv")
n_audit = write_kappa_audit_csv(humans, out_dir / "kappa_audit.csv")
summary = summarise_by_field(rows)
print_field_summary(summary)
log.info("\nwrote %s", out_dir / "pairwise_agreement.csv")
log.info("wrote %s (%d cells)", out_dir / "kappa_audit.csv", n_audit)
if not secondary:
log.info(
"\nNo secondary (returned) re-annotations found yet, so only primary "
"labels are present and human-human agreement is empty. Drop filled "
"workbooks under %s/<expert>/<Country>/ and re-run.",
incoming_root(),
)
return 0
if __name__ == "__main__":
sys.exit(main())