| from __future__ import annotations |
|
|
| import argparse |
| from pathlib import Path |
| from typing import Any |
|
|
| from src.data.io_utils import read_jsonl, write_csv, write_jsonl |
| from src.data.normalize_text import normalize_whitespace |
|
|
|
|
| DATASET_SPECS: dict[str, dict[str, Any]] = { |
| "healthver": { |
| "protocol": "P6_pair_verification", |
| "id_field": "pair_id", |
| "splits": { |
| "train": "data_processed/healthver/pairs_train.jsonl", |
| "dev": "data_processed/healthver/pairs_dev.jsonl", |
| "test": "data_processed/healthver/pairs_test.jsonl", |
| }, |
| "candidate_template": "outputs/retrieval/healthver/candidate_pool_{split}.jsonl", |
| }, |
| "vifactcheck": { |
| "protocol": "P1_full_context_retrieval", |
| "id_field": "claim_id", |
| "splits": { |
| "train": "data_processed/vifactcheck/claims_train.jsonl", |
| "dev": "data_processed/vifactcheck/claims_dev.jsonl", |
| "test": "data_processed/vifactcheck/claims_test.jsonl", |
| }, |
| "candidate_template": "outputs/retrieval/vifactcheck/candidate_pool_{split}.jsonl", |
| }, |
| "averitec": { |
| "protocol": "P4_open_retrieval", |
| "id_field": "claim_id", |
| "qa_evidence": "data_processed/averitec/qa_evidence.jsonl", |
| "splits": { |
| "train_inner": "data_processed/averitec/claims_train_inner.jsonl", |
| "dev_inner": "data_processed/averitec/claims_dev_inner.jsonl", |
| "local_test": "data_processed/averitec/claims_local_test.jsonl", |
| }, |
| "candidate_template": "outputs/retrieval/averitec/candidate_pool_{split}.jsonl", |
| }, |
| } |
|
|
|
|
| def candidate_summary(candidate: dict[str, Any]) -> dict[str, Any]: |
| metadata = candidate.get("metadata") if isinstance(candidate.get("metadata"), dict) else {} |
| return { |
| "candidate_id": candidate.get("candidate_id"), |
| "text": candidate.get("text", ""), |
| "final_rank": candidate.get("final_rank"), |
| "reranker_score": candidate.get("reranker_score"), |
| "is_gold": candidate.get("is_gold"), |
| "source_type": candidate.get("source_type"), |
| "question": candidate.get("question") or metadata.get("question"), |
| "answer": candidate.get("answer") or metadata.get("answer"), |
| } |
|
|
|
|
| def select_evidence(dataset: str, candidates: list[dict[str, Any]], top_k: int) -> list[dict[str, Any]]: |
| selected = candidates[:top_k] |
| if dataset != "healthver": |
| return selected |
|
|
| anchors = [row for row in candidates if row.get("source_type") == "paired_evidence"] |
| if not anchors: |
| return selected |
| anchor = anchors[0] |
| selected_ids = {anchor.get("candidate_id")} |
| augmentations = [row for row in candidates if row.get("candidate_id") not in selected_ids] |
| return [anchor] + augmentations[: max(0, top_k - 1)] |
|
|
|
|
| def format_input_text(dataset: str, claim: str, evidence: list[dict[str, Any]], input_format: str = "flat") -> str: |
| claim = normalize_whitespace(claim) |
| if dataset == "vifactcheck": |
| parts = [f"[STATEMENT] {claim}"] |
| for idx, item in enumerate(evidence, start=1): |
| parts.append(f"[CONTEXT_CHUNK_{idx}] {normalize_whitespace(item.get('text', ''))}") |
| return "\n".join(parts) |
|
|
| if dataset == "healthver": |
| parts = [f"[CLAIM] {claim}"] |
| aug_idx = 1 |
| for item in evidence: |
| text = normalize_whitespace(item.get("text", "")) |
| if item.get("source_type") == "paired_evidence": |
| parts.append(f"[EVIDENCE] {text}") |
| else: |
| parts.append(f"[AUGMENTED_EVIDENCE_{aug_idx}] {text}") |
| aug_idx += 1 |
| return "\n".join(parts) |
|
|
| parts = [f"[CLAIM] {claim}"] |
| if dataset == "averitec" and input_format == "qa": |
| for idx, item in enumerate(evidence, start=1): |
| question = normalize_whitespace(item.get("question", "")) |
| answer = normalize_whitespace(item.get("answer", "")) |
| text = normalize_whitespace(item.get("text", "")) |
| if question: |
| parts.append(f"[QUESTION_{idx}] {question}") |
| if answer: |
| parts.append(f"[ANSWER_{idx}] {answer}") |
| parts.append(f"[EVIDENCE_{idx}] {text}") |
| return "\n".join(parts) |
|
|
| for idx, item in enumerate(evidence, start=1): |
| parts.append(f"[EVIDENCE_{idx}] {normalize_whitespace(item.get('text', ''))}") |
| return "\n".join(parts) |
|
|
|
|
| def load_candidate_rows(path: Path) -> dict[str, dict[str, Any]]: |
| rows: dict[str, dict[str, Any]] = {} |
| for row in read_jsonl(path): |
| rows[row["query_id"]] = row |
| return rows |
|
|
|
|
| def load_averitec_qa_by_evidence(path: Path) -> dict[str, dict[str, Any]]: |
| rows: dict[str, dict[str, Any]] = {} |
| if not path.exists(): |
| return rows |
| for row in read_jsonl(path): |
| metadata = row.get("metadata") if isinstance(row.get("metadata"), dict) else {} |
| evidence_id = metadata.get("evidence_id") |
| if evidence_id: |
| rows[str(evidence_id)] = row |
| return rows |
|
|
|
|
| def enrich_averitec_qa(candidates: list[dict[str, Any]], qa_by_evidence: dict[str, dict[str, Any]]) -> list[dict[str, Any]]: |
| if not qa_by_evidence: |
| return candidates |
| enriched: list[dict[str, Any]] = [] |
| for candidate in candidates: |
| updated = dict(candidate) |
| metadata = dict(updated.get("metadata") if isinstance(updated.get("metadata"), dict) else {}) |
| qa_row = qa_by_evidence.get(str(updated.get("candidate_id"))) |
| if qa_row: |
| updated["question"] = qa_row.get("question") |
| updated["answer"] = qa_row.get("answer") |
| metadata.setdefault("question_id", qa_row.get("question_id")) |
| metadata.setdefault("answer_type", (qa_row.get("metadata") or {}).get("answer_type")) |
| metadata.setdefault("source_url", qa_row.get("source_url")) |
| updated["metadata"] = metadata |
| enriched.append(updated) |
| return enriched |
|
|
|
|
| def build_dataset_split( |
| dataset: str, |
| split: str, |
| source_path: Path, |
| candidate_path: Path, |
| output_path: Path, |
| top_k: int, |
| protocol: str, |
| id_field: str, |
| input_format: str, |
| qa_by_evidence: dict[str, dict[str, Any]] | None = None, |
| ) -> dict[str, Any]: |
| source_rows = read_jsonl(source_path) |
| candidates_by_id = load_candidate_rows(candidate_path) |
| output_rows: list[dict[str, Any]] = [] |
| missing_candidates = 0 |
| missing_labels = 0 |
| anchor_missing = 0 |
|
|
| for row in source_rows: |
| query_id = row.get(id_field) or row.get("claim_id") |
| label = row.get("label") |
| if label is None: |
| missing_labels += 1 |
| continue |
| candidate_row = candidates_by_id.get(query_id) |
| if candidate_row is None: |
| missing_candidates += 1 |
| continue |
|
|
| evidence = select_evidence(dataset, candidate_row.get("candidates", []), top_k=top_k) |
| if dataset == "averitec" and input_format == "qa": |
| evidence = enrich_averitec_qa(evidence, qa_by_evidence or {}) |
| if dataset == "healthver" and not any(item.get("source_type") == "paired_evidence" for item in evidence): |
| anchor_missing += 1 |
| evidence_summaries = [candidate_summary(item) for item in evidence] |
| output_rows.append( |
| { |
| "id": query_id, |
| "dataset": dataset, |
| "split": split, |
| "claim": row.get("claim", ""), |
| "label": label, |
| "input_text": format_input_text(dataset, row.get("claim", ""), evidence, input_format=input_format), |
| "evidence": evidence_summaries, |
| "protocol": protocol, |
| "top_k": top_k, |
| "input_format": input_format, |
| } |
| ) |
|
|
| write_jsonl(output_path, output_rows) |
| return { |
| "dataset": dataset, |
| "split": split, |
| "top_k": top_k, |
| "input_format": input_format, |
| "source_rows": len(source_rows), |
| "output_rows": len(output_rows), |
| "missing_labels": missing_labels, |
| "missing_candidates": missing_candidates, |
| "healthver_anchor_missing": anchor_missing, |
| "output": str(output_path), |
| } |
|
|
|
|
| def build_dataset(dataset: str, top_k: int, output_root: Path, input_format: str) -> list[dict[str, Any]]: |
| spec = DATASET_SPECS[dataset] |
| rows: list[dict[str, Any]] = [] |
| dataset_dir = output_root / dataset |
| qa_by_evidence: dict[str, dict[str, Any]] = {} |
| if dataset == "averitec" and input_format == "qa": |
| qa_by_evidence = load_averitec_qa_by_evidence(Path(spec["qa_evidence"])) |
| for split, source in spec["splits"].items(): |
| source_path = Path(source) |
| candidate_path = Path(spec["candidate_template"].format(split=split)) |
| format_suffix = "_qa" if input_format == "qa" else "" |
| output_path = dataset_dir / f"{split}_top{top_k}{format_suffix}.jsonl" |
| rows.append( |
| build_dataset_split( |
| dataset=dataset, |
| split=split, |
| source_path=source_path, |
| candidate_path=candidate_path, |
| output_path=output_path, |
| top_k=top_k, |
| protocol=spec["protocol"], |
| id_field=spec["id_field"], |
| input_format=input_format, |
| qa_by_evidence=qa_by_evidence, |
| ) |
| ) |
| return rows |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--datasets", nargs="*", choices=sorted(DATASET_SPECS), default=sorted(DATASET_SPECS)) |
| parser.add_argument("--top-k", type=int, action="append", required=True) |
| parser.add_argument("--format", choices=["flat", "qa"], default="flat") |
| parser.add_argument("--output-root", type=Path, default=Path("outputs/verifier_inputs")) |
| parser.add_argument("--summary-output", type=Path, default=Path("outputs/stats/verifier_input_summary.csv")) |
| args = parser.parse_args() |
|
|
| summary_rows: list[dict[str, Any]] = [] |
| for top_k in args.top_k: |
| for dataset in args.datasets: |
| summary_rows.extend( |
| build_dataset(dataset, top_k=top_k, output_root=args.output_root, input_format=args.format) |
| ) |
|
|
| write_csv(args.summary_output, summary_rows) |
| print(f"Wrote {len(summary_rows)} verifier input split summaries to {args.summary_output}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|