File size: 8,533 Bytes
ab9dacf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import json
import re
import base64
import numpy as np
import torch
import time
try:
    import colorama
except Exception:
    colorama = None
from util.prompt_generation import generate_question_prompt
import argparse
try:
    from colorama import Fore, Style, init
except Exception:  # colorama is optional (cosmetic terminal colors)
    class _NoColor:
        def __getattr__(self, _):
            return ""
    Fore = Style = _NoColor()
    def init(*a, **k):
        return None
import cv2
from pathlib import Path
import tempfile
import os
from util.concate_image import concatenate_image
from PIL import Image
import io

SAMPLE_FRAMES = 16

def fix_seed():
    import random
    random.seed(42)
    np.random.seed(42)
    torch.manual_seed(42)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(42)

def generate_input_images_base64(mp4_path, num_frames=16):
    """
    Extracts `num_frames` frames from the video and returns base64-encoded images in memory.
    """
    cap = cv2.VideoCapture(mp4_path)
    if not cap.isOpened():
        raise ValueError(f"Cannot open video file: {mp4_path}")

    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    frame_indices = np.linspace(0, total_frames - 1, num=num_frames, dtype=int)

    results = []
    for i in frame_indices:
        cap.set(cv2.CAP_PROP_POS_FRAMES, i)
        success, frame = cap.read()
        if not success:
            continue

        _, buffer = cv2.imencode('.jpg', frame)  # encode frame to PNG format in memory
        base64_image = base64.b64encode(buffer).decode('utf-8')
        results.append({"image_base64": base64_image})

    cap.release()
    return results

    # return as a list:
    # [{"image": "path/to/image1.jpg"}, {"image": "path/to/image2.jpg"}, ...]
    return [{"image": str(output_dir / f"{i:04d}.jpg")} for i in range(saved_count)]

def evaluate_model_image(category_name, item, model_name, model_series):
    
    fix_seed()

    # only look for the correct category
    item_copy = item.copy()
    
    question = item.get("question", "")
    options = item.get("options", [])
    image = item.get("image", None)

    for format in ["direct", "cot"]:
        question_prompt = generate_question_prompt(format, category_name, question, options, model_category="general")
        print(f"Evaluating item {item.get('idx', item.get('id', '?'))}")

        input_content = [{"image": image}, {"text":question_prompt}]

        if model_series == "gemini":
            from util.gemini import generate_content
            response = generate_content(model_name, input_content)
        elif model_series == "gpt":
            from util.gpt import generate_content
            response = generate_content(model_name, input_content)
        elif model_series == "claude":
            from util.claude import generate_content
            response = generate_content(model_name, input_content)
        
        item_copy[f"{format}_reply"] = response

    return item_copy

def evaluate_model_interleaved(category_name, item, model_name, model_series):
    # only look for the correct category
    item_copy = item.copy()
    
    question = item.get("question", "")
    options = item.get("options", [])
    video = item.get("video", None)
    image = item.get("image", None)

    for format in ["direct", "cot"]:
        (first_prompt, second_prompt, third_prompt) = generate_question_prompt(format, category_name, question, options, model_category="general")
        print(f"Evaluating item {item.get('idx', item.get('id', '?'))}")

        # randomly generate a number to save the video images
        random_number = np.random.randint(1000, 9999)
        video_images = generate_input_images_base64(video,  SAMPLE_FRAMES)
        input_content = [{"text": first_prompt}] + video_images + [{"text": second_prompt}] + [{"image": image}] + [{"text": third_prompt}]

        if model_series == "gemini":
            from util.gemini import generate_content
            response = generate_content(model_name, input_content)
        elif model_series == "gpt":
            from util.gpt import generate_content
            response = generate_content(model_name, input_content)
        elif model_series == "claude":
            from util.claude import generate_content
            response = generate_content(model_name, input_content)
        
        item_copy[f"{format}_reply"] = response

    return item_copy

def evaluate_model_video(category_name, item, model_name, model_series):
    item_copy = item.copy()
    
    question = item.get("question", "")
    options = item.get("options", [])
    video = item.get("video", None)

    for format in ["direct", "cot"]:
        (first_prompt, second_prompt) = generate_question_prompt(format, category_name, question, options, model_category="general")
        print(f"{Fore.YELLOW} Evaluating item {item.get('idx', item.get('id', '?'))}{Style.RESET_ALL}")

        # randomly generate a number to save the video images
        random_number = np.random.randint(1000, 9999)
        input_images = generate_input_images_base64(video,  SAMPLE_FRAMES)
        input_content = [{"text": first_prompt}] + input_images + [{"text": second_prompt}]

        if model_series == "gemini":
            from util.gemini import generate_content
            response = generate_content(model_name, input_content)
        elif model_series == "gpt":
            from util.gpt import generate_content
            response = generate_content(model_name, input_content)
        elif model_series == "claude":
            from util.claude import generate_content
            response = generate_content(model_name, input_content)
        
        item_copy[f"{format}_reply"] = response

    return item_copy


if __name__ == "__main__":
    # only evaluate model within the certain category in the input json file
    parser = argparse.ArgumentParser(description="Evaluate model on a specific category from a JSON file.")
    parser.add_argument("--model_name", type=str, required=True, help="The specific model name (e.g., claude-sonnet-4-20250514)")
    parser.add_argument("--input_json_path", type=str, required=True, help="Path to the input JSON file.")
    parser.add_argument("--category_name", type=str, required=False, default="", help="Optional. Routing is auto-detected from each item's category.")
    parser.add_argument("--model_series", type=str, required=True, choices=["gemini", "gpt", "claude"], help="Model family/series.")
    parser.add_argument("--output_path", type=str, default=None, help="Path to save evaluation results. Default is auto-generated.")
    parser.add_argument("--evaluate_output_category", type=str, default=None, help="Path to save evaluation results. Default is auto-generated.")

    args = parser.parse_args()

    model_name = args.model_name
    input_json_path = args.input_json_path
    category_name = args.category_name
    model_series = args.model_series
    evaluate_category = args.evaluate_output_category
    if not evaluate_category:
        evaluate_category = os.path.splitext(os.path.basename(input_json_path))[0]

    evaluate_output_path = f"final_{model_name}_evaluate_{evaluate_category}.json"

    evaluate_output = []

    # open the input json file
    with open(input_json_path, 'r') as f:
        input_data = json.load(f)

    # evaluate each entry in input_data
    for idx, item in enumerate(input_data):
        category = item.get("category", "")
        if category in ["pointing", "trajectory", "bbox"]:
            output_item = evaluate_model_image(category, item, model_name, model_series)
        elif category in ["path planning", "relative direction"]:
            output_item = evaluate_model_interleaved(category, item, model_name, model_series)
        elif category in ["object localization", "next action prediction", "task progress reasoning"]:
            output_item = evaluate_model_video(category, item, model_name, model_series)
        elif item.get("video"):
            output_item = evaluate_model_video(category, item, model_name, model_series)
        elif item.get("image"):
            output_item = evaluate_model_image(category, item, model_name, model_series)
        else:
            output_item = item.copy()

        evaluate_output.append(output_item)

    # save the output to a json file
    with open(evaluate_output_path, 'w') as f:
        json.dump(evaluate_output, f, indent=4)