from __future__ import annotations import argparse from collections import Counter, defaultdict from pathlib import Path import pyarrow.parquet as pq from src.data.io_utils import write_csv, write_json, write_jsonl from src.data.normalize_text import ( canonical_label, make_sentence_chunks, normalize_for_hash, normalize_whitespace, split_sentences, stable_hash, word_count, ) def token_jaccard(a: str, b: str) -> float: a_tokens = set(normalize_for_hash(a).split()) b_tokens = set(normalize_for_hash(b).split()) if not a_tokens or not b_tokens: return 0.0 return len(a_tokens & b_tokens) / len(a_tokens | b_tokens) def match_evidence_sentence(evidence: str, sentences: list[str]) -> tuple[int | None, float]: evidence_norm = normalize_for_hash(evidence) if not evidence_norm or not sentences: return None, 0.0 best_idx: int | None = None best_score = 0.0 for idx, sentence in enumerate(sentences): sentence_norm = normalize_for_hash(sentence) if evidence_norm and evidence_norm in sentence_norm: return idx, 1.0 score = token_jaccard(evidence, sentence) if score > best_score: best_score = score best_idx = idx return best_idx, best_score def build_split(split: str, input_path: Path) -> tuple[list[dict], list[dict], list[dict], list[dict], dict]: table = pq.read_table(input_path) raw_rows = table.to_pylist() claims: list[dict] = [] sentences_out: list[dict] = [] chunks_out: list[dict] = [] evidence_out: list[dict] = [] label_counts = Counter() missing = Counter() evidence_match_scores: list[float] = [] for idx, row in enumerate(raw_rows): claim_id = f"vifactcheck_{split}_{idx:06d}" doc_id = f"{claim_id}_context" claim = normalize_whitespace(row.get("Statement")) context = normalize_whitespace(row.get("Context")) evidence = normalize_whitespace(row.get("Evidence")) label = canonical_label("vifactcheck", row.get("labels")) if label is None: missing["unknown_label"] += 1 label_counts[label or "UNKNOWN"] += 1 context_sentences = split_sentences(context) matched_sent_id, match_score = match_evidence_sentence(evidence, context_sentences) evidence_match_scores.append(match_score) metadata = { "url": normalize_whitespace(row.get("Url")), "topic": normalize_whitespace(row.get("Topic")), "source": normalize_whitespace(row.get("Author")), "raw_index": row.get("index"), "annotation_id": row.get("annotation_id"), "claim_norm_hash": stable_hash(claim), } gold_evidence = [ { "doc_id": doc_id, "sent_id": matched_sent_id, "text": evidence, "match_score": round(match_score, 6), } ] claims.append( { "claim_id": claim_id, "claim": claim, "label": label, "dataset": "vifactcheck", "language": "vi", "split": split, "context": context, "gold_evidence": gold_evidence, "metadata": metadata, } ) evidence_out.append( { "evidence_id": f"{claim_id}_gold_000", "claim_id": claim_id, "doc_id": doc_id, "sent_id": matched_sent_id, "text": evidence, "dataset": "vifactcheck", "language": "vi", "split": split, "source_type": "gold_evidence", "metadata": { "url": metadata["url"], "topic": metadata["topic"], "source": metadata["source"], "match_score": round(match_score, 6), }, } ) for sent_id, sentence in enumerate(context_sentences): sentences_out.append( { "doc_id": doc_id, "sent_id": sent_id, "chunk_id": None, "text": sentence, "dataset": "vifactcheck", "language": "vi", "split": split, "source_type": "context", "metadata": { "claim_id": claim_id, "url": metadata["url"], "topic": metadata["topic"], "source": metadata["source"], }, } ) for chunk_idx, chunk in enumerate(make_sentence_chunks(context_sentences, max_words=180, overlap_sentences=1)): chunks_out.append( { "doc_id": doc_id, "sent_id": chunk["start_sent_id"], "chunk_id": f"{claim_id}_chunk_{chunk_idx:03d}", "text": chunk["text"], "dataset": "vifactcheck", "language": "vi", "split": split, "source_type": "context", "metadata": { "claim_id": claim_id, "url": metadata["url"], "topic": metadata["topic"], "source": metadata["source"], "start_sent_id": chunk["start_sent_id"], "end_sent_id": chunk["end_sent_id"], }, } ) report = { "split": split, "raw_rows": len(raw_rows), "claims": len(claims), "context_sentences": len(sentences_out), "context_chunks": len(chunks_out), "label_counts": dict(label_counts), "missing": dict(missing), "avg_context_words": sum(word_count(row.get("Context")) for row in raw_rows) / max(1, len(raw_rows)), "avg_evidence_match_score": sum(evidence_match_scores) / max(1, len(evidence_match_scores)), } return claims, sentences_out, chunks_out, evidence_out, report def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--input-dir", type=Path, default=Path("datasets/ViFactCheck")) parser.add_argument("--output-dir", type=Path, default=Path("data_processed/vifactcheck")) parser.add_argument("--stats-dir", type=Path, default=Path("outputs/stats")) args = parser.parse_args() args.output_dir.mkdir(parents=True, exist_ok=True) all_sentences: list[dict] = [] all_chunks: list[dict] = [] all_evidence: list[dict] = [] reports: list[dict] = [] claims_by_split: dict[str, list[dict]] = {} for split in ["train", "dev", "test"]: claims, sentences, chunks, evidence, report = build_split(split, args.input_dir / f"{split}-00000-of-00001.parquet") claims_by_split[split] = claims write_jsonl(args.output_dir / f"claims_{split}.jsonl", claims) all_sentences.extend(sentences) all_chunks.extend(chunks) all_evidence.extend(evidence) reports.append(report) write_jsonl(args.output_dir / "context_sentences.jsonl", all_sentences) write_jsonl(args.output_dir / "context_chunks.jsonl", all_chunks) write_jsonl(args.output_dir / "gold_evidence.jsonl", all_evidence) write_json(args.stats_dir / "vifactcheck_build_report.json", {"splits": reports}) overlap_rows: list[dict] = [] split_names = ["train", "dev", "test"] for i, split_a in enumerate(split_names): for split_b in split_names[i + 1 :]: urls_a = defaultdict(list) urls_b = defaultdict(list) claims_a = defaultdict(list) claims_b = defaultdict(list) for claim in claims_by_split[split_a]: urls_a[claim["metadata"]["url"]].append(claim["claim_id"]) claims_a[claim["metadata"]["claim_norm_hash"]].append(claim["claim_id"]) for claim in claims_by_split[split_b]: urls_b[claim["metadata"]["url"]].append(claim["claim_id"]) claims_b[claim["metadata"]["claim_norm_hash"]].append(claim["claim_id"]) url_overlap = sorted(set(urls_a) & set(urls_b)) claim_overlap = sorted(set(claims_a) & set(claims_b)) overlap_rows.append( { "dataset": "vifactcheck", "split_a": split_a, "split_b": split_b, "url_overlap_count": len(url_overlap), "claim_norm_hash_overlap_count": len(claim_overlap), "url_examples": " | ".join(url_overlap[:3]), "claim_hash_examples": " | ".join(claim_overlap[:3]), } ) write_csv(args.stats_dir / "vifactcheck_url_overlap.csv", overlap_rows) token_rows: list[dict] = [] for split, claims in claims_by_split.items(): for field in ["claim", "context"]: lengths = sorted(word_count(claim.get(field)) for claim in claims) token_rows.append( { "dataset": "vifactcheck", "split": split, "field": field, "count": len(lengths), "mean_words": round(sum(lengths) / max(1, len(lengths)), 3), "p95_words": lengths[int(0.95 * (len(lengths) - 1))] if lengths else 0, "max_words": max(lengths) if lengths else 0, } ) evidence_lengths = sorted(word_count(row["text"]) for row in all_evidence) token_rows.append( { "dataset": "vifactcheck", "split": "all", "field": "gold_evidence", "count": len(evidence_lengths), "mean_words": round(sum(evidence_lengths) / max(1, len(evidence_lengths)), 3), "p95_words": evidence_lengths[int(0.95 * (len(evidence_lengths) - 1))] if evidence_lengths else 0, "max_words": max(evidence_lengths) if evidence_lengths else 0, } ) write_csv(args.stats_dir / "vifactcheck_token_length.csv", token_rows) print("Built ViFactCheck processed files") if __name__ == "__main__": main()