BEAR-benchmark / run_api_model.py
yqi19's picture
Add runnable eval code: API/local runners, GPT-judge scorer, per-task run.sh, util, README
ab9dacf verified
Raw
History Blame Contribute Delete
8.53 kB
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)