File size: 8,979 Bytes
926367a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
268
269
#!/usr/bin/env python3
import argparse
import json
from pathlib import Path
from typing import Dict, List, Optional, Tuple


USER_INSTRUCTION = (
    "Determine whether the claim is SUPPORTS, CONTRADICTS, or NOT ENOUGH INFORMATION "
    "based only on the provided abstract. Use sentence indices as rationale evidence."
)

LABEL_MAP = {
    "SUPPORT": "SUPPORTS",
    "CONTRADICT": "CONTRADICTS",
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Prepare SciFact Unsloth chat-format train/validation datasets."
    )
    parser.add_argument(
        "--corpus-jsonl",
        type=Path,
        default=Path("/d/hpc/projects/FRI/DL/Scholar/raw_downloads/scifact/data/corpus.jsonl"),
    )
    parser.add_argument(
        "--claims-train-jsonl",
        type=Path,
        default=Path("/d/hpc/projects/FRI/DL/Scholar/raw_downloads/scifact/data/claims_train.jsonl"),
    )
    parser.add_argument(
        "--claims-dev-jsonl",
        type=Path,
        default=Path("/d/hpc/projects/FRI/DL/Scholar/raw_downloads/scifact/data/claims_dev.jsonl"),
    )
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=Path("/d/hpc/projects/FRI/DL/Scholar/prepared_datasets/scifact_unsloth"),
    )
    return parser.parse_args()


def read_jsonl(path: Path) -> List[Dict]:
    rows: List[Dict] = []
    with path.open("r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            rows.append(json.loads(line))
    return rows


def build_corpus_lookup(corpus_rows: List[Dict]) -> Dict[int, Dict]:
    lookup: Dict[int, Dict] = {}
    for row in corpus_rows:
        lookup[int(row["doc_id"])] = row
    return lookup


def format_abstract_with_indices(sentences: List[str]) -> str:
    lines = []
    for i, sent in enumerate(sentences):
        sent = (sent or "").strip()
        lines.append(f"[{i}] {sent}")
    return "\n".join(lines)


def get_rationale_texts(sentences: List[str], idxs: List[int]) -> List[str]:
    out = []
    for i in idxs:
        if isinstance(i, int) and 0 <= i < len(sentences):
            txt = (sentences[i] or "").strip()
            if txt:
                out.append(txt)
    return out


def build_user_text(claim: str, title: str, abstract_indexed: str) -> str:
    return (
        f"{USER_INSTRUCTION}\n\n"
        f"Claim: {claim}\n\n"
        f"Document title: {title}\n\n"
        f"Abstract sentences:\n{abstract_indexed}"
    )


def build_assistant_text(label: str, rationale_ids: List[int], rationale_texts: List[str]) -> str:
    if label == "NOT ENOUGH INFORMATION":
        return (
            "Label: NOT ENOUGH INFORMATION\n"
            "Rationale sentence ids: []\n"
            "Explanation: The provided abstract does not contain direct evidence to support or contradict the claim."
        )
    evidence_text = " ".join(rationale_texts).strip()
    verb = "supports" if label == "SUPPORTS" else "contradicts"
    return (
        f"Label: {label}\n"
        f"Rationale sentence ids: {rationale_ids}\n"
        f"Explanation: Evidence states: \"{evidence_text}\". This {verb} the claim."
    )


def row_from_evidence(
    split: str,
    claim_row: Dict,
    doc_id: int,
    evidence_entry: Dict,
    corpus_lookup: Dict[int, Dict],
    variant: str,
) -> Optional[Dict]:
    doc = corpus_lookup.get(doc_id)
    if doc is None:
        return None
    title = doc.get("title", "")
    abstract = doc.get("abstract", []) or []
    rationale_ids = evidence_entry.get("sentences", []) or []
    label_raw = evidence_entry.get("label", "")
    label = LABEL_MAP.get(label_raw, label_raw)
    if label not in {"SUPPORTS", "CONTRADICTS"}:
        return None

    abstract_indexed = format_abstract_with_indices(abstract)
    rationale_texts = get_rationale_texts(abstract, rationale_ids)
    user_text = build_user_text(claim=claim_row["claim"], title=title, abstract_indexed=abstract_indexed)
    assistant_text = build_assistant_text(label=label, rationale_ids=rationale_ids, rationale_texts=rationale_texts)

    return {
        "messages": [
            {"role": "user", "content": [{"type": "text", "text": user_text}]},
            {"role": "assistant", "content": [{"type": "text", "text": assistant_text}]},
        ],
        "meta": {
            "dataset": "scifact",
            "split": split,
            "claim_id": claim_row["id"],
            "doc_id": doc_id,
            "label": label,
            "evidence_sentence_ids": rationale_ids,
            "cited_doc_ids": claim_row.get("cited_doc_ids", []),
            "variant": variant,
        },
    }


def row_for_nei(split: str, claim_row: Dict, corpus_lookup: Dict[int, Dict]) -> Dict:
    cited_doc_ids = claim_row.get("cited_doc_ids", []) or []
    doc_id = cited_doc_ids[0] if cited_doc_ids else None
    doc = corpus_lookup.get(int(doc_id)) if doc_id is not None else None
    if doc is not None:
        title = doc.get("title", "")
        abstract = doc.get("abstract", []) or []
        abstract_indexed = format_abstract_with_indices(abstract)
        user_text = build_user_text(claim=claim_row["claim"], title=title, abstract_indexed=abstract_indexed)
        variant = "nei_with_cited_abstract"
    else:
        user_text = (
            f"{USER_INSTRUCTION}\n\n"
            f"Claim: {claim_row['claim']}\n\n"
            "No cited abstract is available in the corpus for this claim."
        )
        variant = "nei_no_corpus_doc"

    assistant_text = build_assistant_text(
        label="NOT ENOUGH INFORMATION",
        rationale_ids=[],
        rationale_texts=[],
    )
    return {
        "messages": [
            {"role": "user", "content": [{"type": "text", "text": user_text}]},
            {"role": "assistant", "content": [{"type": "text", "text": assistant_text}]},
        ],
        "meta": {
            "dataset": "scifact",
            "split": split,
            "claim_id": claim_row["id"],
            "doc_id": doc_id if doc_id is not None else "",
            "label": "NOT ENOUGH INFORMATION",
            "evidence_sentence_ids": [],
            "cited_doc_ids": cited_doc_ids,
            "variant": variant,
        },
    }


def build_rows(split: str, claim_rows: List[Dict], corpus_lookup: Dict[int, Dict]) -> List[Dict]:
    rows: List[Dict] = []
    for claim_row in claim_rows:
        evidence = claim_row.get("evidence", {}) or {}
        if not evidence:
            rows.append(row_for_nei(split, claim_row, corpus_lookup))
            continue

        emitted = 0
        for doc_id_str, rationale_list in evidence.items():
            doc_id = int(doc_id_str)
            for ev in rationale_list:
                row = row_from_evidence(
                    split=split,
                    claim_row=claim_row,
                    doc_id=doc_id,
                    evidence_entry=ev,
                    corpus_lookup=corpus_lookup,
                    variant="evidence_rationale",
                )
                if row is not None:
                    rows.append(row)
                    emitted += 1
        if emitted == 0:
            rows.append(row_for_nei(split, claim_row, corpus_lookup))
    return rows


def write_jsonl(path: Path, rows: List[Dict]) -> None:
    with path.open("w", encoding="utf-8") as f:
        for r in rows:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")


def counts_by_label(rows: List[Dict]) -> Dict[str, int]:
    labels = ["SUPPORTS", "CONTRADICTS", "NOT ENOUGH INFORMATION"]
    return {label: sum(1 for r in rows if r["meta"]["label"] == label) for label in labels}


def main() -> None:
    args = parse_args()
    args.output_dir.mkdir(parents=True, exist_ok=True)

    corpus_rows = read_jsonl(args.corpus_jsonl)
    train_claims = read_jsonl(args.claims_train_jsonl)
    dev_claims = read_jsonl(args.claims_dev_jsonl)
    corpus_lookup = build_corpus_lookup(corpus_rows)

    train_rows = build_rows("train", train_claims, corpus_lookup)
    dev_rows = build_rows("validation", dev_claims, corpus_lookup)

    train_out = args.output_dir / "train.jsonl"
    val_out = args.output_dir / "validation.jsonl"
    stats_out = args.output_dir / "stats.json"
    write_jsonl(train_out, train_rows)
    write_jsonl(val_out, dev_rows)

    stats = {
        "train": {
            "rows": len(train_rows),
            "label_counts": counts_by_label(train_rows),
        },
        "validation": {
            "rows": len(dev_rows),
            "label_counts": counts_by_label(dev_rows),
        },
        "paths": {
            "train_jsonl": str(train_out),
            "validation_jsonl": str(val_out),
            "stats_json": str(stats_out),
        },
    }
    with stats_out.open("w", encoding="utf-8") as f:
        json.dump(stats, f, ensure_ascii=False, indent=2)
    print(json.dumps(stats, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()