| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import random |
| from collections import Counter, defaultdict |
| from pathlib import Path |
| from typing import Any |
|
|
| from src.data.io_utils import write_csv, write_json, write_jsonl |
| from src.data.normalize_text import canonical_label, normalize_whitespace, stable_hash, stable_hash_raw, word_count |
|
|
|
|
| def load_json(path: Path) -> list[dict[str, Any]]: |
| with path.open(encoding="utf-8") as handle: |
| data = json.load(handle) |
| if not isinstance(data, list): |
| raise ValueError(f"Expected list in {path}") |
| return data |
|
|
|
|
| def row_to_claim(row: dict[str, Any], split: str, idx: int, label: str | None) -> dict[str, Any]: |
| claim = normalize_whitespace(row.get("claim")) |
| claim_id = f"averitec_{split}_{idx:06d}" |
| return { |
| "claim_id": claim_id, |
| "claim": claim, |
| "label": label, |
| "dataset": "averitec", |
| "language": "en", |
| "split": split, |
| "context": "", |
| "gold_evidence": [], |
| "metadata": { |
| "claim_norm_hash": stable_hash(claim), |
| "claim_date": normalize_whitespace(row.get("claim_date")), |
| "speaker": normalize_whitespace(row.get("speaker")), |
| "original_claim_url": normalize_whitespace(row.get("original_claim_url")), |
| "fact_checking_article": normalize_whitespace(row.get("fact_checking_article")), |
| "reporting_source": normalize_whitespace(row.get("reporting_source")), |
| "location_ISO_code": normalize_whitespace(row.get("location_ISO_code")), |
| "claim_types": row.get("claim_types", []), |
| "fact_checking_strategies": row.get("fact_checking_strategies", []), |
| "required_reannotation": row.get("required_reannotation"), |
| "source_split": row.get("_source_split", split), |
| "source_index": row.get("_source_index", idx), |
| }, |
| } |
|
|
|
|
| def emit_qa_rows(claim: dict[str, Any], raw_row: dict[str, Any]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: |
| qa_rows: list[dict[str, Any]] = [] |
| evidence_rows: list[dict[str, Any]] = [] |
| questions = raw_row.get("questions", []) or [] |
| if not isinstance(questions, list): |
| return qa_rows, evidence_rows |
| for q_idx, question_row in enumerate(questions): |
| if not isinstance(question_row, dict): |
| continue |
| question = normalize_whitespace(question_row.get("question")) |
| answers = question_row.get("answers", []) or [] |
| if not isinstance(answers, list): |
| continue |
| for a_idx, answer_row in enumerate(answers): |
| if not isinstance(answer_row, dict): |
| continue |
| answer = normalize_whitespace(answer_row.get("answer")) |
| boolean_explanation = normalize_whitespace(answer_row.get("boolean_explanation")) |
| evidence_text = boolean_explanation if boolean_explanation else answer |
| source_url = normalize_whitespace(answer_row.get("source_url")) |
| evidence_id = f"averitec_ev_{stable_hash_raw(source_url, evidence_text, length=20)}" |
| qa_rows.append( |
| { |
| "claim_id": claim["claim_id"], |
| "question_id": f"{claim['claim_id']}_q{q_idx:03d}", |
| "answer_id": f"{claim['claim_id']}_q{q_idx:03d}_a{a_idx:03d}", |
| "question": question, |
| "answer": answer, |
| "evidence_text": evidence_text, |
| "source_url": source_url, |
| "dataset": "averitec", |
| "split": claim["split"], |
| "metadata": { |
| "answer_type": normalize_whitespace(answer_row.get("answer_type")), |
| "source_medium": normalize_whitespace(answer_row.get("source_medium")), |
| "cached_source_url": normalize_whitespace(answer_row.get("cached_source_url")), |
| "evidence_id": evidence_id, |
| }, |
| } |
| ) |
| evidence_rows.append( |
| { |
| "doc_id": evidence_id, |
| "text": evidence_text, |
| "dataset": "averitec", |
| "language": "en", |
| "split": claim["split"], |
| "source_type": "qa_answer", |
| "metadata": { |
| "claim_id": claim["claim_id"], |
| "question_id": f"{claim['claim_id']}_q{q_idx:03d}", |
| "source_url": source_url, |
| "answer": answer, |
| "answer_type": normalize_whitespace(answer_row.get("answer_type")), |
| "source_medium": normalize_whitespace(answer_row.get("source_medium")), |
| "cached_source_url": normalize_whitespace(answer_row.get("cached_source_url")), |
| }, |
| } |
| ) |
| return qa_rows, evidence_rows |
|
|
|
|
| def group_split_train(rows: list[dict[str, Any]], dev_hashes: set[str], seed: int) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]: |
| kept: list[dict[str, Any]] = [] |
| removed: list[dict[str, Any]] = [] |
| for idx, row in enumerate(rows): |
| row["_source_split"] = "official_train" |
| row["_source_index"] = idx |
| claim_hash = stable_hash(row.get("claim")) |
| if claim_hash in dev_hashes: |
| removed.append(row) |
| else: |
| kept.append(row) |
| groups: dict[str, list[dict[str, Any]]] = defaultdict(list) |
| for row in kept: |
| groups[stable_hash(row.get("claim"))].append(row) |
| group_keys = sorted(groups) |
| random.Random(seed).shuffle(group_keys) |
| dev_group_count = max(1, round(len(group_keys) * 0.10)) |
| dev_keys = set(group_keys[:dev_group_count]) |
| train_inner: list[dict[str, Any]] = [] |
| dev_inner: list[dict[str, Any]] = [] |
| for key, group_rows in groups.items(): |
| if key in dev_keys: |
| dev_inner.extend(group_rows) |
| else: |
| train_inner.extend(group_rows) |
| return train_inner, dev_inner, removed |
|
|
|
|
| def convert_rows(rows: list[dict[str, Any]], split: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]], Counter]: |
| claims: list[dict[str, Any]] = [] |
| qa_rows: list[dict[str, Any]] = [] |
| evidence_rows: list[dict[str, Any]] = [] |
| label_counts: Counter = Counter() |
| for idx, row in enumerate(rows): |
| raw_label = row.get("label") |
| label = canonical_label("averitec", raw_label) if raw_label is not None else None |
| label_counts[label if label is not None else "UNLABELED"] += 1 |
| claim = row_to_claim(row, split=split, idx=idx, label=label) |
| claims.append(claim) |
| qa, evidence = emit_qa_rows(claim, row) |
| qa_rows.extend(qa) |
| evidence_rows.extend(evidence) |
| return claims, qa_rows, evidence_rows, label_counts |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--input-dir", type=Path, default=Path("datasets/AveriTeC")) |
| parser.add_argument("--output-dir", type=Path, default=Path("data_processed/averitec")) |
| parser.add_argument("--stats-dir", type=Path, default=Path("outputs/stats")) |
| parser.add_argument("--seed", type=int, default=13) |
| args = parser.parse_args() |
|
|
| args.output_dir.mkdir(parents=True, exist_ok=True) |
| official_train = load_json(args.input_dir / "train.json") |
| official_dev = load_json(args.input_dir / "dev.json") |
| official_test = load_json(args.input_dir / "test.json") |
| for idx, row in enumerate(official_dev): |
| row["_source_split"] = "official_dev" |
| row["_source_index"] = idx |
| for idx, row in enumerate(official_test): |
| row["_source_split"] = "official_test" |
| row["_source_index"] = idx |
|
|
| official_dev_hashes = {stable_hash(row.get("claim")) for row in official_dev} |
| train_inner_raw, dev_inner_raw, removed_overlap = group_split_train(official_train, official_dev_hashes, seed=args.seed) |
|
|
| split_rows = { |
| "train_inner": train_inner_raw, |
| "dev_inner": dev_inner_raw, |
| "local_test": official_dev, |
| "hidden_test": official_test, |
| } |
| all_qa: list[dict[str, Any]] = [] |
| all_evidence: list[dict[str, Any]] = [] |
| split_reports: dict[str, Any] = {} |
| processed_claims: dict[str, list[dict[str, Any]]] = {} |
| for split, rows in split_rows.items(): |
| claims, qa_rows, evidence_rows, label_counts = convert_rows(rows, split) |
| processed_claims[split] = claims |
| write_jsonl(args.output_dir / f"claims_{split}.jsonl", claims) |
| all_qa.extend(qa_rows) |
| all_evidence.extend(evidence_rows) |
| split_reports[split] = { |
| "rows": len(rows), |
| "unique_claim_hashes": len({stable_hash(row.get("claim")) for row in rows}), |
| "labels": dict(label_counts), |
| "qa_rows": len(qa_rows), |
| "evidence_rows": len(evidence_rows), |
| } |
|
|
| seen_evidence: set[str] = set() |
| deduped_evidence: list[dict[str, Any]] = [] |
| for row in all_evidence: |
| key = row["doc_id"] |
| if key in seen_evidence: |
| continue |
| seen_evidence.add(key) |
| deduped_evidence.append(row) |
| write_jsonl(args.output_dir / "qa_evidence.jsonl", all_qa) |
| write_jsonl(args.output_dir / "evidence_store.jsonl", deduped_evidence) |
|
|
| overlap_rows: list[dict[str, Any]] = [] |
| split_names = list(processed_claims) |
| for i, split_a in enumerate(split_names): |
| for split_b in split_names[i + 1 :]: |
| hashes_a = defaultdict(list) |
| hashes_b = defaultdict(list) |
| for claim in processed_claims[split_a]: |
| hashes_a[claim["metadata"]["claim_norm_hash"]].append(claim["claim_id"]) |
| for claim in processed_claims[split_b]: |
| hashes_b[claim["metadata"]["claim_norm_hash"]].append(claim["claim_id"]) |
| overlap = sorted(set(hashes_a) & set(hashes_b)) |
| overlap_rows.append( |
| { |
| "dataset": "averitec", |
| "split_a": split_a, |
| "split_b": split_b, |
| "claim_norm_hash_overlap_count": len(overlap), |
| "hash_examples": " | ".join(overlap[:5]), |
| } |
| ) |
| write_csv(args.stats_dir / "averitec_claim_overlap.csv", overlap_rows) |
|
|
| official_counts = { |
| "official_train_rows": len(official_train), |
| "official_dev_rows": len(official_dev), |
| "official_test_rows": len(official_test), |
| "removed_train_rows_overlapping_official_dev": len(removed_overlap), |
| "removed_train_unique_hashes_overlapping_official_dev": len({stable_hash(row.get("claim")) for row in removed_overlap}), |
| "hidden_test_has_labels": any("label" in row for row in official_test), |
| "hidden_test_has_questions": any("questions" in row for row in official_test), |
| } |
| split_report = { |
| "seed": args.seed, |
| "official": official_counts, |
| "processed": split_reports, |
| "overlap_rows": overlap_rows, |
| } |
| write_json(args.stats_dir / "averitec_split_report.json", split_report) |
| print("Built AVeriTeC processed files") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|