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}")