math-annotation / tools /fetch_mathvision_images.py
Shoir's picture
Deploy math annotation app
efc6467 verified
Raw History Blame Contribute Delete
5.32 kB
#!/usr/bin/env python3
"""Fetch the MathVision images (and reference answers) used by the math study.
The math datasets only store MathVision `instance_id`s. This script downloads the
MathVision test split from Hugging Face (MathLLMs/MathVision), extracts the
images for every instance id referenced by the MathVision JSON files, and
writes them to `my-annotation-task/images/mathvision/<instance_id>.<ext>` so the
Space can serve them. It also writes a small metadata file with the original
question, answer, and solution, which the data-preparation script uses as the
reference solution for MathVision pilot dialogues (they have no
`Ground_Truth_Solution`).
Run it from the app root (the folder containing `my-annotation-task/`):
python tools/fetch_mathvision_images.py
"""
from __future__ import annotations
import argparse
import json
import urllib.request
from pathlib import Path
PARQUET_URL = (
"https://huggingface.co/datasets/MathLLMs/MathVision/resolve/main/"
"data/test-00000-of-00001-3532b8d3f1b4047a.parquet"
)
IMAGE_SUFFIXES = {
b"\x89PNG": ".png",
b"\xff\xd8\xff": ".jpg",
b"GIF8": ".gif",
}
def resolve_app_root(start: Path) -> Path:
for candidate in [start, *start.parents]:
if (candidate / "my-annotation-task").exists():
return candidate
raise FileNotFoundError("Could not find app root containing my-annotation-task/.")
def default_dataset_paths(app_root: Path) -> list[Path]:
math_mr = app_root.parents[1]
return [
math_mr / "MathVision" / "MathVision_pilot.json",
math_mr / "MathVision" / "MathVision_verified_100.json",
]
def image_suffix(data: bytes, fallback_path: str) -> str:
for magic, suffix in IMAGE_SUFFIXES.items():
if data.startswith(magic):
return suffix
return Path(fallback_path).suffix or ".png"
def clean_text(value) -> str:
if value is None:
return ""
text = str(value).strip()
return "" if text.lower() == "nan" else text
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--app-root", type=Path, default=None)
parser.add_argument("--parquet", type=Path, default=None, help="Use an already downloaded MathVision test parquet.")
parser.add_argument("--cache-dir", type=Path, default=None, help="Where to download the parquet (default: <app>/.cache).")
parser.add_argument("--dataset", type=Path, action="append", default=None, help="MathVision JSON file(s) with instance_id fields.")
parser.add_argument("--image-dir", type=Path, default=None)
parser.add_argument("--metadata-output", type=Path, default=None)
return parser.parse_args()
def main() -> None:
import pyarrow.parquet as pq
args = parse_args()
app_root = args.app_root or resolve_app_root(Path.cwd())
dataset_paths = args.dataset or default_dataset_paths(app_root)
image_dir = args.image_dir or app_root / "my-annotation-task" / "images" / "mathvision"
metadata_output = args.metadata_output or app_root / "tools" / "mathvision_metadata.json"
parquet_path = args.parquet
if parquet_path is None:
cache_dir = args.cache_dir or app_root / ".cache"
cache_dir.mkdir(parents=True, exist_ok=True)
parquet_path = cache_dir / "mathvision_test.parquet"
if not parquet_path.exists():
print(f"Downloading {PARQUET_URL}")
urllib.request.urlretrieve(PARQUET_URL, parquet_path)
needed_ids: set[str] = set()
for path in dataset_paths:
for dialog in json.loads(Path(path).read_text(encoding="utf-8")):
instance_id = clean_text(dialog.get("instance_id"))
if instance_id:
needed_ids.add(instance_id)
table = pq.read_table(parquet_path, columns=["id", "question", "options", "decoded_image", "answer", "solution"])
image_dir.mkdir(parents=True, exist_ok=True)
metadata: dict[str, dict] = {}
for row in table.to_pylist():
instance_id = clean_text(row["id"])
if instance_id not in needed_ids:
continue
image = row["decoded_image"] or {}
data = image.get("bytes") or b""
if not data:
raise ValueError(f"MathVision instance {instance_id} has no image bytes")
filename = f"{instance_id}{image_suffix(data, image.get('path') or '')}"
(image_dir / filename).write_bytes(data)
metadata[instance_id] = {
"image_file": filename,
"question": clean_text(row["question"]),
"options": [clean_text(option) for option in (row["options"] or [])],
"answer": clean_text(row["answer"]),
"solution": clean_text(row["solution"]),
}
missing = sorted(needed_ids - set(metadata), key=int)
if missing:
raise ValueError(f"MathVision instances not found in the parquet: {missing}")
metadata_output.parent.mkdir(parents=True, exist_ok=True)
metadata_output.write_text(
json.dumps(dict(sorted(metadata.items(), key=lambda item: int(item[0]))), indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
print(f"Wrote {len(metadata)} images to {image_dir}")
print(f"Wrote MathVision metadata to {metadata_output}")
if __name__ == "__main__":
main()