| """Goldenset data-quality audit: empty vs. valid vs. malformed per variable. |
| |
| This does *not* judge whether a label is the right answer (there is no |
| reference) — it checks whether each filled cell conforms to the variable's |
| expected type/format, so we can report coding hygiene. Three buckets per cell: |
| |
| - ``empty`` — None / blank (the value is simply absent), |
| - ``valid`` — filled and conforms to the variable's type/format/range/vocab, |
| - ``invalid`` — filled but malformed, e.g. free text where a number is |
| expected, a ratio outside ``[0, 1]``, a non-ISO date, or an ISIC code that is |
| not in the controlled vocabulary. |
| |
| Outputs two tables (CSV + Markdown), matching the request: |
| |
| 1. **By country** — one row per (country, variable) with absolute counts. |
| 2. **Aggregated by variable** — one row per variable, summed over all |
| countries, with counts and percentages. |
| |
| Usage: |
| uv run legex-goldenset-quality |
| uv run legex-goldenset-quality --countries ch,de,br --out data/analysis/quality |
| """ |
|
|
| import argparse |
| import csv |
| import logging |
| import re |
| import sys |
| from collections import defaultdict |
| from datetime import date, datetime |
| from pathlib import Path |
|
|
| from openpyxl import load_workbook |
|
|
| from legex.config import settings |
| from legex.evaluation import is_label_column, normalise |
| from legex.utils import countries_with_goldenset, goldenset_path, goldenset_sheet |
|
|
| log = logging.getLogger("legex.goldenset_quality") |
|
|
| |
| DATE_FIELDS = frozenset({"trial_start_date", "trial_end_date"}) |
| RATIO_FIELDS = frozenset({"plaintiff_loosing_share"}) |
| MONEY_FIELDS = frozenset( |
| {"court_cost_awarded_nominal", "party_compensation_awarded_nominal"} |
| ) |
| |
| DISPUTE_FIELD = "dispute_value_nominal" |
| COUNT_FIELDS = frozenset({"plaintiffs_all_count", "defendants_all_count"}) |
| ISIC_FIELDS = frozenset( |
| {"plaintiff_no1_ISIC1_industry_category", "defendant_no1_ISIC1_industry_category"} |
| ) |
| STRING_FIELDS = frozenset({"legal_subject_judgement"}) |
|
|
| |
| |
| |
| SCHEMA_FIELDS = ( |
| DATE_FIELDS | RATIO_FIELDS | MONEY_FIELDS | {DISPUTE_FIELD} |
| | COUNT_FIELDS | ISIC_FIELDS | STRING_FIELDS |
| ) |
|
|
| |
| ISIC_VOCAB = frozenset( |
| { |
| "a_agriculture_forestry_fishing", "b_mining_quarrying", "c_manufacturing", |
| "d_electricity_gas_steam_ac", "e_water_sewerage_waste_remediation", |
| "f_construction", "g_wholesale_retail_trade", "h_transportation_storage", |
| "i_accommodation_food_service", "j_publishing_broadcasting_content", |
| "k_telecom_it_info_services", "l_financial_insurance", "m_real_estate", |
| "n_professional_scientific_technical", "o_administrative_support", |
| "p_public_admin_defence", "q_education", "r_human_health_social_work", |
| "s_arts_entertainment_recreation", "t_other_service_activities", |
| "u_households_as_employers", "v_extraterritorial_organisations", |
| "no_allocation_possible", |
| } |
| ) |
|
|
| BUCKETS = ("empty", "valid", "invalid") |
|
|
| _NUM_RE = re.compile(r"^-?\d+(?:\.\d+)?$") |
|
|
|
|
| def _is_number(s: str) -> bool: |
| """A clean plain number per the codebook (period decimal, no separators).""" |
| return bool(_NUM_RE.match(s.strip())) |
|
|
|
|
| def _is_int(s: str) -> bool: |
| s = s.strip() |
| if _NUM_RE.match(s): |
| f = float(s) |
| return f.is_integer() and f >= 0 |
| return False |
|
|
|
|
| def _is_iso_date(value: object, normalised: str) -> bool: |
| if isinstance(value, (date, datetime)): |
| return True |
| try: |
| date.fromisoformat(normalised.strip()) |
| return True |
| except ValueError: |
| return False |
|
|
|
|
| def classify_cell(field: str, raw: object) -> str: |
| """Return one of BUCKETS for a single (field, raw cell value).""" |
| s = normalise(raw) |
| if not s: |
| return "empty" |
|
|
| if field in DATE_FIELDS: |
| return "valid" if _is_iso_date(raw, s) else "invalid" |
|
|
| if field == DISPUTE_FIELD: |
| if s.lower() == "nonpecuniary": |
| return "valid" |
| return "valid" if _is_number(s) else "invalid" |
|
|
| if field in MONEY_FIELDS: |
| return "valid" if _is_number(s) else "invalid" |
|
|
| if field in RATIO_FIELDS: |
| if not _is_number(s): |
| return "invalid" |
| return "valid" if 0.0 <= float(s) <= 1.0 else "invalid" |
|
|
| if field in COUNT_FIELDS: |
| return "valid" if _is_int(s) else "invalid" |
|
|
| if field in ISIC_FIELDS: |
| return "valid" if s.lower() in ISIC_VOCAB else "invalid" |
|
|
| if field in STRING_FIELDS: |
| |
| |
| return "invalid" if _is_number(s) else "valid" |
|
|
| |
| return "valid" |
|
|
|
|
| |
| Counts = dict[tuple[str, str], dict[str, int]] |
|
|
|
|
| def audit_country(cc: str) -> tuple[dict[str, dict[str, int]], int]: |
| """Return ({field: {bucket: count}}, n_rows) for one country.""" |
| path = goldenset_path(cc) |
| 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)] |
| label_cols = [h for h in header if is_label_column(h) and h in SCHEMA_FIELDS] |
| per_field: dict[str, dict[str, int]] = { |
| f: {b: 0 for b in BUCKETS} for f in label_cols |
| } |
| n_rows = 0 |
| for row in rows: |
| cells = dict(zip(header, row)) |
| |
| if not any(cells.get(f) not in (None, "") for f in label_cols): |
| continue |
| n_rows += 1 |
| for f in label_cols: |
| per_field[f][classify_cell(f, cells.get(f))] += 1 |
| return per_field, n_rows |
| finally: |
| wb.close() |
|
|
|
|
| def _expected_hint(field: str) -> str: |
| """Human-readable description of the valid form, for the hand-cleaning worklist.""" |
| if field in DATE_FIELDS: |
| return "ISO date YYYY-MM-DD" |
| if field == DISPUTE_FIELD: |
| return "number or 'nonpecuniary'" |
| if field in MONEY_FIELDS: |
| return "number (period decimal, no thousands separators / currency symbols)" |
| if field in RATIO_FIELDS: |
| return "number in [0, 1]" |
| if field in COUNT_FIELDS: |
| return "integer >= 0" |
| if field in ISIC_FIELDS: |
| return "ISIC category from the controlled vocab, or no_allocation_possible" |
| if field in STRING_FIELDS: |
| return "text (not a bare number)" |
| return "" |
|
|
|
|
| def collect_invalid(cc: str) -> list[tuple[str, str, str, str, str]]: |
| """Return one (country, case_id, field, raw_value, expected) row per invalid cell.""" |
| path = goldenset_path(cc) |
| wb = load_workbook(path, read_only=True, data_only=True) |
| out: list[tuple[str, str, str, str, str]] = [] |
| 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)] |
| label_cols = [h for h in header if is_label_column(h) and h in SCHEMA_FIELDS] |
| for row in rows: |
| cells = dict(zip(header, row)) |
| if not any(cells.get(f) not in (None, "") for f in label_cols): |
| continue |
| case_id = cells.get("case_id") |
| case_id = str(case_id) if case_id not in (None, "") else "" |
| for f in label_cols: |
| raw = cells.get(f) |
| if classify_cell(f, raw) == "invalid": |
| out.append((cc, case_id, f, "" if raw is None else str(raw), _expected_hint(f))) |
| return out |
| finally: |
| wb.close() |
|
|
|
|
| def _pct(n: int, total: int) -> float: |
| return n / total if total else 0.0 |
|
|
|
|
| def write_by_country_csv(counts: Counts, 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(["country", "variable", "n", "empty", "valid", "invalid", |
| "pct_empty", "pct_valid", "pct_invalid"]) |
| for (cc, field), c in sorted(counts.items()): |
| total = c["empty"] + c["valid"] + c["invalid"] |
| w.writerow([cc, field, total, c["empty"], c["valid"], c["invalid"], |
| f"{_pct(c['empty'], total):.4f}", |
| f"{_pct(c['valid'], total):.4f}", |
| f"{_pct(c['invalid'], total):.4f}"]) |
|
|
|
|
| def write_by_variable_csv(agg: dict[str, dict[str, int]], 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(["variable", "n", "empty", "valid", "invalid", |
| "pct_empty", "pct_valid", "pct_invalid"]) |
| for field, c in sorted(agg.items()): |
| total = c["empty"] + c["valid"] + c["invalid"] |
| w.writerow([field, total, c["empty"], c["valid"], c["invalid"], |
| f"{_pct(c['empty'], total):.4f}", |
| f"{_pct(c['valid'], total):.4f}", |
| f"{_pct(c['invalid'], total):.4f}"]) |
|
|
|
|
| def write_invalid_csv(rows: list[tuple[str, str, str, str, str]], 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(["country", "case_id", "field", "raw_value", "expected"]) |
| w.writerows(rows) |
|
|
|
|
| def render_markdown(counts: Counts, agg: dict[str, dict[str, int]]) -> str: |
| lines = ["# Goldenset data-quality audit", ""] |
| lines.append("Buckets: **empty** (absent), **valid** (well-typed), " |
| "**invalid** (filled but malformed, e.g. text where a number " |
| "is expected, ratio outside [0,1], non-ISO date, unknown ISIC).") |
| lines.append("") |
|
|
| lines.append("## Aggregated by variable (all countries)") |
| lines.append("") |
| lines.append("| Variable | n | empty | valid | invalid | %empty | %valid | %invalid |") |
| lines.append("|---|---:|---:|---:|---:|---:|---:|---:|") |
| for field, c in sorted(agg.items()): |
| total = c["empty"] + c["valid"] + c["invalid"] |
| lines.append( |
| f"| `{field}` | {total} | {c['empty']} | {c['valid']} | {c['invalid']} | " |
| f"{_pct(c['empty'], total):.1%} | {_pct(c['valid'], total):.1%} | " |
| f"{_pct(c['invalid'], total):.1%} |" |
| ) |
| lines.append("") |
|
|
| lines.append("## By country (absolute counts)") |
| lines.append("") |
| lines.append("| Country | Variable | n | empty | valid | invalid |") |
| lines.append("|---|---|---:|---:|---:|---:|") |
| for (cc, field), c in sorted(counts.items()): |
| total = c["empty"] + c["valid"] + c["invalid"] |
| lines.append( |
| f"| `{cc}` | `{field}` | {total} | {c['empty']} | {c['valid']} | {c['invalid']} |" |
| ) |
| return "\n".join(lines) |
|
|
|
|
| def main(argv: list[str] | None = None) -> int: |
| logging.basicConfig(level=logging.INFO, format="%(message)s") |
| parser = argparse.ArgumentParser(description="Goldenset data-quality audit.") |
| parser.add_argument("--countries", default=None, help="Comma-separated codes (default: all).") |
| parser.add_argument("--out", type=Path, default=None, |
| help="Output dir (default data/analysis/quality).") |
| parser.add_argument("--list-invalid", action="store_true", |
| help="Also write invalid_cells.csv: one row per invalid cell " |
| "(country, case_id, field, raw_value, expected) for hand-cleaning.") |
| args = parser.parse_args(argv) |
|
|
| countries = ( |
| [c.strip() for c in args.countries.split(",") if c.strip()] |
| if args.countries else countries_with_goldenset() |
| ) |
| out_dir = args.out or (settings.data_dir / "analysis" / "quality") |
|
|
| counts: Counts = {} |
| agg: dict[str, dict[str, int]] = defaultdict(lambda: {b: 0 for b in BUCKETS}) |
| for cc in countries: |
| gs = goldenset_path(cc) |
| if not gs.exists(): |
| log.warning("[%s] no goldenset, skipping", cc) |
| continue |
| per_field, n_rows = audit_country(cc) |
| log.info("[%s] %d rows, %d variables", cc, n_rows, len(per_field)) |
| for field, c in per_field.items(): |
| counts[(cc, field)] = c |
| for b in BUCKETS: |
| agg[field][b] += c[b] |
|
|
| if not counts: |
| log.error("no goldensets scored") |
| return 1 |
|
|
| write_by_country_csv(counts, out_dir / "by_country.csv") |
| write_by_variable_csv(agg, out_dir / "by_variable.csv") |
| report = render_markdown(counts, dict(agg)) |
| (out_dir / "report.md").write_text(report, encoding="utf-8") |
|
|
| if args.list_invalid: |
| invalid_rows: list[tuple[str, str, str, str, str]] = [] |
| for cc in countries: |
| if goldenset_path(cc).exists(): |
| invalid_rows.extend(collect_invalid(cc)) |
| write_invalid_csv(invalid_rows, out_dir / "invalid_cells.csv") |
| log.info("wrote %s (%d invalid cells)", |
| out_dir / "invalid_cells.csv", len(invalid_rows)) |
|
|
| |
| width = max((len(f) for f in agg), default=len("variable")) |
| print(f"\n{'variable'.ljust(width)} {'n':>5} {'empty':>6} {'valid':>6} {'invalid':>7}") |
| for field, c in sorted(agg.items()): |
| total = c["empty"] + c["valid"] + c["invalid"] |
| print(f"{field.ljust(width)} {total:>5} " |
| f"{_pct(c['empty'], total):>6.1%} {_pct(c['valid'], total):>6.1%} " |
| f"{_pct(c['invalid'], total):>7.1%}") |
| log.info("\nwrote %s, %s, %s", |
| out_dir / "by_country.csv", out_dir / "by_variable.csv", out_dir / "report.md") |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|