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()