| """Render the IAA / Alternative Annotator Test / evaluation CSVs into a minimal ANALYSIS.md. |
| |
| This is a convenience script, it reads the artifacts produced by |
| ``legex-iaa`` (``pairwise_agreement.csv``), by the Alternative Annotator Test |
| reference adapter ``scripts/alt_test_reference.py`` |
| (``alt_test_reference_*.csv``, see the README section "Alternative Annotator |
| Test (AAT)"), by ``scripts/alt_test_decomposition.py`` |
| (``alt_test_decomposition.csv``), and by ``legex-analysis`` (``per_column.csv``), and emits |
| headers, always-true methodology notes, and live tables. Regenerate the whole |
| chain with ``scripts/reproduce_paper.sh``. |
| |
| Usage |
| ----- |
| uv run legex-analysis-report |
| uv run python -m legex.analysis.report --iaa-dir data/analysis/iaa |
| """ |
|
|
| import argparse |
| import csv |
| import math |
| import statistics |
| from pathlib import Path |
|
|
| from legex.analysis.countries import COUNTRY_NAMES |
|
|
| _BUCKETS = ("tp", "mismatch", "missed", "hallucinated", "tn") |
|
|
|
|
| |
| def _read_csv(path: Path) -> list[dict[str, str]]: |
| if not path.exists(): |
| return [] |
| with path.open(encoding="utf-8", newline="") as f: |
| return list(csv.DictReader(f)) |
|
|
|
|
| def _short_model(model: str) -> str: |
| """Display label for a litellm id (drop the provider prefix).""" |
| return model.split("/")[-1] |
|
|
|
|
| def _country_name(cc: str) -> str: |
| return COUNTRY_NAMES.get(cc, cc.upper()) |
|
|
|
|
| def _md_table(headers: list[str], rows: list[list[str]]) -> str: |
| head = "| " + " | ".join(headers) + " |" |
| sep = "| " + " | ".join("---" for _ in headers) + " |" |
| body = "\n".join("| " + " | ".join(r) + " |" for r in rows) |
| return "\n".join([head, sep, body]) if rows else head + "\n" + sep + "\n| _(no data)_ |" |
|
|
|
|
| def _se(p: float, n: int) -> float: |
| """Binomial standard error of a proportion (1σ of the estimate).""" |
| return math.sqrt(p * (1 - p) / n) if n > 0 else 0.0 |
|
|
|
|
| def _pct_se(p: float, n: int) -> str: |
| """Percent with ±1 SE in percentage points, e.g. '49.2% ±3.3'.""" |
| return f"{p:.1%} ±{_se(p, n) * 100:.1f}" |
|
|
|
|
| def _by_field_grid( |
| per_column: list[dict[str, str]], |
| models: list[str], |
| metric_key: str, |
| *, |
| n_buckets: tuple[str, ...] | None, |
| pct: bool = True, |
| ) -> str: |
| """Field × model grid for one derived metric. |
| |
| ``n_buckets`` sums the bucket columns giving the metric's model-independent |
| denominator (shown as ``n``); pass ``None`` when the denominator is |
| model-dependent (precision) or composite (F1) so ``n`` is omitted. |
| """ |
| fields = sorted({r["column"] for r in per_column}) |
| val = {(r["model"], r["column"]): r.get(metric_key, "") for r in per_column} |
| n_by_field: dict[str, int] = {} |
| if n_buckets: |
| for r in per_column: |
| tot = sum(int(r[b]) for b in n_buckets) |
| n_by_field[r["column"]] = max(n_by_field.get(r["column"], 0), tot) |
| rows = [] |
| for field in fields: |
| row = [f"`{field}`"] |
| if n_buckets: |
| row.append(str(n_by_field.get(field, 0))) |
| for m in models: |
| v = val.get((m, field), "") |
| if v in (None, ""): |
| row.append("–") |
| else: |
| row.append(f"{float(v):.1%}" if pct else f"{float(v):.3f}") |
| rows.append(row) |
| headers = ["Field"] + (["n"] if n_buckets else []) + [_short_model(m) for m in models] |
| return _md_table(headers, rows) |
|
|
|
|
| |
| _CATEGORICAL_FIELDS = { |
| "plaintiff_no1_ISIC1_industry_category", |
| "defendant_no1_ISIC1_industry_category", |
| } |
|
|
| |
| _FIELD_TYPE = { |
| "plaintiff_no1_ISIC1_industry_category": "nominal", |
| "defendant_no1_ISIC1_industry_category": "nominal", |
| "legal_subject_judgement": "free text", |
| "trial_start_date": "date", |
| "trial_end_date": "date", |
| "plaintiffs_all_count": "count", |
| "defendants_all_count": "count", |
| "dispute_value_nominal": "monetary", |
| "court_cost_awarded_nominal": "monetary", |
| "party_compensation_awarded_nominal": "monetary", |
| "plaintiff_loosing_share": "ratio", |
| } |
| _TYPE_ORDER = { |
| t: i for i, t in enumerate( |
| ["nominal", "free text", "date", "count", "monetary", "ratio", "other"] |
| ) |
| } |
|
|
|
|
| |
| def _scope(pairwise: list[dict[str, str]]) -> str: |
| annotators = {r["annotator_a"] for r in pairwise} | {r["annotator_b"] for r in pairwise} |
| pairs = {(r["country"], r["annotator_a"], r["annotator_b"]) for r in pairwise} |
| countries = sorted({r["country"] for r in pairwise}) |
| legend = ", ".join(f"**{cc}** {_country_name(cc)}" for cc in countries) |
| secondary = sorted(a for a in annotators if a != "primary") |
| lines = [ |
| "## 1. Scope", |
| "", |
| f"- Countries with ≥2 annotators: **{len(countries)}** — {', '.join(countries) or '(none)'}", |
| f"- Annotators: **{len(annotators)}** (primary + {len(secondary)} secondary: " |
| f"{', '.join(secondary) or '(none)'})", |
| f"- Annotator pairs (country × pair): **{len(pairs)}**", |
| "", |
| f"Countries: {legend}." if legend else "", |
| ] |
| return "\n".join(lines) |
|
|
|
|
| def _agreement_sections(pairwise: list[dict[str, str]]) -> str: |
| note = ( |
| "> **Per-variable agreement.** Percent agreement is reported for every variable, using the " |
| "same value-matching as the evaluation (ISO-date / number-format aware; `0` and empty treated " |
| "alike). For the two **nominal ISIC** fields — the only variables with a fixed controlled " |
| "vocabulary — we additionally report **Cohen's κ**. For the other variables the category space " |
| "is unbounded (free text) or continuous (dates, counts, money, ratios): there κ's chance " |
| "correction collapses toward percent agreement (as the number of categories → ∞, expected " |
| "agreement pₑ → 0 and κ → observed agreement) and awards no partial credit for near-misses, so " |
| "percent agreement is the appropriate summary. Correlation coefficients are deliberately not " |
| "used — for these labels a wrong value is wrong, not partially correct. Cell detail: " |
| "`kappa_audit.csv`." |
| ) |
| out = [ |
| "## 2. Human–human agreement", "", note, "", |
| "_n = paired case comparisons (shared cases × annotator pairs). We report ±1 SE = √(p(1-p)/n) in " |
| "percentage points, a descriptive precision marker. This is not a significance test._", "", |
| ] |
|
|
| by_pair: dict[tuple[str, str, str], list[dict[str, str]]] = {} |
| for r in pairwise: |
| by_pair.setdefault((r["country"], r["annotator_a"], r["annotator_b"]), []).append(r) |
| |
| pair_cases = {k: int(v[0]["n"]) for k, v in by_pair.items()} |
|
|
| def _agg(rows: list[dict[str, str]]) -> tuple[int, float, float]: |
| """(total paired observations, n-weighted tolerant %, mean defined κ).""" |
| n = sum(int(r["n"]) for r in rows) |
| tol = sum(float(r["pct_tolerant"]) * int(r["n"]) for r in rows) / n if n else 0.0 |
| kv = [float(r["cohen_kappa"]) for r in rows if r.get("cohen_kappa") not in (None, "")] |
| mk = statistics.mean(kv) if kv else float("nan") |
| return n, tol, mk |
|
|
| |
| out += ["### 2.1 By variable", ""] |
| by_field: dict[str, list[dict[str, str]]] = {} |
| for r in pairwise: |
| by_field.setdefault(r["field"], []).append(r) |
| order = sorted( |
| by_field, |
| key=lambda f: (_TYPE_ORDER.get(_FIELD_TYPE.get(f, "other"), 99), -_agg(by_field[f])[1]), |
| ) |
| var_rows = [] |
| for field in order: |
| n, tol, mk = _agg(by_field[field]) |
| kappa = f"{mk:.3f}" if (field in _CATEGORICAL_FIELDS and mk == mk) else "—" |
| var_rows.append([f"`{field}`", _FIELD_TYPE.get(field, "other"), str(n), _pct_se(tol, n), kappa]) |
| out.append(_md_table(["Variable", "Type", "n", "% agreement", "Cohen's κ"], var_rows)) |
|
|
| |
| out += ["", "### 2.2 By country", ""] |
| by_cc: dict[str, list[dict[str, str]]] = {} |
| for r in pairwise: |
| by_cc.setdefault(r["country"], []).append(r) |
| cc_rows = [] |
| for cc in sorted(by_cc): |
| pairs = {(r["annotator_a"], r["annotator_b"]) for r in by_cc[cc]} |
| n_cases = sum(pair_cases[(cc, a, b)] for (a, b) in pairs) |
| _n, tol, _mk = _agg(by_cc[cc]) |
| cc_rows.append([cc, str(len(pairs)), str(n_cases), f"{tol:.1%}"]) |
| out.append(_md_table(["Country", "Pairs", "n", "% agreement"], cc_rows)) |
|
|
| |
| out += ["", "### 2.3 By pair", ""] |
| pair_rows = [] |
| for (cc, a, b) in sorted(by_pair): |
| _n, tol, _mk = _agg(by_pair[(cc, a, b)]) |
| pair_rows.append([cc, f"{a} – {b}", str(pair_cases[(cc, a, b)]), f"{tol:.1%}"]) |
| out.append(_md_table(["Country", "Pair", "n", "% agreement"], pair_rows)) |
| return "\n".join(out) |
|
|
|
|
| _ALT_TEST_FORMULA = """### 3.1 How ω and ρ are computed |
| |
| _Definitions from Calderon et al. (2025), as implemented in the authors' `alt_test`. |
| `values_agree` is the tolerant comparator LEGEX passes in as the scoring function._ |
| |
| ```text |
| One jurisdiction, one candidate f, human annotators H = {1..M}, and instances i |
| (here: one (judgment, variable) cell over the 10 structured fields). |
| |
| LEAVE-ONE-OUT. For human j and every instance i the other humans also labelled, |
| let A(i,-j) be the remaining humans' labels and |
| |
| s_f(i,j) = score( f(i), A(i,-j) ) candidate vs. the other humans |
| s_h(i,j) = score( h_j(i), A(i,-j) ) held-out human vs. the same humans |
| |
| score(p, A) = (1/|A|) * SUM_{a in A} values_agree(p, a) in {0, 1/2, 1} |
| |
| ADVANTAGE PROBABILITY of the candidate against human j. Note the ">=", which |
| credits every tie to the candidate: |
| |
| rho_j = (1/n_j) * SUM_i 1[ s_f(i,j) >= s_h(i,j) ] |
| |
| PER-ANNOTATOR TEST. With d_i = 1[s_f < s_h] - 1[s_f >= s_h], so E[d] = 1 - 2*rho_j: |
| |
| H0: E[d] >= epsilon vs. H1: E[d] < epsilon |
| |
| one-sided paired t-test (Wilcoxon signed-rank when n_j < 30), the M p-values |
| corrected by Benjamini-Yekutieli at q = 0.05. Rejecting H0 is therefore |
| equivalent to rho_j being significantly greater than |
| |
| (1 - epsilon) / 2 = 0.4 for the expert tolerance epsilon = 0.2 |
| |
| VERDICT. |
| |
| omega = |{ j : H0_j rejected }| / M winning rate |
| rho = (1/M) * SUM_j rho_j advantage probability |
| "f may substitute a human annotator" <=> omega >= 0.5 |
| ``` |
| |
| Two consequences worth keeping in view when reading §3.2. First, ρ is a |
| **≥**-comparison, so a candidate that merely matches the held-out human on an |
| instance is scored as winning it. Second, with ε = 0.2 the hypothesis test |
| clears at ρ_j > 0.4, not at 0.5. Both are deliberate: the alt-test asks whether |
| a candidate can *substitute* a human annotator, not whether it is *better* than |
| one. §3.4 separates the two. |
| """ |
|
|
|
|
| def _alt_test_section(iaa_dir: Path) -> str: |
| |
| files = sorted(p for p in iaa_dir.glob("alt_test_reference_*.csv")) |
| rows_by_cand: dict[str, list[dict[str, str]]] = {} |
| for p in files: |
| for r in _read_csv(p): |
| rows_by_cand.setdefault(r["candidate"], []).append(r) |
| all_rows = [r for rs in rows_by_cand.values() for r in rs] |
| note = ( |
| "> **Alternative Annotator Test** (Calderon et al. 2025, " |
| "[arXiv:2501.10970](https://arxiv.org/abs/2501.10970)): leave each human annotator out in " |
| "turn and score, per instance, both the candidate and the excluded annotator against the " |
| "remaining annotators; a one-sided test per annotator asks whether the candidate's " |
| "advantage probability trails the human's by less than ε = 0.2 (the expert-annotator " |
| "tolerance), under Benjamini–Yekutieli FDR control at q = 0.05. `passes` = winning rate " |
| "≥ 0.5. Requires ≥ 3 independent annotators per country; free-text fields are excluded. " |
| "ρ is the advantage probability — how likely the candidate annotates as well as or better " |
| "than a randomly chosen human. The *non-trivial* variant drops instances every expert left " |
| "empty: an empty prediction ties those for free, so the gap between the two columns shows " |
| "how much of a pass rests on empty cells. Untestable cells (too few non-empty judgements) " |
| "are excluded from the denominators.\n>\n" |
| "> These numbers come from the **authors' reference implementation** " |
| "([github.com/nitaytech/AltTest](https://github.com/nitaytech/AltTest)) executed on the " |
| "LEGEX data via `scripts/alt_test_reference.py`. See the README section \"Alternative " |
| "Annotator Test (AAT)\" for how to run it. `legex-iaa` does not produce these CSVs." |
| ) |
| out = ["## 3. Alternative-annotator test", "", note, "", _ALT_TEST_FORMULA, ""] |
|
|
| |
| |
| pooled_csv = iaa_dir / "alt_test_pooled.csv" |
| if pooled_csv.exists(): |
| pooled = _read_csv(pooled_csv) |
| out += [ |
| "### 3.2 Headline: pooled per jurisdiction (paper numbers)", |
| "", |
| "_One alt-test per jurisdiction; instance = (judgment, variable) cell over the" |
| " 10 structured fields, so each annotator contributes ~190+ effective instances" |
| " and the paired t-test applies without the paper's n<30 caveat._", |
| "", |
| "| Candidate | Country | ω | ρ | ω (non-triv) | ρ (non-triv) |", |
| "| --- | --- | --- | --- | --- | --- |", |
| ] |
| for r in pooled: |
| out.append( |
| f"| {r['candidate']} | {r['country']} | {float(r['omega']):.2f}" |
| f" | {float(r['rho']):.2f} | {float(r['omega_nontrivial']):.2f}" |
| f" | {float(r['rho_nontrivial']):.2f} |" |
| ) |
| out.append("") |
|
|
| out += ["### 3.3 Per-field diagnostic (cells passed / testable)", ""] |
| if not rows_by_cand: |
| out.append("_No `alt_test_reference_*.csv` found — run `scripts/alt_test_reference.py` (see README)._") |
| return "\n".join(out + ["", _decomposition_section(iaa_dir)]) |
| countries = sorted({r["country"] for r in all_rows}) |
|
|
| def _rate(rows: list[dict[str, str]], key: str) -> str: |
| rows = [r for r in rows if r[key] != ""] |
| if not rows: |
| return "–" |
| p = sum(int(r[key]) for r in rows) |
| return f"{p}/{len(rows)}" |
|
|
| def _mean_rho(rows: list[dict[str, str]], key: str) -> str: |
| vals = [float(r[key]) for r in rows if r[key] != ""] |
| return f"{statistics.mean(vals):.2f}" if vals else "–" |
|
|
| headers = [ |
| "Candidate", "ρ̄ (all)", "Pass (all)", "ρ̄ (non-triv)", "Pass (non-triv)", |
| *(f"{cc} (all · non-triv)" for cc in countries), |
| ] |
| table_rows = [] |
| for cand in sorted(rows_by_cand): |
| rs = rows_by_cand[cand] |
| row = [ |
| _short_model(cand), |
| _mean_rho(rs, "advantage_probability"), |
| _rate(rs, "passes"), |
| _mean_rho(rs, "advantage_probability_nontrivial"), |
| _rate(rs, "passes_nontrivial"), |
| ] |
| for cc in countries: |
| sub = [r for r in rs if r["country"] == cc] |
| row.append(f"{_rate(sub, 'passes')} · {_rate(sub, 'passes_nontrivial')}") |
| table_rows.append(row) |
| out.append(_md_table(headers, table_rows)) |
|
|
| out += [ |
| "", |
| "> Per-cell winning rates and advantage probabilities are in " |
| "`alt_test_reference_<model>.csv`; an empty cell there means the " |
| "(country, field, variant) combination was untestable.", |
| "", |
| _decomposition_section(iaa_dir), |
| ] |
| return "\n".join(out) |
|
|
|
|
| def _decomposition_section(iaa_dir: Path) -> str: |
| """§3.4 — the win/tie/loss counts ρ is built from (substitutable vs. better).""" |
| rows = _read_csv(iaa_dir / "alt_test_decomposition.csv") |
| out = ["### 3.4 Substitutable vs. better: win / tie / loss decomposition", ""] |
| if not rows: |
| out.append( |
| "_No `alt_test_decomposition.csv` found — run " |
| "`uv run python scripts/alt_test_decomposition.py`._" |
| ) |
| return "\n".join(out) |
|
|
| note = ( |
| "> ρ collapses the leave-one-out comparison of §3.1 into one number, and its `≥` " |
| "hands every tie to the candidate. This section keeps the same comparisons and " |
| "reports the counts instead: per held-out human and instance, whether the candidate " |
| "scored **better than**, **the same as**, or **worse than** that human against the two " |
| "remaining humans. Restricted to judgments all three experts labelled, so every " |
| "comparison has exactly two references and a score is 0, ½ or 1. `ρ (alt-test)` is the " |
| "reproduced advantage probability (ties → candidate); `ρ (ties split)` counts a tie as " |
| "half a win for each side. Source: `alt_test_decomposition.csv` from " |
| "`scripts/alt_test_decomposition.py`, which reproduces the reference ρ of §3.2 to " |
| "within 0.02." |
| ) |
| out += [note, ""] |
|
|
| def _pool(candidate: str, variant: str) -> dict[str, int]: |
| keys = ( |
| "n_comparisons", "refs_disagree", "llm_better", "human_better", |
| "tie", "tie_same", "tie_diff", "tie_at_1", "tie_at_half", "tie_at_0", |
| ) |
| totals = dict.fromkeys(keys, 0) |
| for r in rows: |
| if r["candidate"] == candidate and r["variant"] == variant: |
| for k in keys: |
| totals[k] += int(r[k]) |
| return totals |
|
|
| candidates = sorted({r["candidate"] for r in rows}) |
| countries = sorted({r["country"] for r in rows}) |
| headers = [ |
| "Candidate", "Country", "n", "Candidate better", "Tie", "Human better", |
| "ρ (alt-test)", "ρ (ties split)", |
| ] |
| table: list[list[str]] = [] |
| for cand in candidates: |
| for cc in [*countries, "pooled"]: |
| if cc == "pooled": |
| t = _pool(cand, "all") |
| n = t["n_comparisons"] |
| if not n: |
| continue |
| cells = [t["llm_better"], t["tie"], t["human_better"]] |
| rho_alt = (t["llm_better"] + t["tie"]) / n |
| rho_split = (t["llm_better"] + t["tie"] / 2) / n |
| label = "**all three**" |
| else: |
| r = next( |
| (r for r in rows if r["candidate"] == cand |
| and r["country"] == cc and r["variant"] == "all"), |
| None, |
| ) |
| if r is None: |
| continue |
| n = int(r["n_comparisons"]) |
| cells = [int(r["llm_better"]), int(r["tie"]), int(r["human_better"])] |
| rho_alt = float(r["rho_alttest"]) |
| rho_split = float(r["rho_tiebroken"]) |
| label = cc |
| table.append([ |
| _short_model(cand), label, str(n), |
| *(f"{c} ({c / n:.0%})" for c in cells), |
| f"{rho_alt:.2f}", f"{rho_split:.2f}", |
| ]) |
| out.append(_md_table(headers, table)) |
|
|
| |
| pooled_all = {c: _pool(c, "all") for c in candidates} |
| refs_disagree = next( |
| (t["refs_disagree"], t["n_comparisons"]) for t in pooled_all.values() |
| ) |
| out += [ |
| "", |
| "**What is in the “Tie” bucket.** A tie only means *same score against the same two " |
| "references*, so it merges several different situations. Split by score level, and " |
| "independently by whether the candidate actually produced the held-out expert's answer:", |
| "", |
| ] |
| tie_headers = [ |
| "Candidate", "Ties", "Same answer as expert", "Different answer, equal score", |
| "at 1 (all agree)", "at ½ (experts conflict)", "at 0 (both differ)", |
| ] |
| tie_rows = [] |
| for cand in candidates: |
| t = pooled_all[cand] |
| ties = t["tie"] |
| if not ties: |
| continue |
| tie_rows.append([ |
| _short_model(cand), str(ties), |
| *(f"{t[k]} ({t[k] / ties:.0%})" for k in |
| ("tie_same", "tie_diff", "tie_at_1", "tie_at_half", "tie_at_0")), |
| ]) |
| out.append(_md_table(tie_headers, tie_rows)) |
| out += [ |
| "", |
| f"A tie at ½ is only possible when the two reference experts contradict each other — " |
| f"that caps every achievable score at ½, for the candidate and the held-out expert " |
| f"alike. The two references disagree in {refs_disagree[0]} of {refs_disagree[1]} " |
| f"comparisons ({refs_disagree[0] / refs_disagree[1]:.0%}; a property of the human " |
| f"labels, identical for every candidate). Note that reference disagreement is *not* " |
| f"the same thing as a tie: ties also arise, and in fact more often, where the two " |
| f"references agree and the candidate simply matches them.", |
| ] |
|
|
| |
| lines = [] |
| for cand in candidates: |
| t = pooled_all[cand] |
| nt = _pool(cand, "nontrivial") |
| n, ties = t["n_comparisons"], t["tie"] |
| decisive = t["llm_better"] + t["human_better"] |
| if not (n and ties and decisive): |
| continue |
| nontrivial = ( |
| f" Dropping instances whose reference is empty throughout leaves ρ (ties split) at " |
| f"{(nt['llm_better'] + nt['tie'] / 2) / nt['n_comparisons']:.2f}." |
| if nt["n_comparisons"] else "" |
| ) |
| lines.append( |
| f"- **{_short_model(cand)}** — {ties / n:.0%} of the {n} comparisons are ties. " |
| f"{t['tie_same'] / ties:.0%} of those ties are real agreement (candidate gave the " |
| f"held-out expert's answer); the other {t['tie_diff'] / ties:.0%} are comparisons " |
| f"where candidate and expert gave *different* answers that happened to score the " |
| f"same, and ρ credits every one of them to the candidate. On the {decisive} " |
| f"comparisons that actually discriminate, the human wins " |
| f"{t['human_better'] / decisive:.0%} ({t['human_better']} vs " |
| f"{t['llm_better']}).{nontrivial}" |
| ) |
| if lines: |
| out += ["", "**Reading.**", "", *lines] |
|
|
| out += [ |
| "", |
| "This is what the alt-test is and is not evidence for. The tie rate is high and mostly " |
| "genuine, so on this data the models are largely *indistinguishable* from an additional " |
| "expert — which is exactly the substitutability claim ω and ρ are designed to support, " |
| "and §3.2 supports it. It is not evidence of superiority: once ties stop counting as " |
| "wins, ρ sits at chance, and on the comparisons that separate the two the human expert " |
| "is still ahead. \"Can this model replace a human annotator?\" and \"is this model better " |
| "than a human annotator?\" are different questions, and only the first one is being " |
| "tested.", |
| ] |
| return "\n".join(out) |
|
|
|
|
| def _headline_section(per_column: list[dict[str, str]]) -> str: |
| note = ( |
| "> Recall = TP / (TP + Mismatch + Missed) over cells the expert filled; precision = " |
| "TP / (TP + Mismatch + Hallucinated); hallucination = invented values on empty-gold cells. " |
| "Buckets from `legex/evaluation.py`; per-cell source `../per_column.csv`. n = evaluated " |
| "label cells; recall and precision carry ±1 SE over their gold-filled / emitted denominators. " |
| "The per-field grids (§4.2–4.5) break each metric out by variable across models; their `n` is " |
| "the metric's model-independent denominator (gold-filled for recall, gold-empty for " |
| "hallucination) and is omitted for precision (emitted; model-dependent) and F1 (composite)." |
| ) |
| out = ["## 4. Headline extraction metrics", "", note, ""] |
| if not per_column: |
| out.append("_`../per_column.csv` not found — run `legex-analysis`._") |
| return "\n".join(out) |
|
|
| by_model: dict[str, list[dict[str, str]]] = {} |
| for r in per_column: |
| by_model.setdefault(r["model"], []).append(r) |
|
|
| |
| out += ["### 4.1 Overall (all countries, summed across fields)", ""] |
| rows = [] |
| for model in sorted(by_model): |
| b = {k: sum(int(r[k]) for r in by_model[model]) for k in _BUCKETS} |
| tp, mism, miss, hallu, tn = (b[k] for k in _BUCKETS) |
| total = tp + mism + miss + hallu + tn |
| recall = tp / (tp + mism + miss) if (tp + mism + miss) else 0.0 |
| prec = tp / (tp + mism + hallu) if (tp + mism + hallu) else 0.0 |
| acc = (tp + tn) / total if total else 0.0 |
| hallu_rate = hallu / (hallu + tn) if (hallu + tn) else 0.0 |
| f1 = 2 * prec * recall / (prec + recall) if (prec + recall) else 0.0 |
| filled = tp + mism + miss |
| emitted = tp + mism + hallu |
| rows.append([ |
| _short_model(model), str(total), f"{acc:.1%}", |
| _pct_se(recall, filled), _pct_se(prec, emitted), |
| f"{hallu_rate:.1%}", f"{f1:.3f}", |
| ]) |
| out.append(_md_table( |
| ["Model", "n", "Accuracy", "Recall (filled)", "Precision", "Hallu. rate", "F1"], rows |
| )) |
|
|
| |
| models = sorted(by_model) |
| out += ["", "### 4.2 Recall (filled) by field (all countries)", ""] |
| out.append(_by_field_grid(per_column, models, "recall_when_filled", |
| n_buckets=("tp", "mismatch", "missed"))) |
| out += ["", "### 4.3 Precision by field (all countries)", ""] |
| out.append(_by_field_grid(per_column, models, "precision_when_emitted", n_buckets=None)) |
| out += ["", "### 4.4 Hallucination rate by field (all countries)", ""] |
| out.append(_by_field_grid(per_column, models, "hallucination_rate", |
| n_buckets=("hallucinated", "tn"))) |
| out += ["", "### 4.5 F1 by field (all countries)", ""] |
| out.append(_by_field_grid(per_column, models, "f1", n_buckets=None, pct=False)) |
| return "\n".join(out) |
|
|
|
|
| def _appendix() -> str: |
| return "\n".join([ |
| "## Appendix", |
| "", |
| "### Landis–Koch (1977) κ scale (for interpreting the ISIC κ)", |
| "", |
| _md_table( |
| ["κ", "Strength"], |
| [ |
| ["< 0.00", "Poor (worse than chance)"], |
| ["0.00 – 0.20", "Slight"], |
| ["0.21 – 0.40", "Fair"], |
| ["0.41 – 0.60", "Moderate"], |
| ["0.61 – 0.80", "Substantial"], |
| ["0.81 – 1.00", "Almost perfect"], |
| ], |
| ), |
| "", |
| "### Provenance", |
| "", |
| "- Pairwise agreement & kappa: `legex/analysis/iaa.py` (`pairwise_agreement`, " |
| "`write_kappa_audit_csv`).", |
| "- Alt-test: authors' reference implementation " |
| "([github.com/nitaytech/AltTest](https://github.com/nitaytech/AltTest)) run via " |
| "`scripts/alt_test_reference.py` → `alt_test_reference_*.csv` (see README).", |
| "- Alt-test win/tie/loss decomposition: `scripts/alt_test_decomposition.py` → " |
| "`alt_test_decomposition.csv`.", |
| "- Tolerant comparator: `legex/evaluation/comparison.py` (`values_agree`, `normalise`).", |
| "- Headline buckets: `legex/analysis/aggregate.py` over `legex/evaluation.score_country`.", |
| "- This report: `legex/analysis/report.py`.", |
| ]) |
|
|
|
|
| def build_report(iaa_dir: Path, analysis_dir: Path) -> str: |
| pairwise = _read_csv(iaa_dir / "pairwise_agreement.csv") |
| per_column = _read_csv(analysis_dir / "per_column.csv") |
| header = [ |
| "# Inter-Annotator Agreement & Alternative-Annotator Test", |
| "", |
| "_Generated by `legex-analysis-report` from the CSVs in this directory — do not edit by " |
| "hand; numbers always reflect the current CSVs._", |
| "", |
| "Regenerate the whole chain with `scripts/reproduce_paper.sh`.", |
| "", |
| "---", |
| "", |
| ] |
| parts = [ |
| "\n".join(header), |
| _scope(pairwise), |
| _agreement_sections(pairwise), |
| _alt_test_section(iaa_dir), |
| _headline_section(per_column), |
| _appendix(), |
| ] |
| return "\n\n".join(p.strip() for p in parts) + "\n" |
|
|
|
|
| def main(argv: list[str] | None = None) -> int: |
| parser = argparse.ArgumentParser( |
| prog="legex-analysis-report", |
| description="Render the IAA / alt-test / evaluation CSVs into a minimal ANALYSIS.md.", |
| ) |
| parser.add_argument( |
| "--iaa-dir", type=Path, default=Path("data/analysis/iaa"), |
| help="Directory with pairwise_agreement.csv (from legex-iaa) and " |
| "alt_test_reference_*.csv (from scripts/alt_test_reference.py), " |
| "and the output ANALYSIS.md.", |
| ) |
| parser.add_argument( |
| "--analysis-dir", type=Path, default=Path("data/analysis"), |
| help="Directory with per_column.csv (from legex-analysis).", |
| ) |
| parser.add_argument( |
| "--out", type=Path, default=None, |
| help="Output path (default: <iaa-dir>/ANALYSIS.md).", |
| ) |
| args = parser.parse_args(argv) |
| out = args.out or (args.iaa_dir / "ANALYSIS.md") |
| out.parent.mkdir(parents=True, exist_ok=True) |
| out.write_text(build_report(args.iaa_dir, args.analysis_dir), encoding="utf-8") |
| print(f"wrote {out}") |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|