File size: 10,651 Bytes
a65550c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import re
from rouge import Rouge
import argparse
import os
import json
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity


spot_the_diff = ["Spot-the-Diff", "Birds-to-Words", "CLEVR-Change"]
image_edit_instruct = ["IEdit", "HQ-Edit", "MagicBrush"]
visual_story_telling = ["AESOP", "FlintstonesSV", "PororoSV", "VIST"]
visual_cloze = ["COMICS_Dialogue", "RecipeQA_VisualCloze"]
text_rich_vqa = ["WebQA", "TQA", "OCR-VQA", "DocVQA"]
multi_image_vqa = ["MIT-States_StateCoherence", "MIT-States_PropertyCoherence", "VISION", "RecipeQA_ImageCoherence"]

puzzle = ["RAVEN"]
nlrv2 = ["NLVR2_Mantis"]
qbench = ["QBench"]

class Eval:
    def __init__(self):
        self.periodStrip = re.compile("(?!<=\d)(\.)(?!\d)")
        self.commaStrip = re.compile("(\d)(\,)(\d)")
        self.punct = [
            ";",
            r"/",
            "[",
            "]",
            '"',
            "{",
            "}",
            "(",
            ")",
            "=",
            "+",
            "\\",
            "_",
            "-",
            ">",
            "<",
            "@",
            "`",
            ",",
            "?",
            "!",
        ]
        
    def processPunctuation(self, inText):
        outText = inText
        for p in self.punct:
            if (p + " " in inText or " " + p in inText) or (
                re.search(self.commaStrip, inText) != None
            ):
                outText = outText.replace(p, "")
            else:
                outText = outText.replace(p, " ")
        outText = self.periodStrip.sub("", outText, re.UNICODE)
        return outText
    
    def process(self, answer):
        answer = answer.replace("\n", " ")
        answer = answer.replace("\t", " ")
        answer = answer.strip()
        answer = self.processPunctuation(answer)
        answer = answer.strip('\'')
        answer = answer.strip('\"')
        answer = answer.strip(')')
        answer = answer.strip('(')
        answer = answer.strip().lower()
        return answer

    def evaluate_rouge(self,preds):
        rouge = Rouge()
        acc = {'f': []}
        eval_list = []
        for i, res in enumerate(preds):
            sample_id = res['sample_id']
            # print(sample_id)
            gt_ans = self.process(res["gt_response"])
            pred_ans = self.process(res["pred_response"])
            # assert gt_ans != ''

            if gt_ans == '':
                continue
            
            if pred_ans == '':
                s = 0
            else:
                if len(pred_ans) > 512:
                    pred_ans = pred_ans[0: 512]
                s = rouge.get_scores(pred_ans, gt_ans)[0]['rouge-l']['f']
            acc['f'].append(s)
            eval_list.append({'id':str(sample_id),'score':str(round(s,3))})
        results = {'Rouge-L f': np.mean(acc['f'])}
        return results,eval_list


    def judge_multi_choice(self,sample):
        sample_id = sample['sample_id']
        gt_ans = sample["gt_response"]
        pred_ans = sample["pred_response"]

        if ":" in pred_ans:
            a_list = pred_ans.split(":")
            a_list = [a.strip() for a in a_list ]
            for a in a_list:
                if len(a) == 1 and a[-1] in ["a", "b", "c", "d", "e", "f", "g", "h"]:
                    pred_ans = a

        if pred_ans == gt_ans:
            return 1
        else:
            return 0

    def process_sample(self,sample):
        sample["gt_response"] = self.process(sample["gt_response"])
        sample["pred_response"] = self.process(sample["pred_response"])

    def evaluate_multichoice(self, preditions):
        correct = 0
        eval_list = []
        for i, sample in enumerate(preditions):
            self.process_sample(sample)
            score = self.judge_multi_choice(sample)
            sample_id = sample['sample_id']
            sample['result'] = score
            eval_list.append({'id':str(sample_id),'score':str(score)})
            correct+=score
        return {'Accuracy':correct/len(preditions)},eval_list

    def evaluate_multi_choice_image(self,preditions):
        correct = 0
        eval_list = []
        for i,sample in enumerate(preditions):
            gt_ans = self.process(sample["gt_response"])
            pred_ans = self.process(sample["pred_response"])
            sample_id = sample['sample_id']

            if ":" in pred_ans:
                a_list = pred_ans.split(":")
                a_list = [a.strip() for a in a_list ]
                for a in a_list:
                    if len(a) == 1 and a[-1] in ["a", "b", "c", "d", "e", "f", "g", "h"]:
                        pred_ans = a

            if gt_ans == pred_ans:
                score = 1
            else:
                score = 0
            sample_id = sample['sample_id']
            sample['result'] = score
            eval_list.append({'id':str(sample_id),'score':str(score)})
            correct+=score
        return {'Accuracy':correct/len(preditions)},eval_list


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--result-dir', type=str, required=True)

    args = parser.parse_args()
    
    result_file = os.path.join(args.result_dir, "result.jsonl")

    if not os.path.exists(result_file):
        print('No prediction file found')
        exit(0)
    with open(result_file, 'r') as f:
        preds_all = [json.loads(line) for line in f]
    
    preds_all_dict = dict()
    for pred in preds_all:
        if pred["dataset"] not in preds_all_dict:
            preds_all_dict[pred["dataset"]] = list()
        preds_all_dict[pred["dataset"]].append(pred)

    image_choice_dataset_list = ["recipeqa-RecipeQA_VisualCloze", "RecipeQA_ImageCoherence", "COMICS_Panel"]
    E = Eval()

    eval_result_list = dict()
    eval_result_list_detail = dict()

    for dataset in preds_all_dict:
        
        preds = preds_all_dict[dataset]
        question_type = preds[0]["question_type"]
   
        if question_type == 'open-ended':
            eval_result, eval_list = E.evaluate_rouge(preds)

        elif question_type == 'multi-choice' or dataset == 'nlrv2':
            if dataset in image_choice_dataset_list:
                eval_result, eval_list = E.evaluate_multi_choice_image(preds)
            else:
                eval_result, eval_list = E.evaluate_multichoice(preds)

        else:
            eval_result = 'Dataset not supported'
            print('Dataset not supported')
            exit(0)

        print(dataset, end = ':  ')
        print(eval_result)

        eval_result_list[dataset] = eval_result
        eval_result_list_detail[dataset] = eval_list

    os.makedirs(args.result_dir, exist_ok=True)
    with open(os.path.join(args.result_dir, 'eval_dataset.json'), 'w') as f:
        json.dump(eval_result_list, f, indent=4)

    with open(os.path.join(args.result_dir,'eval_dataset_details.json'), 'w') as f:
        json.dump(eval_result_list_detail, f, indent=4)


    eval_cat_list = dict()
    print()

    # spot_the_diff
    score = 0
    count = 0
    for dataset in eval_result_list:
        if dataset in spot_the_diff:
            count += 1
            score += list(eval_result_list[dataset].values())[0]
    if count > 0:
        score /= count
        eval_cat_list["spot_the_diff"] = score
        print("spot_the_diff", end = ':  ')
        print('{:.2f}'.format(100 * score))

    # image_edit_instruct
    score = 0
    count = 0
    for dataset in eval_result_list:
        if dataset in image_edit_instruct:
            count += 1
            score += list(eval_result_list[dataset].values())[0]
    if count > 0:
        score /= count
        eval_cat_list["image_edit_instruct"] = score
        print("image_edit_instruct", end = ':  ')
        print('{:.2f}'.format(100 * score))

    # visual_story_telling
    score = 0
    count = 0
    for dataset in eval_result_list:
        if dataset in visual_story_telling:
            count += 1
            score += list(eval_result_list[dataset].values())[0]
    if count > 0:
        score /= count
        eval_cat_list["visual_story_telling"] = score
        print("visual_story_telling", end = ':  ')
        print('{:.2f}'.format(100 * score))

    # visual_cloze
    score = 0
    count = 0
    for dataset in eval_result_list:
        if dataset in visual_cloze:
            count += 1
            score += list(eval_result_list[dataset].values())[0]
    if count > 0:
        score /= count
        eval_cat_list["visual_cloze"] = score
        print("visual_cloze", end = ':  ')
        print('{:.2f}'.format(100 * score))

    # text_rich_vqa
    score = 0
    count = 0
    for dataset in eval_result_list:
        if dataset in text_rich_vqa:
            count += 1
            score += list(eval_result_list[dataset].values())[0]
    if count > 0:
        score /= count
        eval_cat_list["text_rich_vqa"] = score
        print("text_rich_vqa", end = ':  ')
        print('{:.2f}'.format(100 * score))

    # multi_image_vqa
    score = 0
    count = 0
    for dataset in eval_result_list:
        if dataset in multi_image_vqa:
            count += 1
            score += list(eval_result_list[dataset].values())[0]
    if count > 0:
        score /= count
        eval_cat_list["multi_image_vqa"] = score
        print("multi_image_vqa", end = ':  ')
        print('{:.2f}'.format(100 * score))

    # puzzle
    score = 0
    count = 0
    for dataset in eval_result_list:
        if dataset in puzzle:
            count += 1
            score += list(eval_result_list[dataset].values())[0]
    if count > 0:
        score /= count
        eval_cat_list["puzzle"] = score
        print("puzzle", end = ':  ')
        print('{:.2f}'.format(100 * score))

    # nlrv2
    score = 0
    count = 0
    for dataset in eval_result_list:
        if dataset in nlrv2:
            count += 1
            score += list(eval_result_list[dataset].values())[0]
    if count > 0:
        score /= count
        eval_cat_list["nlrv2"] = score
        print("nlrv2", end = ':  ')
        print('{:.2f}'.format(100 * score))

    # qbench
    score = 0
    count = 0
    for dataset in eval_result_list:
        if dataset in qbench:
            count += 1
            score += list(eval_result_list[dataset].values())[0]
    if count > 0:
        score /= count
        eval_cat_list["qbench"] = score
        print("qbench", end = ':  ')
        print('{:.2f}'.format(100 * score))

    with open(os.path.join(args.result_dir,'eval_cat.json'), 'w') as f:
        json.dump(eval_cat_list, f, indent=4)