File size: 8,601 Bytes
03859b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
175
176
177
178
179
180
#!/usr/bin/env python3
"""Compute CodeMixCheck statistics directly from the released Parquet files.

    python scripts/dataset_statistics.py                 # print markdown
    python scripts/dataset_statistics.py --json stats.json
    python scripts/dataset_statistics.py --data-dir path/to/other/parquet/root

Every number in README.md's statistics block is produced by `render_markdown()`
in this file; scripts/validate_dataset.py re-runs it and checks that the README
matches byte for byte.

Dependencies: pandas, pyarrow. Optional: wordfreq (heuristic English-lexicon share).
"""
from __future__ import annotations

import argparse
import json
import re
import unicodedata
from pathlib import Path

import pandas as pd

ROOT = Path(__file__).resolve().parents[1]
CONFIGS = ["fact_verification", "sentiment", "abuse_detection"]
SPLIT_ORDER = ["train", "validation", "test_synthetic", "test_curated", "test_human", "silver_unverified"]
TAMIL = "஀-௿"
TOKEN_RE = re.compile(f"[A-Za-z{TAMIL}]+")
TAMIL_RE = re.compile(f"[{TAMIL}]")
LATIN_RE = re.compile(r"[A-Za-z]")
EMOJI_RE = re.compile("[\U0001F000-\U0001FAFF☀-➿⬀-⯿️‍←-⇿⌀-⏿]")


def normalize(text: str) -> str:
    t = unicodedata.normalize("NFC", text).casefold()
    t = EMOJI_RE.sub(" ", t)
    t = re.sub(f"[^a-z0-9{TAMIL}]+", " ", t)
    return re.sub(r"\s+", " ", t).strip()


def load(data_dir: Path) -> dict[str, pd.DataFrame]:
    out = {}
    for cfg in CONFIGS:
        files = sorted((data_dir / cfg).glob("*.parquet"))
        if files:
            out[cfg] = pd.concat([pd.read_parquet(f).assign(_file=f.stem) for f in files], ignore_index=True)
    return out


def _tbl(df: pd.DataFrame) -> str:
    cols = [str(c) for c in df.columns]
    lines = ["| " + " | ".join(cols) + " |", "|" + "|".join(["---"] * len(cols)) + "|"]
    for row in df.itertuples(index=False):
        lines.append("| " + " | ".join(str(v) for v in row) + " |")
    return "\n".join(lines)


def _xtab(df, row, col="_file"):
    t = pd.crosstab(df[row].fillna("(null)"), df[col], margins=True, margins_name="total")
    order = [c for c in SPLIT_ORDER if c in t.columns] + ["total"]
    t = t[order].reset_index().rename(columns={row: row})
    return t


def compute(data: dict[str, pd.DataFrame], with_lexicon: bool = True) -> dict:
    zipf = None
    if with_lexicon:
        try:
            from wordfreq import zipf_frequency as zipf  # noqa: F401
        except ImportError:
            zipf = None
    stats = {}
    for cfg, df in data.items():
        s = {}
        s["rows"] = int(len(df))
        s["split_counts"] = {k: int(v) for k, v in df._file.value_counts().items()}
        s["label_by_split"] = _xtab(df, "label").to_dict("records")
        s["provenance_by_split"] = _xtab(df, "provenance_class").to_dict("records")
        s["label_origin_by_split"] = _xtab(df, "label_origin").to_dict("records")
        s["human_validated_by_split"] = _xtab(df, "human_validated").to_dict("records")
        s["label_status_by_split"] = _xtab(df, "label_status").to_dict("records")
        s["script_by_split"] = _xtab(df, "script").to_dict("records")
        r = df.tamil_script_token_ratio.astype(float)
        ntok = df.text.map(lambda t: len(TOKEN_RE.findall(t)))
        s["code_mixing"] = {
            "mean_tokens_per_text": round(float(ntok.mean()), 2),
            "median_tokens_per_text": float(ntok.median()),
            "tamil_script_token_ratio_mean": round(float(r.mean()), 4),
            "tamil_script_token_ratio_mean_over_texts_with_tamil": round(float(r[r > 0].mean()), 4) if (r > 0).any() else "n/a (no Tamil-script tokens)",
            "pct_texts_with_any_tamil_script": round(100 * float((r > 0).mean()), 2),
            "pct_texts_roman_only": round(100 * float((r == 0).mean()), 2),
            "pct_texts_tamil_script_only": round(100 * float((r == 1).mean()), 2),
            "pct_texts_with_emoji": round(100 * float(df.text.str.contains(EMOJI_RE).mean()), 2),
            "pct_texts_with_hashtag": round(100 * float(df.text.str.contains(r"#\w").mean()), 2),
        }
        if zipf is not None:
            from functools import lru_cache
            z = lru_cache(maxsize=None)(zipf)
            stop = {"la", "nu", "da", "ah", "um", "ku", "na", "vera", "illa", "dha", "dhaan", "than", "ra",
                    "raa", "ma", "mo", "po", "pa", "ya", "eh", "oh", "ne", "nee", "naa", "naan", "un", "en",
                    "ena", "enna", "idhu", "adhu", "aana", "ana", "seri", "sema", "semma", "dei", "poda",
                    "machi", "macha", "bro", "broo", "pola", "kooda", "mattum", "thaan", "va", "vaa", "ok",
                    "okay", "apo", "ipo", "ippo", "appo", "inga", "anga", "oru", "rendu", "moonu", "mela",
                    "kela", "pathi", "paathi", "iru", "irukku", "pannu", "pannunga", "sollu", "sollunga",
                    "tha", "the", "of", "a"}

            def share(t):
                rom = [x.lower() for x in TOKEN_RE.findall(t) if LATIN_RE.search(x)]
                if not rom:
                    return None
                return sum(len(x) >= 3 and x not in stop and z(x, "en") >= 3.5 for x in rom) / len(rom)

            sh = df.text.map(share).dropna()
            s["code_mixing"]["heuristic_english_lexicon_share_of_roman_tokens_mean"] = round(float(sh.mean()), 4)
        # missing values (% null) over all columns
        miss = (df.drop(columns=["_file"]).isna().mean() * 100).round(2)
        s["missing_pct"] = {k: float(v) for k, v in miss.items() if v > 0}
        # duplicates
        norm = df.text.map(normalize)
        s["duplicates"] = {
            "duplicate_ids": int(df.id.duplicated().sum()),
            "exact_duplicate_texts": int(df.text.duplicated().sum()),
            "normalised_duplicate_texts": int(norm.duplicated().sum()),
            "normalised_text_shared_across_splits": int((pd.DataFrame({"n": norm, "f": df._file})
                                                         .groupby("n").f.nunique() > 1).sum()),
            "rows_flagged_near_duplicate_C04": int(df.audit_flags.map(lambda x: "C04" in x).sum()),
            "rows_flagged_cross_split_near_duplicate_D02": int(df.audit_flags.map(lambda x: "D02" in x).sum()),
            "rows_flagged_cross_split_proposition_D01": int(df.audit_flags.map(lambda x: "D01" in x).sum()),
            "is_content_duplicate_true": int(df.is_content_duplicate.sum()),
        }
        if "eval_subset" in df and df.eval_subset.notna().any():
            s["eval_subset_by_label"] = pd.crosstab(df.eval_subset.fillna("(none)"), df.label).reset_index().to_dict("records")
        stats[cfg] = s
    return stats


def render_markdown(data: dict[str, pd.DataFrame], with_lexicon: bool = True) -> str:
    st = compute(data, with_lexicon)
    out = []
    tot = sum(v["rows"] for v in st.values())
    out.append(f"Total records in these files: **{tot}**.\n")
    for cfg, s in st.items():
        out.append(f"#### `{cfg}` ({s['rows']} records)\n")
        df = data[cfg]
        out.append("Label distribution by split:\n")
        out.append(_tbl(_xtab(df, "label")) + "\n")
        out.append("Provenance class by split:\n")
        out.append(_tbl(_xtab(df, "provenance_class")) + "\n")
        out.append("Label origin / human-validation status by split:\n")
        out.append(_tbl(_xtab(df, "label_origin")) + "\n")
        out.append(_tbl(_xtab(df, "human_validated")) + "\n")
        out.append("Script by split:\n")
        out.append(_tbl(_xtab(df, "script")) + "\n")
        cm = s["code_mixing"]
        out.append("Code-mixing / script statistics:\n")
        out.append(_tbl(pd.DataFrame([{"statistic": k, "value": v} for k, v in cm.items()])) + "\n")
        out.append("Duplicate statistics:\n")
        out.append(_tbl(pd.DataFrame([{"check": k, "count": v} for k, v in s["duplicates"].items()])) + "\n")
        out.append("Columns with missing values (% null):\n")
        mp = s["missing_pct"]
        out.append((_tbl(pd.DataFrame([{"column": k, "pct_null": v} for k, v in sorted(mp.items())]))
                    if mp else "none") + "\n")
    return "\n".join(out).rstrip() + "\n"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--data-dir", default=str(ROOT / "data"))
    ap.add_argument("--json")
    ap.add_argument("--no-lexicon", action="store_true")
    a = ap.parse_args()
    data = load(Path(a.data_dir))
    if a.json:
        Path(a.json).write_text(json.dumps(compute(data, not a.no_lexicon), indent=1, default=str))
    print(render_markdown(data, not a.no_lexicon))


if __name__ == "__main__":
    main()