File size: 10,180 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
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
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
try:
    from vlmeval.config import supported_VLM
except Exception:  # only needed for local ("image") models
    supported_VLM = None
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
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
from util.concate_image import concatenate_image
from PIL import Image
from io import BytesIO
import tempfile
import argparse
import os

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 concate_image_to_video(images, img_path):
    """
    Appends an external image (from img_path) to the list of PIL images.
    """
    extra_img = Image.open(img_path).convert("RGB")  # open and ensure RGB
    images.append(extra_img)
    return images

def generate_input_images_memory(mp4_path, num_frames=SAMPLE_FRAMES):
    """
    Extracts `num_frames` frames from a video and returns them as PIL.Image objects 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)

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

        # Convert OpenCV BGR image to RGB, then to PIL.Image
        rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        image = Image.fromarray(rgb)
        images.append(image)

    cap.release()
    return images

def evaluate_model_video(category_name, model_name, item):
    
    fix_seed()

    item_copy = item.copy()
    
    question = item.get("question", "")
    options = item.get("options", [])
    video = item.get("video", None)

    for format in ["direct"]:
        question_prompt = generate_question_prompt(format, category_name, question, options, model_category="image")
        print(f"{Fore.YELLOW}Evaluating item{Style.RESET_ALL}")
        print(f"{Fore.BLUE}Question Prompt: {question_prompt}{Style.RESET_ALL}")
        # print the input question prompt
        random_number = np.random.randint(0, 9999)
        input_images_open = generate_input_images_memory(video, SAMPLE_FRAMES)
        # conbine the input_images

        # debug this function
        combined_image = concatenate_image(input_images_open, rows=2, columns=8)

        # Use tempfile to avoid collisions between process
        with tempfile.NamedTemporaryFile(suffix=".jpg", prefix="temp_combined_image_", delete=False) as tmp_file:
            temp_image_path = tmp_file.name
            combined_image.save(temp_image_path, format="JPEG")

        print(f"{Fore.GREEN}Combined image saved as {temp_image_path}{Style.RESET_ALL}")

        response = supported_VLM[model_name]().generate([temp_image_path, question_prompt])

        # Optional: clean up after inference
        Path(temp_image_path).unlink(missing_ok=True)


        print(f"{Fore.CYAN}Response is: {response}{Style.RESET_ALL}")
        item_copy[f"{format}_reply"] = response
    
    return item_copy

def evaluate_model_interleaved(category_name, model_name, item):
    
    fix_seed()
    # load input_json file

    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"]:
        question_prompt = generate_question_prompt(format, category_name, question, options, model_category="image")
        print(f"{Fore.YELLOW}Evaluating item: {Style.RESET_ALL}")
        print(f"{Fore.BLUE}Question Prompt: {question_prompt}{Style.RESET_ALL}")
        # print the input question prompt
        random_number = np.random.randint(0, 9999)
        input_images_open = generate_input_images_memory(video, SAMPLE_FRAMES)
        # conbine the input_images
        input_images_open_new = concate_image_to_video(input_images_open, image)

        # debug this function
        combined_image = concatenate_image(input_images_open_new, rows=5, columns=7)

        # Use tempfile to avoid collisions between process
        with tempfile.NamedTemporaryFile(suffix=".jpg", prefix="temp_combined_image_", delete=False) as tmp_file:
            temp_image_path = tmp_file.name
            combined_image.save(temp_image_path, format="JPEG")

        print(f"{Fore.GREEN}Combined image saved as {temp_image_path}{Style.RESET_ALL}")

        response = supported_VLM[model_name]().generate([temp_image_path, question_prompt])

        # Optional: clean up after inference
        Path(temp_image_path).unlink(missing_ok=True)

        print(f"{Fore.YELLOW}Response for item: {response}{Style.RESET_ALL}")
        item_copy[f"{format}_reply"] = response

    return item_copy

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

    item_copy = item.copy()

    question = item.get("question", "")
    options = item.get("options", [])
    image = item.get("image", None)

    for format in ["direct"]:
        question_prompt = generate_question_prompt(format, category_name, question, options, model_category="image")
        print(f"{Fore.YELLOW}Evaluating item: {Style.RESET_ALL}")
        # print the input question prompt

        # if failure, try a few more attempts
        response = "error"
        for attempt in range(3):
            try:
                response = supported_VLM[model_name]().generate([image, question_prompt])
                break
            except:
                print(f"{Fore.RED}Error generating response for item, attempt {attempt + 1}. Retrying...{Style.RESET_ALL}")
                time.sleep(2 ** attempt)
                continue  # retry the same item

        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 VLM model on video QA tasks.")
    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=False, default="image", help="Unused for local image models; kept for CLI symmetry.")
    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

    print(f"{Fore.GREEN}Evaluating model: {model_name} on category: {category_name}{Style.RESET_ALL}")

    evaluate_output_path =f"final_{model_name}_evaluate_{evaluate_category}.json"
    tmp_dir = "tmp"
    os.makedirs(tmp_dir, exist_ok=True)
    tmp_path = os.path.join(tmp_dir, evaluate_output_path)

    # Load input
    with open(input_json_path, "r", encoding="utf-8") as f:
        input_data = json.load(f)

    # === RESUME LOGIC ===
    evaluate_output = []
    processed_ids = set()

    if os.path.exists(tmp_path):
        try:
            with open(tmp_path, "r", encoding="utf-8") as f:
                evaluate_output = json.load(f)
            # Build fast lookup of processed items: prefer explicit idx, else ordinal
            for pos, item in enumerate(evaluate_output):
                key = item.get("idx", pos)
                processed_ids.add(key)
            print(f"{Fore.YELLOW}[Resume] Loaded {len(evaluate_output)} partial results from {tmp_path}.{Style.RESET_ALL}")
        except Exception as e:
            print(f"{Fore.RED}[Resume] Could not load {tmp_path}: {e}. Starting fresh.{Style.RESET_ALL}")
            evaluate_output = []
            processed_ids = set()

    # Iterate and skip already processed
    for pos, item in enumerate(input_data):
        key = item.get("idx", pos)
        if key in processed_ids:
            continue  # already done

        subcat = item.get("category", "")
        if subcat in ["pointing", "trajectory", "bbox"]:
            output_item = evaluate_model_image(subcat, model_name, item)
        elif subcat in ["path planning", "relative direction"]:
            output_item = evaluate_model_interleaved(subcat, model_name, item)
        elif subcat in ["object localization", "next action prediction", "task progress reasoning"]:
            output_item = evaluate_model_video(subcat, model_name, item)
        elif item.get("video"):
            output_item = evaluate_model_video(subcat, model_name, item)
        elif item.get("image"):
            output_item = evaluate_model_image(subcat, model_name, item)
        else:
            output_item = item

        evaluate_output.append(output_item)
        processed_ids.add(key)

        # Save at tmp
        with open(tmp_path, "w", encoding="utf-8") as f:
            json.dump(evaluate_output, f, indent=4, ensure_ascii=False)

    # Write final output
    with open(evaluate_output_path, "w", encoding="utf-8") as f:
        json.dump(evaluate_output, f, indent=4, ensure_ascii=False)

    print(f"{Fore.CYAN} Done. Saved final results to: {evaluate_output_path}{Style.RESET_ALL}")