File size: 16,687 Bytes
f239efc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
340
341
342
343
344
345
346
347
348
349
from functools import partial
import os
import json
from typing import OrderedDict

import tqdm
import torch
from PIL import Image
import ast
import numpy as np
from multiprocessing import Pool

from decord import VideoReader, cpu

import os
from tasks.eval.eval_utils import (
    dump_json,
    load_json,
    EvalDataset,
)
from dataclasses import dataclass
from openai import OpenAI
client = OpenAI(
    # This is the default and can be omitted
    api_key=os.environ.get("OPENAI_API_KEY"),
)

task_type2chatgpt_contents = OrderedDict({
    "MSVD_QA": {
        "system": "You are an intelligent chatbot designed for evaluating the correctness of generative outputs for question-answer pairs. "
                  "Your task is to compare the predicted answer with the correct answer and determine if they match meaningfully. Here's how you can accomplish the task:"
                  "------"
                  "##INSTRUCTIONS: "
                  "- Focus on the meaningful match between the predicted answer and the correct answer.\n"
                  "- Consider synonyms or paraphrases as valid matches.\n"
                  "- Evaluate the correctness of the prediction compared to the answer.",
        "user": """Please evaluate the following video-based question-answer pair:\n\n"""
                """Question: {question}\n"""
                """Correct Answer: {answer}\n"""
                """Predicted Answer: {pred}\n\n"""
                """Provide your evaluation only as a yes/no and score where the score is an integer value between 0 and 5, with 5 indicating the highest meaningful match. """
                """Please generate the response in the form of a Python dictionary string with keys 'pred' and 'score', where value of 'pred' is  a string of 'yes' or 'no' and value of 'score' is in INTEGER, not STRING."""
                """DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. """
                """For example, your response should look like this: {{'pred': 'yes', 'score': 4.8}}."""
    },
    "MSRVTT_QA": {
        "system": "You are an intelligent chatbot designed for evaluating the correctness of generative outputs for question-answer pairs. "
                  "Your task is to compare the predicted answer with the correct answer and determine if they match meaningfully. Here's how you can accomplish the task:"
                  "------"
                  "##INSTRUCTIONS: "
                  "- Focus on the meaningful match between the predicted answer and the correct answer.\n"
                  "- Consider synonyms or paraphrases as valid matches.\n"
                  "- Evaluate the correctness of the prediction compared to the answer.",
        "user": """Please evaluate the following video-based question-answer pair:\n\n"""
                """Question: {question}\n"""
                """Correct Answer: {answer}\n"""
                """Predicted Answer: {pred}\n\n"""
                """Provide your evaluation only as a yes/no and score where the score is an integer value between 0 and 5, with 5 indicating the highest meaningful match. """
                """Please generate the response in the form of a Python dictionary string with keys 'pred' and 'score', where value of 'pred' is  a string of 'yes' or 'no' and value of 'score' is in INTEGER, not STRING."""
                """DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. """
                """For example, your response should look like this: {{'pred': 'yes', 'score': 4.8}}."""
                # """Make sure you only response with text that Follows Python syntax. For example, your response should look like this: {'pred': 'yes', 'score': 4.8}."""
    },
    "ActivityNet": {
        "system": "You are an intelligent chatbot designed for evaluating the correctness of generative outputs for question-answer pairs. "
                  "Your task is to compare the predicted answer with the correct answer and determine if they match meaningfully. Here's how you can accomplish the task:"
                  "------"
                  "##INSTRUCTIONS: "
                  "- Focus on the meaningful match between the predicted answer and the correct answer.\n"
                  "- Consider synonyms or paraphrases as valid matches.\n"
                  "- Evaluate the correctness of the prediction compared to the answer.",
        "user": """Please evaluate the following video-based question-answer pair:\n\n"""
                """Question: {question}\n"""
                """Correct Answer: {answer}\n"""
                """Predicted Answer: {pred}\n\n"""
                """Provide your evaluation only as a yes/no and score where the score is an integer value between 0 and 5, with 5 indicating the highest meaningful match. """
                """Please generate the response in the form of a Python dictionary string with keys 'pred' and 'score', where value of 'pred' is  a string of 'yes' or 'no' and value of 'score' is in INTEGER, not STRING."""
                """DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. """
                """For example, your response should look like this: {{'pred': 'yes', 'score': 4.8}}."""
                # """Make sure you only response with text that Follows Python syntax. For example, your response should look like this: {'pred': 'yes', 'score': 4.8}."""
    },
    "TGIF_QA": {
        "system": "You are an intelligent chatbot designed for evaluating the correctness of generative outputs for question-answer pairs. "
                  "Your task is to compare the predicted answer with the correct answer and determine if they match meaningfully. Here's how you can accomplish the task:"
                  "------"
                  "##INSTRUCTIONS: "
                  "- Focus on the meaningful match between the predicted answer and the correct answer.\n"
                  "- Consider synonyms or paraphrases as valid matches.\n"
                  "- Evaluate the correctness of the prediction compared to the answer.",
        "user": """Please evaluate the following video-based question-answer pair:\n\n"""
                """Question: {question}\n"""
                """Correct Answer: {answer}\n"""
                """Predicted Answer: {pred}\n\n"""
                """Provide your evaluation only as a yes/no and score where the score is an integer value between 0 and 5, with 5 indicating the highest meaningful match. """
                """Please generate the response in the form of a Python dictionary string with keys 'pred' and 'score', where value of 'pred' is  a string of 'yes' or 'no' and value of 'score' is in INTEGER, not STRING."""
                """DO NOT PROVIDE ANY OTHER OUTPUT TEXT OR EXPLANATION. Only provide the Python dictionary string. """
                """For example, your response should look like this: {{'pred': 'yes', 'score': 4.8}}."""
                # """Make sure you only response with text that Follows Python syntax. For example, your response should look like this: {'pred': 'yes', 'score': 4.8}."""
    },
})

# Follow the instructions carefully and be helpful and precise with your answer.

def check_ans_qa(question, pred, gt, task_type, model="gpt-3.5-turbo-0125"):
    try:
        # Compute the temporal understanding score
        user_input = task_type2chatgpt_contents[task_type]['user']
        user_input = user_input.format(question=question, answer=gt, pred=pred)
        completion = client.chat.completions.create(
            model=model,
            messages=[
                {
                    "role": "system",
                    "content": task_type2chatgpt_contents[task_type]['system'],
                },
                {
                    "role": "user",
                    "content": user_input,
                }
            ]
        )
        # Convert response to a Python dictionary.
        # response_message = completion["choices"][0]["message"]["content"]
        response_message = completion.choices[0].message.content
        response_dict = ast.literal_eval(response_message)
        pred = response_dict['pred']
        score = response_dict['score']
        if not pred in ('yes', 'no') or not isinstance(score, (int, float)):
            raise ValueError(f"{model} doesn't follow")
        flag = pred == 'yes'
    except Exception as e:
        import traceback
        traceback.print_exc()
        flag, score = False, 0
        print(
            f"GPT cannot deal with:\n" 
            f"--pred: {pred}\n"
            f"--gt: {gt}\n"
            f"--gpt responded: {response_message}\n"
            "--will assign flag=False and score=0"
        )
        print(f"Dumb Answer in {task_type}")
    return flag, score

def chatgpt_eval(res, model="gpt-3.5-turbo-0125"):
    pred = res['pred']
    gt = res['gt']
    question=res['question']
    task_type = res['task_type']
    correct, score = check_ans_qa(question=question, pred=pred, gt=gt,task_type=task_type, model=model) # acc is bool, score is given by chatgpt
    # update the scores in result_list for this sample
    res['score'] = score
    res['correct'] = correct
    return res

def save_results(result_list, save_path, model="gpt-3.5-turbo-0125"):
    dump_json(result_list, save_path, 'inference_results.json')
    with Pool(7) as pool:
        func = partial(chatgpt_eval, model=model)
        result_list = [ res for res in tqdm.tqdm(pool.imap_unordered(func, result_list), total=len(result_list), desc='Language Chat Model Automated Evaluation...')]

        # result_list = pool.map(partial(chatgpt_eval, model=model), result_list)
    # result_list = [chatgpt_eval(res, model=model) for res in result_list]

    final_res, acc_dict = {}, {}
    correct, total, total_score = 0, 0, 0
    for i, res in enumerate(result_list):
        task_type = res['task_type']
        if task_type not in acc_dict:
            acc_dict[task_type] = {
                'correct': 0,
                'total': 0,
                'score': 0,
            } # correct, total
        acc_dict[task_type]['total'] += 1
        acc_dict[task_type]['correct'] += res['correct']
        acc_dict[task_type]['score'] += res['score']
     
    for k, v in acc_dict.items():
        final_res[k] = {
            'acc': v['correct'] / v['total'] * 100,
            'score': v['score'] / v['total']
        }
        correct += v['correct']
        total += v['total']
        total_score += v['score']

    final_res['Avg_Acc'] = correct / total * 100
    final_res['Avg_Score'] = total_score / total

    all_results = {
        "acc_dict": acc_dict,
        "result_list": result_list
    }
    dump_json(all_results, save_path, 'all_results.json')
    dump_json(final_res, save_path, 'upload_leaderboard.json')

def load_results(save_path):
    json_data = load_json(save_path, 'inference_results.json')
    return json_data

@dataclass
class OpenendQASample():
    question: str
    answer: str



class VideoQABenchDataset(EvalDataset):
    data_dir = "DATAS/VideoQA"
    data_list_info = OrderedDict({
        "MSVD_QA": OrderedDict(
            q_json_relpath="MSVD_Zero_Shot_QA/test_q.json", 
            a_json_relpath="MSVD_Zero_Shot_QA/test_a.json", 
            prefix="DATAS/VideoQA/MSVD_Zero_Shot_QA/videos", 
            data_type="video", 
            bound=False,
            question_key='question',
            answer_key='answer',
            name_key='video_name',
            postfix=('avi',),
        ),
        "MSRVTT_QA": OrderedDict(
            q_json_relpath="MSRVTT_Zero_Shot_QA/test_q.json", 
            a_json_relpath="MSRVTT_Zero_Shot_QA/test_a.json", 
            prefix="DATAS/VideoQA/MSRVTT_Zero_Shot_QA/videos/all", 
            data_type="video", 
            bound=False,
            question_key='question',
            answer_key='answer',
            name_key='video_name',
            postfix=('mp4', ),
        ), # don't has start & end 
        "ActivityNet": OrderedDict(
            q_json_relpath="ActivityNet/test_q.json", 
            a_json_relpath="ActivityNet/test_a.json", 
            prefix="DATAS/VideoQA/ActivityNet/all_test", 
            data_type="video", 
            bound=False,
            question_key='question',
            answer_key='answer',
            name_key='video_name',
            postfix=('mp4', 'mkv', 'webm'),
        ), # don't has start & end
        "TGIF_QA": OrderedDict(
            q_json_relpath="TGIF_QA/test_q.json", 
            a_json_relpath="TGIF_QA/test_a.json", 
            prefix="DATAS/VideoQA/TGIF_QA/tgif_videos", 
            data_type="gif", 
            bound=False,
            question_key='question',
            answer_key='answer',
            name_key='video_name',
            postfix=('gif',),
        ), # don't has start & end

    })

    def __init__(self, *args, **kwargs):
        # test_ratio for videoqa is for each sub dataset
        test_ratio = kwargs.pop('test_ratio', None)
        kwargs['test_ratio'] = None
        test_datasets = kwargs.pop('test_datasets', None)
        super().__init__(*args, **kwargs)
        test_ratio = 1 if test_ratio is None else test_ratio
        self.test_ratio = test_ratio
        if test_datasets is not None:
            data_list_info = {k:v for k,v in self.data_list_info.items() if k in test_datasets}
        else:
            data_list_info = self.data_list_info
        data_dir = self.data_dir

        self.data_list = []
        for k, v in data_list_info.items():
            with open(os.path.join(data_dir, v['q_json_relpath']), 'r') as f:
                quesions_json_data = json.load(f)
            with open(os.path.join(data_dir, v['a_json_relpath']), 'r') as f:
                answers_json_data = json.load(f)
            
            indexs = list(range(len(quesions_json_data)))
            np.random.RandomState(42).shuffle(indexs)
            num_samples = int(len(indexs) * self.test_ratio) if 0 < self.test_ratio <= 1 else int(self.test_ratio)
            indexs = indexs[:num_samples]
            for i in indexs:
                question_data = quesions_json_data[i]
                answer_data = answers_json_data[i]
                data = {}
                # why do we have anet's video name not in the original json file???
                if k == "ActivityNet":
                    question_data['video_name'] = 'v_' + question_data['video_name']
                data.update(**question_data)
                data.update(**answer_data)
                self.data_list.append({
                    'task_type': k,
                    'data': data,
                    **v, # all the infos
                })
        print(len(self.data_list))
        
    def __len__(self):
        return len(self.data_list)
    
    
    def __getitem__(self, idx):
        decord_method = self.decord_method[self.data_list[idx]['data_type']]
        bound = None
        if self.data_list[idx]['bound']:
            bound = (
                self.data_list[idx]['data']['start'],
                self.data_list[idx]['data']['end'],
            )
        video_name_key = self.data_list[idx]['name_key']
        video_name = self.data_list[idx]['data'][video_name_key]

        video_postfixs = self.data_list[idx]['postfix']
        video_paths =  []
        for p in video_postfixs:
            video_path = os.path.join(self.data_list[idx]['prefix'], video_name + '.' + p)
            if os.path.exists(video_path):
                video_paths.append(video_path) 
        assert len(video_paths) > 0, f'no video named {video_name}'
        # video_filename = self.data_list[idx]['data'][video_name_key] + video_postfix
        video_path = video_paths[0]
        images_group = decord_method(video_path, bound)

        question_key = self.data_list[idx]['question_key']
        answer_key = self.data_list[idx]['answer_key']
        sample = OpenendQASample(
            question=self.data_list[idx]['data'][question_key],
            answer=self.data_list[idx]['data'][answer_key]
        )
        question, answer = self.qa_template(sample)
            
        return {
            'video_pils': images_group, # some might use the original pils and do their own transforms
            'question': question,
            'video_path': video_path,
            'answer': answer,
            'task_type': self.data_list[idx]['task_type']
        }

    def qa_template(self, data: OpenendQASample):
        answer = data.answer
        question = data.question
        # by far, might use some prompting.
        return question, answer