# finmme_raw_builder.py from __future__ import annotations from typing import List, Dict, Any, Literal, Optional from pydantic import BaseModel, Field from pathlib import Path from tqdm import tqdm from datasets import load_dataset import json import math # ====== 路径配置 ====== FINMME_IMAGE_ROOT = Path("/workspace/data/finmme/images") FINMME_RAW_JSONL = Path("/workspace/data/finmme_raw.jsonl") class FinMMERawItem(BaseModel): """ FINMME train split 的标准化 raw 结构。 """ id: str image_path: str question: str options: List[str] answer: str question_type: Literal["single_choice", "multi_choice", "calculation", "other"] caption: Optional[str] = None description: Optional[str] = None unit: Optional[str] = None tolerance: Optional[float] = None extra: Dict[str, Any] = Field(default_factory=dict) class FinMMERawItem(BaseModel): id: str image_path: str question: str options: List[str] answer: str question_type: str caption: Optional[str] = None description: Optional[str] = None # 允许三种情况:字符串(如 "percentage")、数值(如 5.0)、None unit: Optional[str] = None tolerance: Optional[float | str] = None extra: Dict[str, Any] = Field(default_factory=dict) def split_options(option_str: str) -> List[str]: """ 把 "A: ...\\nB: ...\\nC: ...\\nD: ..." 拆成 ["A: ...", "B: ...", ...] """ lines = [l.strip() for l in option_str.split("\n") if l.strip()] return lines def question_type_to_enum(qtype: str) -> str: """ 映射 question_type 字段。 """ qtype = (qtype or "").strip().lower() if qtype in {"single_choice", "single"}: return "single_choice" if qtype in {"multi_choice", "multiple_choice", "multi"}: return "multi_choice" if qtype in {"calculation", "numeric", "cal"}: return "calculation" return "other" def build_finmme_raw_from_hf( split: str = "train", image_root: Path = FINMME_IMAGE_ROOT, out_path: Path = FINMME_RAW_JSONL, ) -> None: """ 从 HuggingFace luojunyu/FinMME 读取数据, 保存图片到本地,标准化为 FinMMERawItem,并写为 JSONL。 """ ds = load_dataset("luojunyu/FinMME", split=split) image_root.mkdir(parents=True, exist_ok=True) out_path.parent.mkdir(parents=True, exist_ok=True) with out_path.open("w", encoding="utf-8") as f_out: for row in tqdm(ds, desc=f"Building FINMME raw [{split}]"): try: # 1. 保存图片到本地 pil_img = row["image"] img_filename = f"finmme_{split}_{row['id']}.png" img_path = image_root / img_filename pil_img.save(img_path) # 2. 选项 options_list = split_options(row["options"]) # 3. 答案统一为大写 answer = str(row["answer"]).strip().upper() # 4. 容差 tol_raw = row.get("tolerance", None) tolerance = None if tol_raw is not None and not (isinstance(tol_raw, float) and math.isnan(tol_raw)): try: tolerance = float(tol_raw) except Exception: tolerance = None raw_item = FinMMERawItem( id=str(row["id"]), image_path=str(img_path), question=row["question_text"], options=options_list, answer=answer, question_type=question_type_to_enum(row.get("question_type", "other")), caption=row.get("verified_caption"), description=row.get("related_sentences"), unit=row.get("unit") or None, tolerance=tolerance, extra={}, ) except Exception: continue f_out.write(raw_item.model_dump_json(ensure_ascii=False) + "\n") print(f"[FINMME] Raw JSONL saved to: {out_path}") print(f"[FINMME] Images saved under: {image_root}") if __name__ == "__main__": build_finmme_raw_from_hf(split="train")