File size: 4,274 Bytes
43235e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# 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")