File size: 7,810 Bytes
b5beb60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import argparse
import itertools
import json
import os
import re
from functools import partial
from pathlib import Path
import numpy as np
import torch
from qwen_vl_utils import process_vision_info
from torchvision.ops.boxes import box_area
from tqdm import tqdm
from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
import cv2
import pandas as pd
import random
# from utils import seed_everything, get_model_id, update_res
import datetime
from num2words import num2words
import ast
import warnings
import csv

CAPABILITY_NAME = 'category'
def update_data_format(df_data):
    df_data = df_data.rename(columns={'capability': CAPABILITY_NAME})
    if 'dataset_name' in df_data.columns:
        df_data['sub_task'] = df_data['dataset_name']
        df_data.drop(columns=['dataset_name'], inplace=True)
        df_data.loc[df_data['sub_task'] == 'OCR-VQA', 'sub_task'] = 'BookOCR'
        df_data.loc[df_data[CAPABILITY_NAME] != 'Visual Reasoning', CAPABILITY_NAME] = 'Visual Perception'
        df_data['reasoning_type'] = df_data['reasoning_type'].fillna('')
        df_data.loc[df_data['reasoning_type'] == 'algebraic', 'reasoning_type'] = 'arithmetic'
        df_data.loc[df_data['task'] == 'Text Localization Bbox2Text', 'sub_task'] = 'Bbox2Text'
        df_data.loc[df_data['task'] == 'Text Localization Text2Bbox', 'sub_task'] = 'Text2Bbox'
        df_data.loc[df_data['task'] == 'Text Localization Bbox2Text', 'task'] = 'Text Localization'
        df_data.loc[df_data['task'] == 'Text Localization Text2Bbox', 'task'] = 'Text Localization'

        df_perception = df_data[df_data[CAPABILITY_NAME] == 'Visual Perception']
        df_reasoning = df_data[df_data[CAPABILITY_NAME] == 'Visual Reasoning'].copy()
        df_reasoning['task'] = df_reasoning['reasoning_type'].str.title()
        df_reasoning['task'] = df_reasoning['task'].apply(
            lambda x: x + ' Reasoning' if x in ['Arithmetic', 'Logical', 'Spatial'] else x
        )
        df_reasoning = df_reasoning.drop(columns=['reasoning_type'])  # mute SettingWithCopyWarning warnings
        return pd.concat([df_perception, df_reasoning], ignore_index=True)
    return df_data

answer_pattern = re.compile(r'<answer>(.*?)</answer>')
markdown_json_pattern = re.compile(r'```json(.*?)```', re.DOTALL)
def process_answer(answer):
    answer = answer.split('### Final Answer ###')[-1].strip() if '### Final Answer ###' in answer else answer
    answer = answer.split('Answer:')[-1].strip() if 'Answer:' in answer else answer
    matches = re.findall(answer_pattern, answer)
    answer = matches[-1] if matches else answer
    matches = re.findall(markdown_json_pattern, answer)
    answer = matches[-1] if matches else answer
    try:
        answer_json = json.loads(answer)
        answer = answer_json["answer"]
    except:
        pass
    return str(answer)

class NoMatchedEquationError(Exception):
    pass


def calculate(expression):
    try:
        exp = expression.split('=')[0].strip()
        node = ast.parse(exp, mode='eval')
        result = eval(compile(node, '<string>', 'eval'))
        return result
    except:
        return None
    
def extract_and_judge(expression, target_result):
    expression = expression.replace(" ", "").replace("$", "")
    result = calculate(expression)
    if result is None:
        raise NoMatchedEquationError(f"none error")
    else:
        return target_result.strip() in str(result).strip()
    
def check_relation(gt, ans, strict=False):
    # # cot: 200 direct: 25
    if strict:
        delta_len = 25
    else:
        delta_len = 200
    if abs(len(str(ans)) - len(str(gt))) > 200:
        return False
    
    gt = str(gt).strip()
    ans = str(ans).strip()

    if gt.lower() == ans.lower():
        return True

    ## rule 1: if string has million, then parse number
    # if "million" in ans or "increase" in ans or "decrease" in ans:
    #     a = re.findall(r'\d+', gt)
    #     for i in a:
    #         if str(i) in ans:
    #             return True

    ## rule 2: string exact match
    try:
        aa = int(gt.replace(",", "").replace("$", "").replace("*", "").replace("**", "").replace("@", "").replace("-","").replace(" ", "").replace("%", ""))
        # print(aa)
        words_list = ans.split(" ")
        for i in words_list:
            if int(aa) == int(i.replace(",", "").replace("$", "").replace("*", "").replace("**", "").replace("@", "").replace("-", "").replace(" ", "").replace("%", "").replace("million","").replace("increase","").replace("decrease","")):
                if len(words_list)<5:
                    return True
    except:
        pass
    
    try:
        aa = float(gt.replace(",", "").replace("$", "").replace("*", "").replace("**", "").replace("@", "").replace("-","").replace(" ", "").replace("%", ""))
        # print(aa)
        words_list = ans.split(" ")
        for i in words_list:
            if round(aa,4) ==round(float(i.replace(",", "").replace("$", "").replace("*", "").replace("**", "").replace("@", "").replace("-", "").replace(" ", "").replace("%", "").replace("million","").replace("increase","").replace("decrease","")),4):
                if len(words_list) < 3:
                    return True
    except:
        pass

    ## rule 3: if string can be converted to number, then use number to test, avoid '1' and '12'
    try:
        a_f = float(ans.replace(",", "").replace("$", ""))
        g_f = float(gt.replace(",", "").replace("$", ""))
        if a_f == g_f:
            return True
        else:
            return False
    except:
        pass
    ## rule 4: if answer contains equation e.g. 141-111=30
    try:
        aa = extract_and_judge(ans, gt)
        return aa
    except:
        pass

    ## rule 5: string contains thousandths like 1,000 or percentage like 10% 
    try:
        num_gt = float(gt.lstrip('$').replace(',', '').rstrip('%')) / 100 if "%" in gt else float(
            gt.lstrip('$').replace(',', ''))
        num_ans = float(ans.lstrip('$').replace(',', '').rstrip('%')) / 100 if "%" in ans else float(
            ans.lstrip('$').replace(',', ''))
        if num_gt == num_ans:
            return True
        else:
            return False
    except ValueError:
        pass

    ## rule 6: number to word e.g. eleven=>11
    try:
        num_gt = float(gt.lstrip('$').replace(',', '').rstrip('%')) / 100 if "%" in gt else float(
            gt.lstrip('$').replace(',', ''))
        if num2words(int(num_gt)).lower() == ans.lower():
            return True
        else:
            return False
    except ValueError:
        pass
    
    ## rule 7: string convert
    aa = gt.lower() in ans.lower()
    if aa:
        try:
            a = int(ans.lower().replace(gt.lower(), "").replace(" ", ""))
            if a:
                return False
            else:
                return True
        except:
            return True
        
def eval_mmdocbench(ans, gt_obj, strict=False):
    # 1.process ans
    ans = process_answer(ans)
    # 2.process ground truth
    # if isinstance(gt_obj[0], str):
    #     gt_obj = json.loads(gt_obj[0])
    # for gt_obj_ in gt_obj:
    #     gt_ls = []
    #     if isinstance(gt_obj_, list):
    #         for sub_gt_obj_ in gt_obj_:
    #             gt_ls.append(str(sub_gt_obj_['answer']))
    #     else:
    #         gt_ls.append(str(gt_obj_['answer']))
    gt_ls = []
    gt_obj_lst = json.loads(gt_obj)
    
    if type(gt_obj_lst[0]) == list:
        gt_obj_lst = gt_obj_lst[0]
    for item in gt_obj_lst: # gt_obj_lst is list
        gt_ls.append(item["answer"])

    # 3.calculate em
    cnt = 0
    em = 0
    for gt in gt_ls:
        if gt != "":
            cnt += 1
            flag = check_relation(gt, ans, strict)
            if flag:
                em += 1
    em /= cnt
    return em