File size: 11,472 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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#!/usr/bin/env python3
"""Validate the CodeMixCheck release folder.

    python scripts/validate_dataset.py                # checks the public repo
    python scripts/validate_dataset.py --hf           # also load every config with `datasets`
    python scripts/validate_dataset.py --report out.md

Exit code 0 = every check PASSed (WARN does not fail the run).
Checks: file integrity (sha256 vs data_manifest.json), row counts, column schema,
label vocabularies, split validity, provenance completeness, duplicates,
missing required values, private-data screen, README statistics block,
CITATION.cff metadata and (optionally) Hugging Face loading.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import re
import sys
from pathlib import Path

import pandas as pd
import pyarrow.parquet as pq

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
from dataset_statistics import load, normalize, render_markdown  # noqa: E402

VERSION = "2.2.1"
LABELS = {
    "fact_verification": {"True", "False", "Partially True", "Unverifiable"},
    "sentiment": {"positive", "negative", "neutral"},
    "abuse_detection": {"abusive", "not_abusive"},
}
LABEL_3WAY = {"True": "SUPPORTED", "False": "REFUTED", "Unverifiable": "NOT_ENOUGH_INFO", "Partially True": None}
SPLITS = {
    "fact_verification": {"train", "validation", "test_synthetic", "test_curated"},
    "sentiment": {"train", "validation", "test_human", "silver_unverified"},
    "abuse_detection": {"train", "validation", "test_synthetic"},
}
COMMON = ["id", "text", "label", "hf_split", "split_v2_2_1", "eval_subset", "cv_fold", "label_status",
          "label_origin", "human_validated", "label_source", "review_flag", "annotation_note", "content_flag",
          "domain", "register", "tone", "post_format", "noise_level", "script", "tamil_script_token_ratio",
          "provenance", "provenance_class", "data_origin", "source_detail", "source_reference", "generator",
          "generation_batch", "release_tier", "template_group", "content_group", "is_content_duplicate",
          "change_v2_1", "change_v2_2", "change_v2_2_1", "audit_flags", "task"]
SPECIFIC = {"fact_verification": ["label_3way", "evidence_explanation", "proposition", "frame_family"],
            "sentiment": ["abuse_label", "sentiment_label_suggested"],
            "abuse_detection": ["sentiment_label"]}
REQUIRED_NON_NULL = ["id", "text", "label", "hf_split", "label_status", "label_origin", "human_validated",
                     "script", "provenance", "provenance_class", "release_tier", "content_group", "task"]
PLACEHOLDER_HANDLES = {"@someone", "@ourvillage_updates", "@localnews_tn", "@classmates_group",
                       "@my_friend_circle", "@somone", "@amma", "@smeone", "@office_gang", "@somene", "@SOMEONE"}

results: list[tuple[str, str, str]] = []


def check(name: str, ok: bool, detail: str = "", warn: bool = False):
    results.append((("PASS" if ok else ("WARN" if warn else "FAIL")), name, detail))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", default=str(ROOT))
    ap.add_argument("--hf", action="store_true", help="also load each config with datasets.load_dataset")
    ap.add_argument("--report")
    ap.add_argument("--allow-withheld", action="store_true",
                    help="permit rows whose release_tier is not public (private/full builds only)")
    a = ap.parse_args()
    root = Path(a.root)
    data_dir = root / "data"

    # ---- manifest / integrity
    man = json.loads((root / "data_manifest.json").read_text())
    files = sorted(data_dir.rglob("*.parquet"))
    listed = {m["path"] for m in man["files"]}
    check("manifest lists exactly the parquet files present",
          listed == {str(f.relative_to(root)) for f in files}, f"{len(files)} files")
    for m in man["files"]:
        p = root / m["path"]
        try:
            pf = pq.ParquetFile(p)
            n = pf.metadata.num_rows
            sha = hashlib.sha256(p.read_bytes()).hexdigest()
            check(f"integrity {m['path']}", sha == m["sha256"], "sha256 match" if sha == m["sha256"] else "sha256 MISMATCH")
            check(f"row count {m['path']}", n == m["rows"], f"{n} rows (manifest {m['rows']})")
        except Exception as e:  # noqa: BLE001
            check(f"readable {m['path']}", False, repr(e))

    data = load(data_dir)
    all_ids, all_text = [], []
    for cfg, df in data.items():
        # ---- schema
        expected = ["id", "text", "label"] + SPECIFIC[cfg] + COMMON[3:]
        cols = [c for c in df.columns if c != "_file"]
        check(f"{cfg}: column schema", cols == expected,
              "ok" if cols == expected else f"missing={set(expected)-set(cols)} extra={set(cols)-set(expected)}")
        types_ok = (str(df.cv_fold.dtype) in ("Int8", "float64", "int8")) and df.tamil_script_token_ratio.dtype.kind == "f" \
            and df.is_content_duplicate.dtype == bool
        check(f"{cfg}: column dtypes", types_ok, f"cv_fold={df.cv_fold.dtype}, ratio={df.tamil_script_token_ratio.dtype}")
        # ---- labels
        bad = df[~df.label.isin(LABELS[cfg])]
        check(f"{cfg}: label vocabulary", bad.empty, f"{len(bad)} invalid")
        check(f"{cfg}: task column", (df.task == cfg).all())
        if cfg == "fact_verification":
            exp3 = df.label.map(LABEL_3WAY)
            ok3 = ((exp3.isna() & df.label_3way.isna()) | (exp3 == df.label_3way)).all()
            check(f"{cfg}: label_3way consistent with label", bool(ok3))
        # ---- splits
        check(f"{cfg}: hf_split matches file name", (df.hf_split == df._file).all())
        check(f"{cfg}: split names valid", set(df._file) <= SPLITS[cfg], str(sorted(set(df._file))))
        syn_in_curated = df[(df._file.isin(["test_curated", "test_human"])) & (df.provenance == "template_generated")]
        nonsyn_in_syn = df[(df._file.isin(["train", "validation", "test_synthetic"])) & (df.provenance != "template_generated")]
        check(f"{cfg}: synthetic and curated/human evaluation subsets not mixed",
              syn_in_curated.empty and nonsyn_in_syn.empty)
        silver_ok = ((df._file == "silver_unverified") == (df.label_status == "silver")).all()
        check(f"{cfg}: silver labels only in silver_unverified", bool(silver_ok))
        if (df.label_status == "silver").any():
            check(f"{cfg}: silver rows never marked human-validated",
                  not df[(df.label_status == "silver")].human_validated.isin(["user_labelled", "yes"]).any())
        # ---- provenance / missing
        nulls = {c: int(df[c].isna().sum()) for c in REQUIRED_NON_NULL}
        check(f"{cfg}: required fields non-null", not any(nulls.values()), str({k: v for k, v in nulls.items() if v}))
        check(f"{cfg}: provenance_class consistent with provenance",
              (df.groupby("provenance").provenance_class.nunique() == 1).all())
        if not a.allow_withheld:
            wh = df[~df.release_tier.str.startswith("public")]
            check(f"{cfg}: no withheld records in public files", wh.empty, f"{len(wh)} withheld rows")
        # ---- private data screen
        urls = df.text.str.contains(r"https?://|www\.", regex=True)
        emails = df.text.str.contains(r"[\w.]+@[\w-]+\.[a-z]{2,}", regex=True)
        phones = df.text.str.contains(r"\b\d{10}\b|\+91", regex=True)
        check(f"{cfg}: no URLs / e-mails / phone numbers in text", not (urls | emails | phones).any(),
              f"url={int(urls.sum())} email={int(emails.sum())} phone={int(phones.sum())}")
        handles = {h for t in df.text for h in re.findall(r"@\w+", t)}
        check(f"{cfg}: @handles limited to documented template placeholders", handles <= PLACEHOLDER_HANDLES,
              f"unexpected={sorted(handles - PLACEHOLDER_HANDLES)}")
        priv_cols = [c for c in df.columns if re.search(r"user(name)?_?handle|profile|url|email|phone", c)]
        check(f"{cfg}: no private-metadata columns", not priv_cols, str(priv_cols))
        # ---- duplicates (within config)
        check(f"{cfg}: unique ids", not df.id.duplicated().any())
        check(f"{cfg}: no exact duplicate texts", not df.text.duplicated().any())
        norm = df.text.map(normalize)
        xs = (pd.DataFrame({"n": norm, "f": df._file}).groupby("n").f.nunique() > 1).sum()
        check(f"{cfg}: no normalised-identical text shared across splits", xs == 0, f"{xs} shared")
        nd = int(df.audit_flags.map(lambda x: "D02" in x or "D01" in x).sum())
        check(f"{cfg}: cross-split near-duplicate / same-claim rows are flagged (not removed)", True,
              f"{nd} rows carry D01/D02 flags - see docs/limitations.md", warn=False)
        all_ids += list(df.id)
        all_text += list(df.text)
    check("ids unique across all configs", len(all_ids) == len(set(all_ids)), f"{len(all_ids)} ids")
    check("texts unique across all configs", len(all_text) == len(set(all_text)))

    # ---- README stats block
    readme = (root / "README.md").read_text()
    m = re.search(r"<!-- STATS:BEGIN -->\n(.*?)<!-- STATS:END -->", readme, re.S)
    if m:
        fresh = render_markdown(data)
        check("README statistics block matches files", m.group(1) == fresh,
              "identical" if m.group(1) == fresh else "README stats are stale - re-run build")
    else:
        check("README statistics block present", False)
    yaml_head = readme.split("---")[1]
    for cfg in data:
        for f in sorted((data_dir / cfg).glob("*.parquet")):
            check(f"README configs reference data/{cfg}/{f.name}", f"data/{cfg}/{f.name}" in yaml_head)
    check("README states version", VERSION in readme)

    # ---- CITATION.cff
    try:
        import yaml  # type: ignore
        cff = yaml.safe_load((root / "CITATION.cff").read_text())
        check("CITATION.cff parses", True)
        check("CITATION.cff version", str(cff.get("version")) == VERSION, str(cff.get("version")))
        check("CITATION.cff type=dataset", cff.get("type") == "dataset")
        check("CITATION.cff has no DOI claimed", "doi" not in cff and "identifiers" not in cff, "", warn=True)
    except Exception as e:  # noqa: BLE001
        check("CITATION.cff parses", False, repr(e))

    # ---- HF loading
    if a.hf:
        try:
            from datasets import load_dataset
            for cfg in data:
                ds = load_dataset(str(root), cfg)
                exp = {k: int(v) for k, v in data[cfg]._file.value_counts().items()}
                got = {k: len(v) for k, v in ds.items()}
                check(f"datasets.load_dataset('{cfg}') split sizes", got == exp, str(got))
        except Exception as e:  # noqa: BLE001
            check("datasets.load_dataset", False, repr(e)[:300])

    width = max(len(r[1]) for r in results)
    lines = [f"{s:4s}  {n.ljust(width)}  {d}" for s, n, d in results]
    print("\n".join(lines))
    n_fail = sum(s == "FAIL" for s, _, _ in results)
    summary = f"\n{len(results)} checks: {sum(s == 'PASS' for s, _, _ in results)} PASS, " \
              f"{sum(s == 'WARN' for s, _, _ in results)} WARN, {n_fail} FAIL"
    print(summary)
    if a.report:
        Path(a.report).write_text("| status | check | detail |\n|---|---|---|\n" +
                                  "\n".join(f"| {s} | {n} | {d.replace('|', '/')} |" for s, n, d in results) +
                                  "\n\n" + summary.strip() + "\n")
    sys.exit(1 if n_fail else 0)


if __name__ == "__main__":
    main()