File size: 6,300 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 163 164 165 166 167 168 169 170 171 172 173 174 | #!/usr/bin/env python3
"""Diversity proxy statistics + legal-subject word cloud (appendix material).
Case-type composition is not part of the LEGEX ground truth, so this script
summarizes sample diversity along the dimensions that ARE annotated: field
coverage, observed ISIC sectors, party structure, and dispute-value coverage.
It also renders a word cloud over the normalized free-text
``legal_subject_judgement`` labels (underscores stripped) for the appendix /
HF dataset card. Reads the published goldenset JSONL (``--gold-dir``).
Usage:
uv run --with wordcloud python scripts/diversity_stats.py
Outputs:
data/analysis/tables/diversity.tex
data/analysis/figures/legal_subject_wordcloud.png
"""
import argparse
import re
import sys
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 COUNTRY_NAMES, RELEASE_COUNTRIES # noqa: E402
COST_BLOCK = (
"dispute_value_nominal",
"plaintiff_loosing_share",
"court_cost_awarded_nominal",
"party_compensation_awarded_nominal",
)
ISIC_FIELDS = (
"plaintiff_no1_ISIC1_industry_category",
"defendant_no1_ISIC1_industry_category",
)
NON_SECTORS = {"", "none", "no_allocation_possible"}
def _stats(cc: str, gold_dir: Path) -> dict | None:
if not published.gold_file(gold_dir, cc).exists():
return None
# Count judgments the same way as the paper: non-empty
# legal_subject_judgement (a few released rows lack it).
_, gold = published.load_gold_labels(gold_dir, cc)
rows = {
cid: f
for cid, f in gold.items()
if f.get("legal_subject_judgement", "").strip()
}
n = len(rows)
if not n:
return None
sectors: set[str] = set()
n_multi = n_dispute = 0
cost_filled = cost_total = 0
subjects: list[str] = []
for fields in rows.values():
for f in ISIC_FIELDS:
v = fields.get(f, "").strip().lower()
if v not in NON_SECTORS:
sectors.add(v)
try:
multi = int(float(fields.get("plaintiffs_all_count") or 0)) > 1 or \
int(float(fields.get("defendants_all_count") or 0)) > 1
except ValueError:
multi = False
n_multi += multi
n_dispute += bool(fields.get("dispute_value_nominal", "").strip())
for f in COST_BLOCK:
cost_total += 1
cost_filled += bool(fields.get(f, "").strip())
subj = fields.get("legal_subject_judgement", "").strip()
if subj:
subjects.append(subj)
return {
"cc": cc,
"n": n,
"sectors": len(sectors),
"pct_multi": 100.0 * n_multi / n,
"pct_dispute": 100.0 * n_dispute / n,
"pct_cost": 100.0 * cost_filled / cost_total,
"subjects": subjects,
}
def _normalise_subject(s: str) -> str:
s = s.replace("_", " ").strip()
s = re.sub(r"\s+", " ", s)
return s.title()
def write_table(all_stats: list[dict], out: Path) -> None:
lines = [
"% Auto-generated by scripts/diversity_stats.py — do not edit by hand.",
r"\begin{table}[t]",
r"\caption{Sample diversity along the annotated dimensions."
r" \emph{Sectors} counts the distinct ISIC top-level sectors observed"
r" among plaintiffs and defendants (of 22 possible, A--V);"
r" \emph{multi-party} is the share of judgments with more than one"
r" plaintiff or defendant; the last two columns give the share of"
r" judgments with a coded dispute value and the fill rate over the"
r" four cost-block fields.}",
r"\label{tab:diversity}",
r"\vskip 0.05in",
r"\centering\small",
r"\begin{tabular}{@{}lrrrrr@{}}",
r"\toprule",
r"\textbf{Jurisdiction} & \textbf{$n$} & \textbf{Sectors}"
r" & \textbf{Multi-party} & \textbf{Dispute value} & \textbf{Cost block} \\",
r"\midrule",
]
for s in all_stats:
lines.append(
f"{COUNTRY_NAMES[s['cc']]} & {s['n']} & {s['sectors']}"
f" & {s['pct_multi']:.0f}\\% & {s['pct_dispute']:.0f}\\%"
f" & {s['pct_cost']:.0f}\\% \\\\"
)
lines += [r"\bottomrule", r"\end{tabular}", r"\end{table}", ""]
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text("\n".join(lines), encoding="utf-8")
print(f"wrote {out}")
def write_wordcloud(subjects: list[str], out: Path) -> None:
from wordcloud import STOPWORDS, WordCloud
# Word-level cloud: full subject labels are long multi-word phrases and
# render as unreadable sentences; individual (stopword-free) terms show
# the topical spread instead.
text = " ".join(_normalise_subject(s) for s in subjects)
stopwords = STOPWORDS | {"Law", "Legal", "Case", "Proceedings", "Procedure"}
wc = WordCloud(
width=1600,
height=900,
background_color="white",
colormap="cividis",
max_words=100,
prefer_horizontal=0.95,
stopwords=stopwords,
collocations=False,
random_state=0, # deterministic layout across runs
).generate(text)
out.parent.mkdir(parents=True, exist_ok=True)
wc.to_file(str(out))
print(f"wrote {out} ({len(subjects)} labels)")
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)
all_stats = []
subjects: list[str] = []
for cc in sorted(RELEASE_COUNTRIES, key=lambda c: COUNTRY_NAMES[c]):
s = _stats(cc, gold_dir)
if s is None:
print(f"[{cc}] no goldenset — skipped", file=sys.stderr)
continue
subjects.extend(s.pop("subjects"))
all_stats.append(s)
write_table(all_stats, REPO_ROOT / "data/analysis/tables/diversity.tex")
write_wordcloud(subjects, REPO_ROOT / "data/analysis/figures/legal_subject_wordcloud.png")
if __name__ == "__main__":
main()
|