#!/usr/bin/env python3 """Frequency material for the paper appendix: ISIC sectors and currencies. Reads the 19 published goldensets (primary rows with a coded legal subject) and writes * data/analysis/figures/isic_frequencies.pdf — horizontal bar chart of the ISIC top-level sectors observed for plaintiffs and defendants; * data/analysis/tables/currency_frequencies.tex — frequency of the currency labels over the three monetary fields. Usage: uv run python scripts/appendix_frequencies.py """ import argparse import sys from collections import Counter from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO_ROOT)) from legex import published # noqa: E402 from legex.analysis.countries import RELEASE_COUNTRIES # noqa: E402 ISIC_FIELDS = ( "plaintiff_no1_ISIC1_industry_category", "defendant_no1_ISIC1_industry_category", ) CURRENCY_FIELDS = ( "Currency_dispute_value_nominal", "Currency_court_cost_awarded_nominal", "Currency_party_compensation_awarded_nominal", ) FIG_OUT = REPO_ROOT / "data/analysis/figures/isic_frequencies.pdf" TAB_OUT = REPO_ROOT / "data/analysis/tables/currency_frequencies.tex" def _norm(v) -> str: return str(v).strip() if v is not None else "" def collect(gold_dir: Path) -> tuple[Counter, Counter, Counter, int]: isic_p, isic_d, currencies = Counter(), Counter(), Counter() n_judgments = 0 for cc in RELEASE_COUNTRIES: seen: set[str] = set() for rec in published.iter_gold_rows(gold_dir, cc): cid = _norm(rec.get("case_id")) if not cid or cid in seen: # first row per case_id = primary continue seen.add(cid) if not _norm(rec.get("legal_subject_judgement")): continue # released but not fully coded n_judgments += 1 p = _norm(rec.get(ISIC_FIELDS[0])).lower() d = _norm(rec.get(ISIC_FIELDS[1])).lower() if p: isic_p[p] += 1 if d: isic_d[d] += 1 for f in CURRENCY_FIELDS: c = _norm(rec.get(f)).upper() if c: currencies[c] += 1 return isic_p, isic_d, currencies, n_judgments def _pretty(sector: str) -> str: # e.g. "m_real_estate" -> "M — Real estate"; fallback codes stay verbatim. if sector in ("none", "no_allocation_possible"): return sector.replace("_", r"\_") if len(sector) > 2 and sector[1] == "_": letter, rest = sector[0].upper(), sector[2:] return f"{letter} — {rest.replace('_', ' ').capitalize()}" return sector.replace("_", " ") def write_isic_chart(isic_p: Counter, isic_d: Counter) -> None: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt sectors = sorted(set(isic_p) | set(isic_d), key=lambda s: -(isic_p[s] + isic_d[s])) y = range(len(sectors)) p_vals = [isic_p[s] for s in sectors] d_vals = [isic_d[s] for s in sectors] fig, ax = plt.subplots(figsize=(7.0, 0.34 * len(sectors) + 1.2)) h = 0.38 bars_p = ax.barh( [i - h / 2 for i in y], p_vals, height=h, color="#1F4E79", edgecolor="black", linewidth=0.5, label="Plaintiff", ) bars_d = ax.barh( [i + h / 2 for i in y], d_vals, height=h, color="#DD6E6E", edgecolor="black", linewidth=0.5, label="Defendant", ) for bars in (bars_p, bars_d): ax.bar_label(bars, fontsize=6.5, padding=2, color="#374151") ax.set_yticks(list(y)) ax.set_yticklabels([_pretty(s).replace(r"\_", "_") for s in sectors], fontsize=8) ax.invert_yaxis() ax.set_xlabel("Judgments with the sector assigned", fontsize=9) ax.set_xlim(0, max(max(p_vals), max(d_vals)) * 1.08) ax.grid(axis="x", linestyle=":", linewidth=0.6, color="#9CA3AF", alpha=0.7) ax.set_axisbelow(True) ax.legend(title="Party", frameon=True, edgecolor="#6B7280", fontsize=9, title_fontsize=9) ax.tick_params(axis="x", labelsize=8) fig.tight_layout() FIG_OUT.parent.mkdir(parents=True, exist_ok=True) fig.savefig(FIG_OUT) plt.close(fig) print(f"wrote {FIG_OUT} ({len(sectors)} sectors)") # The currency columns are auxiliary audit fields filled in free text; map the # common synonyms to ISO codes, drop the explicit no-currency markers. _CURRENCY_SYNONYMS = {"RUPEES": "INR", "EURO": "EUR", "EUROS": "EUR"} _NO_CURRENCY = {"NONE", "N/A", "NA", "-"} _TOP_N = 12 def write_currency_table(currencies: Counter) -> None: cleaned: Counter = Counter() for cur, n in currencies.items(): if cur in _NO_CURRENCY: continue cleaned[_CURRENCY_SYNONYMS.get(cur, cur)] += n total = sum(cleaned.values()) top = cleaned.most_common(_TOP_N) rest = cleaned.most_common()[_TOP_N:] lines = [ "% Auto-generated by scripts/appendix_frequencies.py — do not edit by hand.", r"\begin{table}[t]", r"\caption{Currencies of the three monetary fields" r" (\texttt{dispute\_value}, \texttt{court\_cost}, \texttt{party\_compensation})" f" over all filled cells of the release with a recorded currency (n\\,=\\,{total:,})." r" Labels as recorded by the annotators, with common synonyms mapped to ISO codes.}", r"\label{tab:currencies}", r"\vskip 0.05in", r"\centering\small", r"\begin{tabular}{@{}lrr@{}}", r"\toprule", r"\textbf{Currency} & \textbf{Cells} & \textbf{Share} \\", r"\midrule", ] for cur, n in top: label = cur.title() if len(cur) > 3 else cur lines.append(f"{label} & {n:,} & {100 * n / total:.1f}\\% \\\\") if rest: n_rest = sum(n for _, n in rest) lines.append( f"Other ({len(rest)} labels) & {n_rest:,} & {100 * n_rest / total:.1f}\\% \\\\" ) lines += [r"\bottomrule", r"\end{tabular}", r"\end{table}", ""] TAB_OUT.parent.mkdir(parents=True, exist_ok=True) TAB_OUT.write_text("\n".join(lines), encoding="utf-8") print(f"wrote {TAB_OUT} ({len(cleaned)} currencies after cleaning)") def main() -> None: ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("--gold-dir", type=Path, default=None, help="published goldenset data directory (default: " "submission/goldensets/data, else ../goldensets/data)") args = ap.parse_args() gold_dir = args.gold_dir or published.default_gold_dir(REPO_ROOT) isic_p, isic_d, currencies, n = collect(gold_dir) print(f"{n} annotated judgments scanned") write_isic_chart(isic_p, isic_d) write_currency_table(currencies) if __name__ == "__main__": main()