File size: 10,467 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
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()