GeneralScience-MLLM-22K / scripts /validate_general_science_release.py
gineven's picture
Upload 355 files
3bee27f verified
Raw
History Blame Contribute Delete
4.61 kB
#!/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