File size: 4,606 Bytes
3bee27f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate the local general science release before upload."""

from __future__ import annotations

import json
import re
import sys
from collections import Counter
from pathlib import Path
from typing import Any


RELEASE_DIR = Path(__file__).resolve().parents[1]
TRAIN_PATH = RELEASE_DIR / "train.jsonl"
TEST_PATH = RELEASE_DIR / "test.jsonl"


def normalize_for_key(value: Any) -> str:
    text = "" if value is None else str(value).strip().lower()
    text = re.sub(r"\s+", " ", text)
    text = re.sub(r"[^\w\s]+", "", text)
    return text.strip()


def dedup_key(example: dict[str, Any]) -> str:
    choices = sorted(normalize_for_key(choice["text"]) for choice in example["choices"])
    return " || ".join([normalize_for_key(example["question"]), *choices, normalize_for_key(example["answer_text"])])


def load_jsonl(path: Path) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    with path.open(encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, 1):
            try:
                rows.append(json.loads(line))
            except json.JSONDecodeError as exc:
                raise ValueError(f"{path}:{line_number} invalid JSON: {exc}") from exc
    return rows


def validate_example(example: dict[str, Any], expected_split: str) -> None:
    required = {
        "id",
        "dataset",
        "subset",
        "split",
        "task_type",
        "modality",
        "question",
        "image",
        "choices",
        "answer_label",
        "answer_text",
        "support",
        "source_meta",
    }
    missing = required - set(example)
    if missing:
        raise ValueError(f"{example.get('id')} missing required fields: {sorted(missing)}")
    if example["split"] != expected_split:
        raise ValueError(f"{example['id']} split={example['split']} expected {expected_split}")
    if example["task_type"] != "multiple_choice_science_qa":
        raise ValueError(f"{example['id']} unexpected task_type")
    if not isinstance(example["choices"], list) or len(example["choices"]) < 4:
        raise ValueError(f"{example['id']} has fewer than four choices")
    labels = [choice.get("label") for choice in example["choices"]]
    if labels != [chr(ord("A") + idx) for idx in range(len(labels))]:
        raise ValueError(f"{example['id']} labels are not contiguous from A")
    if example["answer_label"] not in set(labels):
        raise ValueError(f"{example['id']} answer label not in choices")
    if example["modality"] == "image_text":
        image = example.get("image")
        if not image or not image.get("path"):
            raise ValueError(f"{example['id']} image_text example has no image path")
        image_path = RELEASE_DIR / image["path"]
        if not image_path.exists():
            raise ValueError(f"{example['id']} image path missing: {image_path}")
    elif example["modality"] == "text":
        if example.get("image") is not None:
            raise ValueError(f"{example['id']} text example should have image=null")
    else:
        raise ValueError(f"{example['id']} unexpected modality {example['modality']}")


def main() -> int:
    train = load_jsonl(TRAIN_PATH)
    test = load_jsonl(TEST_PATH)
    ids = [example["id"] for example in train + test]
    duplicated_ids = [item for item, count in Counter(ids).items() if count > 1]
    if duplicated_ids:
        raise ValueError(f"Duplicated ids: {duplicated_ids[:10]}")

    for example in train:
        validate_example(example, "train")
    for example in test:
        validate_example(example, "test")

    train_keys = {dedup_key(example) for example in train}
    test_keys = {dedup_key(example) for example in test}
    overlap = train_keys & test_keys
    if overlap:
        raise ValueError(f"Train/test normalized overlap found: {len(overlap)}")

    all_examples = train + test
    dataset_counts = Counter((example["dataset"], example["subset"]) for example in all_examples)
    modality_counts = Counter(example["modality"] for example in all_examples)
    image_count = sum(1 for example in all_examples if example.get("image"))

    print(f"train={len(train)}")
    print(f"test={len(test)}")
    print(f"total={len(all_examples)}")
    print(f"datasets={dict(dataset_counts)}")
    print(f"modalities={dict(modality_counts)}")
    print(f"image_examples={image_count}")
    print("validation=ok")
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as exc:
        print(f"Error: {exc}", file=sys.stderr)
        raise SystemExit(1) from exc