File size: 12,452 Bytes
715cc5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
from __future__ import annotations

import argparse
import json
from collections import Counter
from pathlib import Path

from src.data.io_utils import read_jsonl, write_csv, write_json
from src.data.normalize_text import stable_hash


def label_distribution(dataset: str, split: str, rows: list[dict], unit: str) -> list[dict]:
    counts = Counter(row.get("label") if row.get("label") is not None else "UNLABELED" for row in rows)
    return [
        {
            "dataset": dataset,
            "split": split,
            "unit": unit,
            "label": label,
            "count": count,
            "percent": round(count / max(1, len(rows)) * 100, 4),
        }
        for label, count in sorted(counts.items())
    ]


def claim_hashes(rows: list[dict]) -> set[str]:
    hashes = set()
    for row in rows:
        metadata = row.get("metadata") or {}
        hashes.add(metadata.get("claim_norm_hash") or stable_hash(row.get("claim")))
    return hashes


def split_overlap_rows(dataset: str, split_rows: dict[str, list[dict]], unit: str) -> list[dict]:
    rows: list[dict] = []
    names = list(split_rows)
    for i, split_a in enumerate(names):
        for split_b in names[i + 1 :]:
            hashes_a = claim_hashes(split_rows[split_a])
            hashes_b = claim_hashes(split_rows[split_b])
            overlap = sorted(hashes_a & hashes_b)
            rows.append(
                {
                    "dataset": dataset,
                    "split_a": split_a,
                    "split_b": split_b,
                    "unit": unit,
                    "overlap_type": "claim_norm_hash",
                    "overlap_count": len(overlap),
                    "examples": " | ".join(overlap[:5]),
                }
            )
    return rows


def evidence_hashes(rows: list[dict]) -> set[str]:
    hashes = set()
    for row in rows:
        metadata = row.get("metadata") or {}
        if metadata.get("evidence_hash"):
            hashes.add(metadata["evidence_hash"])
    return hashes


def file_exists(path: Path) -> bool:
    return path.exists() and path.stat().st_size > 0


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--data-root", type=Path, default=Path("data_processed"))
    parser.add_argument("--stats-dir", type=Path, default=Path("outputs/stats"))
    parser.add_argument("--tables-dir", type=Path, default=Path("outputs/tables"))
    args = parser.parse_args()

    dataset_stats_rows: list[dict] = []
    label_rows: list[dict] = []
    overlap_rows: list[dict] = []

    vifactcheck = {
        split: read_jsonl(args.data_root / "vifactcheck" / f"claims_{split}.jsonl")
        for split in ["train", "dev", "test"]
    }
    dataset_stats_rows.append(
        {
            "Dataset": "ViFactCheck",
            "Language": "Vietnamese",
            "Domain": "News",
            "Train": len(vifactcheck["train"]),
            "Dev": len(vifactcheck["dev"]),
            "Test": len(vifactcheck["test"]),
            "Evidence source": "Context chunks; gold Evidence diagnostic only",
            "Labels": "SUPPORTS/REFUTES/NEI",
            "Unit": "claim",
        }
    )
    for split, rows in vifactcheck.items():
        label_rows.extend(label_distribution("vifactcheck", split, rows, "claim"))
    overlap_rows.extend(split_overlap_rows("vifactcheck", vifactcheck, "claim"))

    averitec = {
        split: read_jsonl(args.data_root / "averitec" / f"claims_{split}.jsonl")
        for split in ["train_inner", "dev_inner", "local_test", "hidden_test"]
    }
    dataset_stats_rows.append(
        {
            "Dataset": "AVeriTeC",
            "Language": "English",
            "Domain": "Web fact-checking",
            "Train": len(averitec["train_inner"]),
            "Dev": len(averitec["dev_inner"]),
            "Test": f"local_test={len(averitec['local_test'])}; hidden_test={len(averitec['hidden_test'])}",
            "Evidence source": "QA evidence store; hidden test has no local labels",
            "Labels": "SUPPORTS/REFUTES/NEI/CONFLICTING",
            "Unit": "claim",
        }
    )
    for split, rows in averitec.items():
        label_rows.extend(label_distribution("averitec", split, rows, "claim"))
    overlap_rows.extend(split_overlap_rows("averitec", averitec, "claim"))

    healthver_pairs = {
        split: read_jsonl(args.data_root / "healthver" / f"pairs_{split}.jsonl")
        for split in ["train", "dev", "test"]
    }
    dataset_stats_rows.append(
        {
            "Dataset": "HealthVer",
            "Language": "English",
            "Domain": "Health/Biomedical",
            "Train": len(healthver_pairs["train"]),
            "Dev": len(healthver_pairs["dev"]),
            "Test": len(healthver_pairs["test"]),
            "Evidence source": "claim-evidence pairs",
            "Labels": "SUPPORTS/REFUTES/NEI",
            "Unit": "pair",
        }
    )
    for split, rows in healthver_pairs.items():
        label_rows.extend(label_distribution("healthver", split, rows, "pair"))
    healthver_grouped = {
        split: read_jsonl(args.data_root / "healthver" / f"claims_grouped_{split}.jsonl")
        for split in ["train", "dev", "test"]
    }
    overlap_rows.extend(split_overlap_rows("healthver", healthver_grouped, "claim_grouped"))
    for split_a, split_b in [("train", "dev"), ("train", "test"), ("dev", "test")]:
        hashes_a = evidence_hashes(healthver_pairs[split_a])
        hashes_b = evidence_hashes(healthver_pairs[split_b])
        overlap = sorted(hashes_a & hashes_b)
        overlap_rows.append(
            {
                "dataset": "healthver",
                "split_a": split_a,
                "split_b": split_b,
                "unit": "pair",
                "overlap_type": "evidence_text_hash",
                "overlap_count": len(overlap),
                "examples": " | ".join(overlap[:5]),
            }
        )

    write_csv(args.stats_dir / "dataset_statistics.csv", dataset_stats_rows)
    write_csv(args.stats_dir / "label_distribution.csv", label_rows)
    write_csv(args.stats_dir / "split_overlap_report.csv", overlap_rows)
    write_csv(args.tables_dir / "T1_dataset_statistics.csv", dataset_stats_rows)

    label_mapping_rows = [
        {"Dataset": "ViFactCheck", "Raw label": "0", "Canonical label": "SUPPORTS", "Main?": "yes", "Note": "verified local numeric label"},
        {"Dataset": "ViFactCheck", "Raw label": "1", "Canonical label": "REFUTES", "Main?": "yes", "Note": "verified local numeric label"},
        {"Dataset": "ViFactCheck", "Raw label": "2", "Canonical label": "NEI", "Main?": "yes", "Note": "verified local numeric label"},
        {"Dataset": "AVeriTeC", "Raw label": "Supported", "Canonical label": "SUPPORTS", "Main?": "yes", "Note": "4-class"},
        {"Dataset": "AVeriTeC", "Raw label": "Refuted", "Canonical label": "REFUTES", "Main?": "yes", "Note": "4-class"},
        {"Dataset": "AVeriTeC", "Raw label": "Not Enough Evidence", "Canonical label": "NEI", "Main?": "yes", "Note": "4-class"},
        {"Dataset": "AVeriTeC", "Raw label": "Conflicting Evidence/Cherrypicking", "Canonical label": "CONFLICTING", "Main?": "yes", "Note": "not merged in main"},
        {"Dataset": "HealthVer", "Raw label": "Supports", "Canonical label": "SUPPORTS", "Main?": "yes", "Note": "pair-level"},
        {"Dataset": "HealthVer", "Raw label": "Refutes", "Canonical label": "REFUTES", "Main?": "yes", "Note": "pair-level"},
        {"Dataset": "HealthVer", "Raw label": "Neutral", "Canonical label": "NEI", "Main?": "yes", "Note": "pair-level"},
    ]
    write_csv(args.tables_dir / "T2_label_mapping.csv", label_mapping_rows)

    protocol_rows = [
        {"Protocol": "P1", "Dataset": "ViFactCheck", "Input allowed": "Statement + Context chunks", "Forbidden": "Evidence", "Role": "main"},
        {"Protocol": "P2", "Dataset": "ViFactCheck", "Input allowed": "Statement + Context-derived WikiKG", "Forbidden": "Evidence", "Role": "proposed"},
        {"Protocol": "P3", "Dataset": "ViFactCheck", "Input allowed": "Statement + Evidence", "Forbidden": "report as main", "Role": "upper-bound"},
        {"Protocol": "P4", "Dataset": "AVeriTeC", "Input allowed": "Claim + evidence store", "Forbidden": "hidden test label/questions", "Role": "main"},
        {"Protocol": "P5", "Dataset": "AVeriTeC", "Input allowed": "Claim + WikiKG evidence", "Forbidden": "hidden test label", "Role": "proposed"},
        {"Protocol": "P6", "Dataset": "HealthVer", "Input allowed": "Claim + evidence pair", "Forbidden": "test tuning", "Role": "main"},
        {"Protocol": "P7", "Dataset": "HealthVer", "Input allowed": "Claim + evidence-derived WikiKG", "Forbidden": "test tuning", "Role": "proposed"},
        {"Protocol": "P8", "Dataset": "All", "Input allowed": "same evidence without KG/path", "Forbidden": "KG features", "Role": "ablation"},
    ]
    write_csv(args.tables_dir / "T3_protocol_matrix.csv", protocol_rows)

    averitec_split_report = json.loads((args.stats_dir / "averitec_split_report.json").read_text(encoding="utf-8"))
    averitec_local_overlap = [
        row
        for row in overlap_rows
        if row["dataset"] == "averitec"
        and {row["split_a"], row["split_b"]} in [{"train_inner", "local_test"}, {"dev_inner", "local_test"}]
    ]
    leakage_checks = {
        "raw_manifest_exists": file_exists(args.stats_dir / "raw_file_manifest.csv"),
        "vifactcheck_context_evidence_separated": file_exists(args.data_root / "vifactcheck" / "context_chunks.jsonl")
        and file_exists(args.data_root / "vifactcheck" / "gold_evidence.jsonl"),
        "averitec_local_test_is_official_dev_labeled": all(row.get("label") not in (None, "UNLABELED") for row in averitec["local_test"]),
        "averitec_hidden_test_has_no_local_labels": all(row.get("label") is None for row in averitec["hidden_test"])
        and not averitec_split_report["official"]["hidden_test_has_labels"],
        "averitec_no_train_or_dev_inner_overlap_with_local_test": all(int(row["overlap_count"]) == 0 for row in averitec_local_overlap),
        "healthver_pair_files_exist": all(file_exists(args.data_root / "healthver" / f"pairs_{split}.jsonl") for split in ["train", "dev", "test"]),
        "healthver_grouped_claim_files_exist": all(
            file_exists(args.data_root / "healthver" / f"claims_grouped_{split}.jsonl") for split in ["train", "dev", "test"]
        ),
        "tables_t1_t2_t3_exist": all(file_exists(args.tables_dir / name) for name in ["T1_dataset_statistics.csv", "T2_label_mapping.csv", "T3_protocol_matrix.csv"]),
    }
    warnings = {
        "vifactcheck_official_split_claim_overlap": [
            row for row in overlap_rows if row["dataset"] == "vifactcheck" and int(row["overlap_count"]) > 0
        ],
        "averitec_hidden_prediction_only_overlap": [
            row
            for row in overlap_rows
            if row["dataset"] == "averitec" and "hidden_test" in {row["split_a"], row["split_b"]} and int(row["overlap_count"]) > 0
        ],
        "healthver_official_split_claim_overlap": [
            row
            for row in overlap_rows
            if row["dataset"] == "healthver" and row["overlap_type"] == "claim_norm_hash" and int(row["overlap_count"]) > 0
        ],
        "healthver_official_split_evidence_text_overlap": [
            row
            for row in overlap_rows
            if row["dataset"] == "healthver" and row["overlap_type"] == "evidence_text_hash" and int(row["overlap_count"]) > 0
        ],
    }
    leakage_report = {
        "stage": "Stage 0-1-2 protocol lock",
        "checks": leakage_checks,
        "pass": all(leakage_checks.values()),
        "warnings": warnings,
        "notes": {
            "averitec_hidden_test": "Hidden-style local file is prediction-only; no metric is computed without official labels.",
            "vifactcheck_evidence": "Gold Evidence is diagnostic/upper-bound only, not main input.",
            "healthver_unit": "Main unit is pair-level; grouped claims are analysis/robustness files.",
            "healthver_overlap": "The official HealthVer split has substantial repeated evidence text across splits; report this risk and consider evidence-disjoint robustness.",
        },
    }
    write_json(args.stats_dir / "leakage_report.json", leakage_report)
    print(f"Wrote validation tables and leakage report. PASS={leakage_report['pass']}")


if __name__ == "__main__":
    main()