| |
| """ |
| Public RealVideo-Bench evaluation script. |
| |
| This file merges the dataset/meta preparation flow from process.py with the |
| response parsing and accuracy flow from result/parse_res.py. It intentionally |
| contains no private paths, private imports, API keys, or vendor-specific secrets. |
| |
| Typical usage: |
| |
| 1. Build task jsonl files from the released dataset layout: |
| python public_eval.py build-meta --dataset-root /path/to/RealVideo-Bench/data --output-dir task |
| |
| 2. Run model inference with an OpenAI-compatible vision API: |
| export REALVIDEO_API_KEY="YOUR_API_KEY" |
| export REALVIDEO_BASE_URL="https://your.openai-compatible.endpoint/v1" |
| python public_eval.py infer --task-file task/task1_meta.jsonl --task-type 1 \ |
| --video-root /path/to/RealVideo-Bench/data --model YOUR_MODEL \ |
| --output result/task_1/your_model_fps5.jsonl |
| |
| 3. Parse model responses: |
| python public_eval.py parse --input result/task_1/your_model_fps5.jsonl \ |
| --task-type 1 --output result/parse_res/task_1/your_model_fps5.jsonl \ |
| --parser api --model YOUR_TEXT_MODEL |
| |
| 4. Calculate accuracy: |
| python public_eval.py accuracy --input result/parse_res/task_1/your_model_fps5.jsonl \ |
| --task-type 1 --meta-file task/task1_meta.jsonl |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import base64 |
| import copy |
| import json |
| import os |
| import random |
| import re |
| import threading |
| import time |
| import traceback |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from pathlib import Path |
| from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple |
|
|
| try: |
| from tqdm import tqdm |
| except ImportError: |
| def tqdm(iterable: Iterable[Any], **_: Any) -> Iterable[Any]: |
| return iterable |
|
|
|
|
| VIDEO_SUFFIXES = (".mp4", ".avi", ".mkv", ".mov", ".webm") |
| DEFAULT_API_KEY_ENVS = ("REALVIDEO_API_KEY", "OPENAI_API_KEY") |
| DEFAULT_BASE_URL_ENVS = ("REALVIDEO_BASE_URL", "OPENAI_BASE_URL") |
|
|
|
|
| PROMPT_TASK_1 = """Determine whether the given video is generated by modern AI-based generative models (AIGC). |
| |
| Videos created using traditional computer graphics (CG), animation pipelines, game engines, or professional rendering tools should NOT be classified as AIGC, even though they are not captured from the real world. This includes stylized or animated content, as well as game footage. |
| |
| Such videos may exhibit visual artifacts due to artistic design, rendering limitations, compression, or real-time graphics constraints. However, these artifacts are fundamentally different from those introduced by AI generative models and should NOT be used as evidence for AIGC classification. |
| |
| Your judgment should be based on the presence of artifacts that are characteristic of AIGC methods, arising from the limitations of generative models. |
| |
| Typical AIGC artifacts include, but are not limited to: |
| - temporal inconsistency (e.g., flickering, unstable details across frames), |
| - structural distortions (e.g., warped objects, inconsistent geometry), |
| - unnatural motion or dynamics, |
| - semantic incoherence (e.g., objects appearing/disappearing or morphing inconsistently), |
| - abnormal visual appearance or texture anomalies (e.g., overly smooth, painterly, or "oily" rendering). |
| |
| Do NOT rely solely on visual style (e.g., animation, rendering style, or game graphics) when making your judgment. Instead, focus on identifying artifact patterns that are indicative of AI-based generation. |
| |
| If such AIGC-specific artifacts are clearly present, classify the video as "yes". Otherwise, classify it as "no". |
| |
| Respond with "yes" if the video is AIGC, and "no" otherwise.""" |
|
|
|
|
| PROMPT_TASK_2 = """You are given two videos, <Video A> and <Video B>. Both videos are generated by modern AI-based generative models (AIGC). |
| |
| Your task is to determine which video exhibits higher perceptual realism, i.e., which video contains fewer, less noticeable, or less severe artifacts introduced by generative models. |
| |
| The comparison should be based on the presence and severity of AIGC-specific artifacts, rather than overall visual style or aesthetic preference. |
| |
| Typical AIGC artifacts include, but are not limited to: |
| - temporal inconsistency (e.g., flickering, unstable details across frames), |
| - structural distortions (e.g., warped objects, inconsistent geometry), |
| - unnatural motion or dynamics, |
| - semantic incoherence (e.g., objects appearing/disappearing or morphing inconsistently), |
| - abnormal visual appearance or texture anomalies (e.g., overly smooth, painterly, or "oily" rendering). |
| |
| When making your decision: |
| - Focus on the **severity, frequency, and perceptibility** of such artifacts. |
| - A video with fewer and less perceptible artifacts should be considered more realistic. |
| - Minor or barely noticeable artifacts are less important than severe or obvious ones. |
| |
| Do NOT base your decision on: |
| - stylistic differences, |
| - resolution or sharpness alone, |
| - color grading or lighting preferences, |
| - high-level semantics or scene plausibility. |
| |
| Do not be biased by video length, scene complexity, or content diversity. |
| |
| Even if both videos contain artifacts, you must choose the one that is relatively more realistic. |
| |
| Respond with: |
| - "<Video A>" if <Video A> is more realistic, |
| - "<Video B>" if <Video B> is more realistic.""" |
|
|
|
|
| PROMPT_TASK_3 = """You are given a video that is generated by a modern AI-based generative model (AIGC). |
| |
| For the following options, select all AIGC-specific artifacts that are clearly observable in the video. |
| |
| Option: |
| {OPTION} |
| |
| Respond using the corresponding letter(s), separated by commas if multiple are selected (e.g., "A", "B,D", "A,C,E").""" |
|
|
|
|
| PARSE_PROMPT_TASK_1 = """You are an answer extraction system. |
| |
| The original task is to determine whether a video is generated by an AI-based generative model (AIGC): |
| - "yes" means the video is AI-generated. |
| - "no" means the video is not AI-generated. |
| |
| You are given a model response that may contain lengthy reasoning, analysis, self-corrections, or <think>...</think> blocks. |
| |
| Your task is to extract only the model's final intended answer. |
| |
| Model Response: |
| {Response} |
| |
| Rules: |
| 1. Ignore all reasoning, explanations, and intermediate analysis. |
| 2. Focus only on the final conclusion. |
| 3. The only valid outputs are: |
| - "yes" |
| - "no" |
| 4. Output exactly one valid answer without any additional text or explanation. |
| 5. If the response does not contain a clear final answer indicating whether the video is AI-generated, output: |
| "Invalid" |
| """ |
|
|
|
|
| PARSE_PROMPT_TASK_2 = """You are an answer extraction system. |
| |
| The original task is to compare two AI-generated videos, <Video A> and <Video B>, and determine which video has higher perceptual realism, i.e., which video contains fewer or less severe AIGC-specific artifacts. |
| |
| The only valid answers are: |
| - "<Video A>" |
| - "<Video B>" |
| |
| You are given a model response that may contain lengthy reasoning, analysis, self-corrections, or <think>...</think> blocks. |
| |
| Your task is to extract only the model's final intended answer. |
| |
| Model Response: |
| {Response} |
| |
| Rules: |
| 1. Ignore all reasoning, explanations, and intermediate analysis. |
| 2. Focus only on the final conclusion. |
| 3. Output exactly one of the following: |
| - "<Video A>" |
| - "<Video B>" |
| 4. Do not output any additional text or explanation. |
| 5. If the response does not contain a clear final answer indicating which video is more realistic, output: |
| "Invalid" |
| """ |
|
|
|
|
| PARSE_PROMPT_TASK_3 = """You are an answer extraction system. |
| |
| The original task is to identify all AIGC-specific artifacts that are clearly observable in a given AI-generated video. |
| |
| The candidate options are multiple-choice options labeled with letters (e.g., A-F). Multiple options may be correct. |
| |
| You are given a model response that may contain lengthy reasoning, analysis, self-corrections, or <think>...</think> blocks. |
| |
| Your task is to extract only the model's final intended answer. |
| |
| Model Response: |
| {Response} |
| |
| Rules: |
| 1. Ignore all reasoning, explanations, and intermediate analysis. |
| 2. Focus only on the final conclusion. |
| 3. Extract only the selected option letters. |
| 4. If multiple options are selected, output them separated by commas (e.g., "A,C,E"). |
| 5. Do not output any additional text or explanation. |
| 6. Only output valid option letters that appear in the final answer. |
| 7. If the response does not contain a clear final answer, output: |
| "Invalid" |
| """ |
|
|
|
|
| PARSE_PROMPTS = { |
| 1: PARSE_PROMPT_TASK_1, |
| 2: PARSE_PROMPT_TASK_2, |
| 3: PARSE_PROMPT_TASK_3, |
| } |
|
|
|
|
| def ensure_parent(file_path: str | Path) -> None: |
| parent = Path(file_path).expanduser().parent |
| if str(parent) and str(parent) != ".": |
| parent.mkdir(parents=True, exist_ok=True) |
|
|
|
|
| def load_json(file_path: str | Path) -> Any: |
| with open(file_path, "r", encoding="utf-8") as file: |
| return json.load(file) |
|
|
|
|
| def save_json(data: Any, file_path: str | Path) -> None: |
| ensure_parent(file_path) |
| with open(file_path, "w", encoding="utf-8") as file: |
| json.dump(data, file, ensure_ascii=False, indent=4) |
|
|
|
|
| def load_jsonl(file_path: str | Path) -> List[Dict[str, Any]]: |
| data = [] |
| with open(file_path, "r", encoding="utf-8") as file: |
| for line_no, line in enumerate(file, start=1): |
| line = line.strip() |
| if not line: |
| continue |
| try: |
| data.append(json.loads(line)) |
| except json.JSONDecodeError as exc: |
| raise ValueError(f"Invalid JSONL at {file_path}:{line_no}") from exc |
| return data |
|
|
|
|
| def save_jsonl(data: Sequence[Dict[str, Any]], file_path: str | Path) -> None: |
| ensure_parent(file_path) |
| with open(file_path, "w", encoding="utf-8") as file: |
| for item in data: |
| file.write(json.dumps(item, ensure_ascii=False) + "\n") |
|
|
|
|
| def append_jsonl(item: Dict[str, Any], file_path: str | Path) -> None: |
| ensure_parent(file_path) |
| with open(file_path, "a", encoding="utf-8") as file: |
| file.write(json.dumps(item, ensure_ascii=False) + "\n") |
| file.flush() |
|
|
|
|
| def list_video_files(video_dir: str | Path) -> List[Path]: |
| video_dir = Path(video_dir) |
| return sorted( |
| path |
| for path in video_dir.iterdir() |
| if path.is_file() and path.suffix.lower() in VIDEO_SUFFIXES |
| ) |
|
|
|
|
| def public_path(path: str | Path, root: str | Path, use_absolute_paths: bool) -> str: |
| path = Path(path) |
| root = Path(root) |
| if use_absolute_paths: |
| return str(path.resolve()) |
| return path.relative_to(root).as_posix() |
|
|
|
|
| def build_task3_prompt(option: Optional[Sequence[str]] = None) -> str: |
| if option is None: |
| raise ValueError("Task 3 requires an 'option' list in each item.") |
| option_str = "\n".join(f"{chr(65 + idx)}. {opt}" for idx, opt in enumerate(option)) |
| return PROMPT_TASK_3.format(OPTION=option_str) |
|
|
|
|
| def get_item_question(item: Dict[str, Any], default_task_type: Optional[int] = None) -> str: |
| task_type = int(item.get("task_type", default_task_type)) |
| if task_type == 1: |
| return PROMPT_TASK_1 |
| if task_type == 2: |
| return PROMPT_TASK_2 |
| if task_type == 3: |
| return build_task3_prompt(item.get("option")) |
| raise ValueError(f"Unsupported task_type: {task_type}") |
|
|
|
|
| def get_item_video_paths(item: Dict[str, Any]) -> List[str]: |
| if "video_path" in item: |
| video_path = item["video_path"] |
| if isinstance(video_path, (list, tuple)): |
| return [str(path) for path in video_path] |
| return [str(video_path)] |
|
|
| candidate_key_pairs = [ |
| ("video_path_a", "video_path_b"), |
| ("video_path_A", "video_path_B"), |
| ("video_a_path", "video_b_path"), |
| ("video_A_path", "video_B_path"), |
| ("video_a", "video_b"), |
| ("video_A", "video_B"), |
| ("Video A", "Video B"), |
| ] |
| for key_a, key_b in candidate_key_pairs: |
| if key_a in item and key_b in item: |
| return [str(item[key_a]), str(item[key_b])] |
|
|
| raise KeyError("Cannot find video path field(s) in item.") |
|
|
|
|
| def build_item_key(item: Dict[str, Any]) -> str: |
| if "sample_id" in item: |
| task_type = item.get("task_type") |
| if task_type is not None: |
| return f"task_{task_type}:sample_{item['sample_id']}" |
| return f"sample_{item['sample_id']}" |
|
|
| video_paths = get_item_video_paths(item) |
| if len(video_paths) == 1: |
| return video_paths[0] |
| return json.dumps(video_paths, ensure_ascii=False) |
|
|
|
|
| def resolve_video_path(video_path: str, video_root: Optional[str | Path]) -> Path: |
| path = Path(video_path).expanduser() |
| if path.is_absolute(): |
| if not path.exists(): |
| raise FileNotFoundError(f"Video not found: {path}") |
| return path |
|
|
| candidates = [] |
| if video_root: |
| candidates.append(Path(video_root).expanduser() / path) |
| candidates.append(Path.cwd() / path) |
|
|
| for candidate in candidates: |
| if candidate.exists(): |
| return candidate |
| raise FileNotFoundError( |
| f"Video not found: {video_path}. Pass --video-root if paths are relative." |
| ) |
|
|
|
|
| def resolve_item_video_paths( |
| item: Dict[str, Any], |
| video_root: Optional[str | Path], |
| ) -> List[Path]: |
| return [resolve_video_path(path, video_root) for path in get_item_video_paths(item)] |
|
|
|
|
| def infer_answer_from_task1_filename(video_name: str) -> str: |
| lower_name = video_name.lower() |
| if "fake" in lower_name: |
| return "yes" |
| if "real" in lower_name: |
| return "no" |
| raise ValueError( |
| f"Cannot infer Task 1 answer from filename '{video_name}'. " |
| "Expected filename to contain 'fake' or 'real'." |
| ) |
|
|
|
|
| def replace_real_with_fake(video_name: str) -> str: |
| if "real" in video_name: |
| return video_name.replace("real", "fake", 1) |
| if "Real" in video_name: |
| return video_name.replace("Real", "Fake", 1) |
| if "REAL" in video_name: |
| return video_name.replace("REAL", "FAKE", 1) |
| raise ValueError(f"Cannot derive fake filename from real filename: {video_name}") |
|
|
|
|
| def build_meta_for_task1( |
| dataset_root: str | Path, |
| output_dir: str | Path, |
| use_absolute_paths: bool = False, |
| ) -> List[Dict[str, Any]]: |
| dataset_root = Path(dataset_root) |
| video_dir = dataset_root / "Task_1" / "videos" |
| data = [] |
| for sample_id, video_path in enumerate(list_video_files(video_dir), start=1): |
| data.append( |
| { |
| "task_type": 1, |
| "sample_id": sample_id, |
| "video_path": [public_path(video_path, dataset_root, use_absolute_paths)], |
| "answer": infer_answer_from_task1_filename(video_path.name), |
| "level": None, |
| } |
| ) |
| save_jsonl(data, Path(output_dir) / "task1_meta.jsonl") |
| return data |
|
|
|
|
| def build_meta_for_task2( |
| dataset_root: str | Path, |
| output_dir: str | Path, |
| use_absolute_paths: bool = False, |
| ) -> List[Dict[str, Any]]: |
| dataset_root = Path(dataset_root) |
| video_dir = dataset_root / "Task_2" / "videos" |
| real_videos = [ |
| path for path in list_video_files(video_dir) if "real" in path.name.lower() |
| ] |
|
|
| data = [] |
| for sample_id, real_video_path in enumerate(real_videos, start=1): |
| fake_video_path = video_dir / replace_real_with_fake(real_video_path.name) |
| if not fake_video_path.exists(): |
| raise FileNotFoundError(f"Expected fake video not found: {fake_video_path}") |
|
|
| real_path = public_path(real_video_path, dataset_root, use_absolute_paths) |
| fake_path = public_path(fake_video_path, dataset_root, use_absolute_paths) |
| if sample_id % 2 == 1: |
| video_paths = [fake_path, real_path] |
| answer = "<Video B>" |
| else: |
| video_paths = [real_path, fake_path] |
| answer = "<Video A>" |
|
|
| data.append( |
| { |
| "task_type": 2, |
| "sample_id": sample_id, |
| "video_path": video_paths, |
| "answer": answer, |
| "level": None, |
| } |
| ) |
|
|
| save_jsonl(data, Path(output_dir) / "task2_meta.jsonl") |
| return data |
|
|
|
|
| def build_meta_for_task3( |
| dataset_root: str | Path, |
| output_dir: str | Path, |
| use_absolute_paths: bool = False, |
| seed: int = 42, |
| ) -> List[Dict[str, Any]]: |
| dataset_root = Path(dataset_root) |
| video_dir = dataset_root / "Task_3" / "videos" |
| question_json = dataset_root / "Task_3" / "task3_questions.json" |
| question_data = load_json(question_json) |
| rng = random.Random(seed) |
|
|
| data = [] |
| for sample_id, qa_item in enumerate(question_data, start=1): |
| video_name = Path(qa_item["video"][0]).name |
| video_path = video_dir / video_name |
| if not video_path.exists(): |
| raise FileNotFoundError(f"Expected video not found: {video_path}") |
|
|
| shuffled_options = copy.deepcopy(qa_item["options"]) |
| rng.shuffle(shuffled_options) |
|
|
| option_labels = [] |
| answer_idx = [] |
| answer_letter = [] |
| correct_labels = [] |
| for option_idx, option in enumerate(shuffled_options): |
| option_labels.append(option["label"]) |
| if option["is_correct"] is True: |
| answer_idx.append(option_idx) |
| answer_letter.append(chr(65 + option_idx)) |
| correct_labels.append(option["label"]) |
|
|
| matched_answer_num = 0 |
| for expected_answer in qa_item["answer"]: |
| if any(expected_answer in correct_label for correct_label in correct_labels): |
| matched_answer_num += 1 |
| else: |
| raise ValueError( |
| f"Answer '{expected_answer}' not found in options for sample_id {sample_id}" |
| ) |
| if matched_answer_num != len(qa_item["answer"]): |
| raise ValueError( |
| f"Matched answer count ({matched_answer_num}) does not equal " |
| f"expected ({len(qa_item['answer'])}) for sample_id {sample_id}" |
| ) |
|
|
| data.append( |
| { |
| "task_type": 3, |
| "sample_id": sample_id, |
| "video_path": [public_path(video_path, dataset_root, use_absolute_paths)], |
| "option": option_labels, |
| "answer_idx": answer_idx, |
| "answer_letter": answer_letter, |
| "option_dic": copy.deepcopy(qa_item["options"]), |
| "answer": ",".join(answer_letter), |
| "level": None, |
| } |
| ) |
|
|
| save_jsonl(data, Path(output_dir) / "task3_meta.jsonl") |
| return data |
|
|
|
|
| def add_level_info(dataset_root: str | Path, output_dir: str | Path) -> None: |
| dataset_root = Path(dataset_root) |
| output_dir = Path(output_dir) |
|
|
| task1_meta = output_dir / "task1_meta.jsonl" |
| task1_level_json = dataset_root / "Task_1" / "metadata.json" |
| if task1_meta.exists() and task1_level_json.exists(): |
| task1_level_info = {} |
| for item in load_json(task1_level_json): |
| task1_level_info[item["real_filename"]] = item["real_rating"] |
| task1_level_info[item["fake_filename"]] = item["fake_rating"] |
| data = load_jsonl(task1_meta) |
| for item in data: |
| item["level"] = task1_level_info.get(Path(item["video_path"][0]).name) |
| save_jsonl(data, task1_meta) |
|
|
| task2_meta = output_dir / "task2_meta.jsonl" |
| task2_level_json = dataset_root / "Task_2" / "metadata.json" |
| if task2_meta.exists() and task2_level_json.exists(): |
| task2_level_info = {} |
| for item in load_json(task2_level_json): |
| task2_level_info[item["real_filename"]] = item["pair_rating"] |
| data = load_jsonl(task2_meta) |
| for item in data: |
| real_video = next( |
| path for path in item["video_path"] if "real" in Path(path).name.lower() |
| ) |
| item["level"] = task2_level_info.get(Path(real_video).name) |
| save_jsonl(data, task2_meta) |
|
|
| task3_meta = output_dir / "task3_meta.jsonl" |
| task3_level_json = dataset_root / "Task_3" / "metadata.json" |
| if task3_meta.exists() and task3_level_json.exists(): |
| task3_level_info = {} |
| for item in load_json(task3_level_json): |
| task3_level_info[item["stable_identity"]["filename"]] = item["rating"] |
| data = load_jsonl(task3_meta) |
| for item in data: |
| item["level"] = task3_level_info.get(Path(item["video_path"][0]).name) |
| save_jsonl(data, task3_meta) |
|
|
|
|
| def build_meta_files(args: argparse.Namespace) -> None: |
| if 1 in args.tasks: |
| task1 = build_meta_for_task1( |
| dataset_root=args.dataset_root, |
| output_dir=args.output_dir, |
| use_absolute_paths=args.absolute_video_paths, |
| ) |
| print(f"Task 1 meta samples: {len(task1)}") |
| if 2 in args.tasks: |
| task2 = build_meta_for_task2( |
| dataset_root=args.dataset_root, |
| output_dir=args.output_dir, |
| use_absolute_paths=args.absolute_video_paths, |
| ) |
| print(f"Task 2 meta samples: {len(task2)}") |
| if 3 in args.tasks: |
| task3 = build_meta_for_task3( |
| dataset_root=args.dataset_root, |
| output_dir=args.output_dir, |
| use_absolute_paths=args.absolute_video_paths, |
| seed=args.seed, |
| ) |
| print(f"Task 3 meta samples: {len(task3)}") |
| if args.add_level: |
| add_level_info(args.dataset_root, args.output_dir) |
| print("Level info added when metadata.json files were available.") |
|
|
|
|
| def get_env_value(names: Sequence[str]) -> Optional[str]: |
| for name in names: |
| value = os.environ.get(name) |
| if value: |
| return value |
| return None |
|
|
|
|
| class OpenAICompatibleClient: |
| """Small wrapper around an OpenAI-compatible chat-completions endpoint.""" |
|
|
| def __init__( |
| self, |
| model: str, |
| api_key: Optional[str] = None, |
| base_url: Optional[str] = None, |
| timeout: float = 300.0, |
| ) -> None: |
| self.model = model |
| self.api_key = api_key or get_env_value(DEFAULT_API_KEY_ENVS) |
| self.base_url = base_url or get_env_value(DEFAULT_BASE_URL_ENVS) |
| self.timeout = timeout |
| if not self.api_key: |
| envs = " or ".join(DEFAULT_API_KEY_ENVS) |
| raise ValueError(f"Missing API key. Set {envs}, or pass --api-key.") |
|
|
| try: |
| from openai import OpenAI |
| except ImportError as exc: |
| raise ImportError("Please install the OpenAI Python package: pip install openai") from exc |
|
|
| kwargs = {"api_key": self.api_key, "timeout": self.timeout} |
| if self.base_url: |
| kwargs["base_url"] = self.base_url |
| self.client = OpenAI(**kwargs) |
|
|
| def generate( |
| self, |
| content: str | List[Dict[str, Any]], |
| max_tokens: int, |
| temperature: float, |
| max_retries: int, |
| retry_interval: float, |
| ) -> str: |
| messages = [{"role": "user", "content": content}] |
| last_error = None |
| for attempt in range(1, max_retries + 1): |
| try: |
| response = self.client.chat.completions.create( |
| model=self.model, |
| messages=messages, |
| temperature=temperature, |
| max_tokens=max_tokens, |
| ) |
| return response.choices[0].message.content or "" |
| except Exception as exc: |
| last_error = exc |
| if attempt == max_retries: |
| raise |
| time.sleep(retry_interval * attempt) |
| raise RuntimeError("API request failed") from last_error |
|
|
|
|
| def encode_jpeg_frame(frame: Any, max_image_side: int, jpeg_quality: int) -> str: |
| try: |
| import cv2 |
| except ImportError as exc: |
| raise ImportError("Please install OpenCV for frame sampling: pip install opencv-python") from exc |
|
|
| height, width = frame.shape[:2] |
| if max_image_side > 0 and max(height, width) > max_image_side: |
| scale = max_image_side / max(height, width) |
| new_size = (max(1, int(width * scale)), max(1, int(height * scale))) |
| frame = cv2.resize(frame, new_size, interpolation=cv2.INTER_AREA) |
|
|
| ok, buffer = cv2.imencode( |
| ".jpg", |
| frame, |
| [int(cv2.IMWRITE_JPEG_QUALITY), int(jpeg_quality)], |
| ) |
| if not ok: |
| raise RuntimeError("Failed to encode sampled video frame as JPEG.") |
| encoded = base64.b64encode(buffer.tobytes()).decode("utf-8") |
| return f"data:image/jpeg;base64,{encoded}" |
|
|
|
|
| def sample_video_frames_as_data_urls( |
| video_path: str | Path, |
| fps: float, |
| max_frames: int, |
| max_image_side: int, |
| jpeg_quality: int, |
| ) -> List[str]: |
| try: |
| import cv2 |
| except ImportError as exc: |
| raise ImportError("Please install OpenCV for frame sampling: pip install opencv-python") from exc |
|
|
| video_path = Path(video_path) |
| cap = cv2.VideoCapture(str(video_path)) |
| if not cap.isOpened(): |
| raise RuntimeError(f"Failed to open video: {video_path}") |
|
|
| native_fps = cap.get(cv2.CAP_PROP_FPS) or fps or 1.0 |
| frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) |
|
|
| frame_indices = [] |
| if frame_count > 0: |
| duration = frame_count / max(native_fps, 1e-6) |
| target_count = max(1, int(round(duration * fps))) if fps > 0 else frame_count |
| if max_frames > 0: |
| target_count = min(target_count, max_frames) |
| if target_count == 1: |
| frame_indices = [0] |
| else: |
| step = max(frame_count - 1, 1) / float(target_count - 1) |
| frame_indices = [min(frame_count - 1, int(round(idx * step))) for idx in range(target_count)] |
| else: |
| step = max(1, int(round(native_fps / fps))) if fps > 0 else 1 |
| idx = 0 |
| while True: |
| ok, _ = cap.read() |
| if not ok: |
| break |
| if idx % step == 0: |
| frame_indices.append(idx) |
| if max_frames > 0 and len(frame_indices) >= max_frames: |
| break |
| idx += 1 |
|
|
| data_urls = [] |
| for frame_idx in frame_indices: |
| cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx) |
| ok, frame = cap.read() |
| if not ok: |
| continue |
| data_urls.append(encode_jpeg_frame(frame, max_image_side, jpeg_quality)) |
| cap.release() |
|
|
| if not data_urls: |
| raise RuntimeError(f"No frames sampled from video: {video_path}") |
| return data_urls |
|
|
|
|
| def image_part(data_url: str, image_detail: str) -> Dict[str, Any]: |
| part = {"type": "image_url", "image_url": {"url": data_url}} |
| if image_detail: |
| part["image_url"]["detail"] = image_detail |
| return part |
|
|
|
|
| def build_vision_content( |
| item: Dict[str, Any], |
| video_paths: Sequence[Path], |
| task_type: int, |
| fps: float, |
| max_frames: int, |
| max_image_side: int, |
| jpeg_quality: int, |
| image_detail: str, |
| ) -> List[Dict[str, Any]]: |
| question = get_item_question(item, default_task_type=task_type) |
| frame_groups = [ |
| sample_video_frames_as_data_urls( |
| video_path=video_path, |
| fps=fps, |
| max_frames=max_frames, |
| max_image_side=max_image_side, |
| jpeg_quality=jpeg_quality, |
| ) |
| for video_path in video_paths |
| ] |
|
|
| parts: List[Dict[str, Any]] = [] |
| if task_type == 1: |
| for data_url in frame_groups[0]: |
| parts.append(image_part(data_url, image_detail)) |
| parts.append({"type": "text", "text": question}) |
| return parts |
|
|
| if task_type == 2: |
| if len(frame_groups) != 2: |
| raise ValueError(f"Task 2 expects exactly two videos, got {len(frame_groups)}.") |
| parts.append({"type": "text", "text": "Video A:\n"}) |
| for data_url in frame_groups[0]: |
| parts.append(image_part(data_url, image_detail)) |
| parts.append({"type": "text", "text": "\nVideo B:\n"}) |
| for data_url in frame_groups[1]: |
| parts.append(image_part(data_url, image_detail)) |
| parts.append({"type": "text", "text": f"\n{question}"}) |
| return parts |
|
|
| if task_type == 3: |
| for data_url in frame_groups[0]: |
| parts.append(image_part(data_url, image_detail)) |
| parts.append({"type": "text", "text": question}) |
| return parts |
|
|
| raise ValueError(f"Unsupported task_type: {task_type}") |
|
|
|
|
| def load_completed_results(output_file: str | Path) -> Dict[str, Dict[str, Any]]: |
| if not Path(output_file).exists(): |
| return {} |
| completed = {} |
| for item in load_jsonl(output_file): |
| completed[build_item_key(item)] = item |
| return completed |
|
|
|
|
| def infer_one_item( |
| item: Dict[str, Any], |
| task_type: int, |
| video_root: Optional[str | Path], |
| client: OpenAICompatibleClient, |
| args: argparse.Namespace, |
| ) -> Dict[str, Any]: |
| result_item = dict(item) |
| item_task_type = int(item.get("task_type", task_type)) |
| try: |
| video_paths = resolve_item_video_paths(item, video_root) |
| content = build_vision_content( |
| item=item, |
| video_paths=video_paths, |
| task_type=item_task_type, |
| fps=args.fps, |
| max_frames=args.max_frames, |
| max_image_side=args.max_image_side, |
| jpeg_quality=args.jpeg_quality, |
| image_detail=args.image_detail, |
| ) |
| response = client.generate( |
| content=content, |
| max_tokens=args.max_tokens, |
| temperature=args.temperature, |
| max_retries=args.max_retries, |
| retry_interval=args.retry_interval, |
| ) |
| result_item["model_response"] = response |
| except Exception: |
| result_item["model_response"] = None |
| result_item["infer_error"] = traceback.format_exc() |
|
|
| result_item["eval_info"] = { |
| "model": args.model, |
| "fps": args.fps, |
| "max_frames": args.max_frames, |
| "max_image_side": args.max_image_side, |
| "temperature": args.temperature, |
| } |
| return result_item |
|
|
|
|
| def run_inference(args: argparse.Namespace) -> None: |
| data = load_jsonl(args.task_file) |
| completed = load_completed_results(args.output) |
| pending = [item for item in data if build_item_key(item) not in completed] |
|
|
| if not pending: |
| print(f"All samples already completed in {args.output}.") |
| return |
|
|
| client = OpenAICompatibleClient( |
| model=args.model, |
| api_key=args.api_key, |
| base_url=args.base_url, |
| timeout=args.timeout, |
| ) |
| write_lock = threading.Lock() |
|
|
| workers = max(1, min(args.workers, len(pending))) |
| with ThreadPoolExecutor(max_workers=workers) as executor: |
| futures = [ |
| executor.submit(infer_one_item, item, args.task_type, args.video_root, client, args) |
| for item in pending |
| ] |
| for future in tqdm(as_completed(futures), total=len(futures), desc="Calling API"): |
| result_item = future.result() |
| with write_lock: |
| append_jsonl(result_item, args.output) |
|
|
| print( |
| f"Finish inference. skipped={len(completed)}, newly_processed={len(pending)}, " |
| f"output={args.output}" |
| ) |
|
|
|
|
| def strip_think_blocks(text: str) -> str: |
| return re.sub(r"<think>.*?</think>", "", text, flags=re.IGNORECASE | re.DOTALL) |
|
|
|
|
| def normalize_task1_answer(text: str) -> str: |
| if not text: |
| return "Invalid" |
| text = strip_think_blocks(text).strip() |
| if text.lower() == "invalid": |
| return "Invalid" |
| matches = re.findall(r"\b(yes|no)\b", text, flags=re.IGNORECASE) |
| if not matches: |
| return "Invalid" |
| return matches[-1].lower() |
|
|
|
|
| def normalize_task2_answer(text: str) -> str: |
| if not text: |
| return "Invalid" |
| text = strip_think_blocks(text).strip() |
| if text.lower() == "invalid": |
| return "Invalid" |
| matches = list( |
| re.finditer(r"<\s*Video\s*([AB])\s*>|\bVideo\s*([AB])\b", text, flags=re.IGNORECASE) |
| ) |
| if not matches: |
| return "Invalid" |
| letter = (matches[-1].group(1) or matches[-1].group(2)).upper() |
| return f"<Video {letter}>" |
|
|
|
|
| def normalize_letters(text: str) -> str: |
| if not text: |
| return "Invalid" |
| text = strip_think_blocks(text).strip() |
| if text.lower() == "invalid": |
| return "Invalid" |
| letters = re.findall(r"[A-Z]", text.upper()) |
| if not letters: |
| return "Invalid" |
| deduped = [] |
| for letter in letters: |
| if letter not in deduped: |
| deduped.append(letter) |
| return ",".join(deduped) |
|
|
|
|
| def parse_task3_locally(text: str) -> str: |
| if not text: |
| return "Invalid" |
| cleaned = strip_think_blocks(text).strip() |
| if cleaned.lower() == "invalid": |
| return "Invalid" |
|
|
| lines = [line.strip() for line in cleaned.splitlines() if line.strip()] |
| for line in reversed(lines[-8:]): |
| exact = re.fullmatch(r"[A-Z](?:\s*,\s*[A-Z])*\s*\.?", line.upper()) |
| if exact: |
| return normalize_letters(line.rstrip(".")) |
| keyword = re.search( |
| r"(?:final answer|answer|selected options?|therefore)\s*[:\-]?\s*" |
| r"([A-Z](?:\s*,\s*[A-Z])*)", |
| line, |
| flags=re.IGNORECASE, |
| ) |
| if keyword: |
| return normalize_letters(keyword.group(1)) |
| return "Invalid" |
|
|
|
|
| def parse_response_locally(task_type: int, response: str) -> str: |
| if task_type == 1: |
| return normalize_task1_answer(response) |
| if task_type == 2: |
| return normalize_task2_answer(response) |
| if task_type == 3: |
| return parse_task3_locally(response) |
| raise ValueError(f"Unsupported task_type: {task_type}") |
|
|
|
|
| def parse_response_with_api( |
| task_type: int, |
| response: str, |
| client: OpenAICompatibleClient, |
| args: argparse.Namespace, |
| ) -> str: |
| prompt = PARSE_PROMPTS[task_type].format(Response=response or "") |
| parse_response = client.generate( |
| content=prompt, |
| max_tokens=args.parse_max_tokens, |
| temperature=args.parse_temperature, |
| max_retries=args.max_retries, |
| retry_interval=args.retry_interval, |
| ) |
| if task_type == 1: |
| return normalize_task1_answer(parse_response) |
| if task_type == 2: |
| return normalize_task2_answer(parse_response) |
| if task_type == 3: |
| return parse_task3_locally(parse_response) |
| raise ValueError(f"Unsupported task_type: {task_type}") |
|
|
|
|
| def clean_inference_data(data: Sequence[Dict[str, Any]]) -> List[Dict[str, Any]]: |
| cleaned = [] |
| seen = set() |
| for item in data: |
| if item.get("infer_error") or not item.get("model_response"): |
| continue |
| key = build_item_key(item) |
| if key in seen: |
| continue |
| seen.add(key) |
| cleaned.append(item) |
| return cleaned |
|
|
|
|
| def parse_results(args: argparse.Namespace) -> None: |
| data = clean_inference_data(load_jsonl(args.input)) |
| client = None |
| if args.parser == "api": |
| parser_model = args.parse_model or args.model |
| if not parser_model: |
| raise ValueError("Pass --model or --parse-model when using --parser api.") |
| client = OpenAICompatibleClient( |
| model=parser_model, |
| api_key=args.api_key, |
| base_url=args.base_url, |
| timeout=args.timeout, |
| ) |
|
|
| parsed_data = [] |
| for item in tqdm(data, desc="Parsing"): |
| new_item = dict(item) |
| try: |
| if args.parser == "api": |
| assert client is not None |
| new_item["parse_response"] = parse_response_with_api( |
| task_type=args.task_type, |
| response=item.get("model_response", ""), |
| client=client, |
| args=args, |
| ) |
| else: |
| new_item["parse_response"] = parse_response_locally( |
| args.task_type, |
| item.get("model_response", ""), |
| ) |
| except Exception: |
| new_item["parse_response"] = "Parse Error" |
| new_item["parse_error"] = traceback.format_exc() |
| parsed_data.append(new_item) |
|
|
| save_jsonl(parsed_data, args.output) |
| print(f"Finish parsing. input={args.input}, output={args.output}, samples={len(parsed_data)}") |
|
|
|
|
| def answer_letter_set(text: str) -> set[str]: |
| if not text or text.lower().startswith("invalid"): |
| return set() |
| return set(re.findall(r"[A-Z]", text.upper())) |
|
|
|
|
| def is_correct_answer(item: Dict[str, Any], task_type: int) -> bool: |
| pred = item.get("parse_response", "") |
| answer = item.get("answer", "") |
| if task_type == 1: |
| return normalize_task1_answer(pred) == answer.lower() |
| if task_type == 2: |
| return normalize_task2_answer(pred).lower() == answer.lower() |
| if task_type == 3: |
| return answer_letter_set(pred) == answer_letter_set(answer) |
| raise ValueError(f"Unsupported task_type: {task_type}") |
|
|
|
|
| def load_level_info( |
| meta_file: Optional[str | Path], |
| parsed_data: Sequence[Dict[str, Any]], |
| ) -> Tuple[Dict[str, Any], Dict[str, int]]: |
| source_data = load_jsonl(meta_file) if meta_file else list(parsed_data) |
| level_by_sample_id = {} |
| actual_level_total: Dict[str, int] = {} |
| for item in source_data: |
| level = item.get("level", "unknown") or "unknown" |
| sample_id = str(item["sample_id"]) |
| level_by_sample_id[sample_id] = level |
| actual_level_total[level] = actual_level_total.get(level, 0) + 1 |
| return level_by_sample_id, actual_level_total |
|
|
|
|
| def get_level_stats( |
| data: Sequence[Dict[str, Any]], |
| task_type: int, |
| level_by_sample_id: Dict[str, Any], |
| actual_level_total: Dict[str, int], |
| ) -> Dict[str, Dict[str, Any]]: |
| level_stats = { |
| level: {"correct_num": 0, "total": 0, "actual_total": actual_total} |
| for level, actual_total in actual_level_total.items() |
| } |
|
|
| for item in data: |
| sample_id = str(item["sample_id"]) |
| level = item.get("level") or level_by_sample_id.get(sample_id, "unknown") |
| if level not in level_stats: |
| level_stats[level] = {"correct_num": 0, "total": 0, "actual_total": 0} |
| level_stats[level]["total"] += 1 |
| if is_correct_answer(item, task_type): |
| level_stats[level]["correct_num"] += 1 |
|
|
| for level_result in level_stats.values(): |
| total = level_result["total"] |
| level_result["accuracy"] = level_result["correct_num"] / total if total > 0 else 0.0 |
| return level_stats |
|
|
|
|
| def print_accuracy_table( |
| input_file: str | Path, |
| task_type: int, |
| result: Dict[str, Any], |
| actual_level_total: Dict[str, int], |
| ) -> None: |
| model_name = Path(input_file).stem |
| level_names = list(actual_level_total.keys()) or ["unknown"] |
| model_name_width = max(len("Model"), len(model_name)) |
| level_width = max(len("Level"), len("all"), *(len(str(level)) for level in level_names)) |
| table_width = model_name_width + level_width + 61 |
|
|
| print(f"\n{'=' * table_width}") |
| print(f"Task: task_{task_type}") |
| print(f"{'-' * table_width}") |
| print( |
| f"{'Model':<{model_name_width}} {'Level':<{level_width}} " |
| f"{'Accuracy':>10} {'Correct':>10} {'Total':>6} {'Actual Total':>12}" |
| ) |
| print(f"{'-' * table_width}") |
| print( |
| f"{model_name:<{model_name_width}} {'all':<{level_width}} " |
| f"{result['accuracy'] * 100:>9.2f}% {result['correct_num']:>10} " |
| f"{result['total']:>6} {result['actual_total']:>12}" |
| ) |
| for level, level_result in result["level_stats"].items(): |
| print( |
| f"{'':<{model_name_width}} {level:<{level_width}} " |
| f"{level_result['accuracy'] * 100:>9.2f}% " |
| f"{level_result['correct_num']:>10} {level_result['total']:>6} " |
| f"{level_result['actual_total']:>12}" |
| ) |
| print(f"{'=' * table_width}\n") |
|
|
|
|
| def calculate_accuracy(args: argparse.Namespace) -> Dict[str, Any]: |
| data = load_jsonl(args.input) |
| level_by_sample_id, actual_level_total = load_level_info(args.meta_file, data) |
| total = len(data) |
| correct = sum(1 for item in data if is_correct_answer(item, args.task_type)) |
| result = { |
| "accuracy": correct / total if total > 0 else 0.0, |
| "total": total, |
| "correct_num": correct, |
| "actual_total": len(level_by_sample_id), |
| "level_stats": get_level_stats( |
| data=data, |
| task_type=args.task_type, |
| level_by_sample_id=level_by_sample_id, |
| actual_level_total=actual_level_total, |
| ), |
| } |
| output = args.output or str(Path(args.input).with_name("accuracy.json")) |
| save_json({Path(args.input).stem: result}, output) |
| print_accuracy_table(args.input, args.task_type, result, actual_level_total) |
| print(f"Accuracy saved to {output}") |
| return result |
|
|
|
|
| def run_eval_task(args: argparse.Namespace) -> None: |
| run_inference(args) |
| parse_args = argparse.Namespace(**vars(args)) |
| parse_args.input = args.output |
| parse_args.output = args.parsed_output |
| parse_results(parse_args) |
| accuracy_args = argparse.Namespace( |
| input=args.parsed_output, |
| task_type=args.task_type, |
| meta_file=args.meta_file or args.task_file, |
| output=args.accuracy_output, |
| ) |
| calculate_accuracy(accuracy_args) |
|
|
|
|
| def add_api_args(parser: argparse.ArgumentParser) -> None: |
| parser.add_argument("--api-key", default=None, help="API key. Defaults to REALVIDEO_API_KEY or OPENAI_API_KEY.") |
| parser.add_argument("--base-url", default=None, help="OpenAI-compatible base URL. Defaults to REALVIDEO_BASE_URL or OPENAI_BASE_URL.") |
| parser.add_argument("--model", default=None, help="Model name for inference or parsing.") |
| parser.add_argument("--timeout", type=float, default=300.0) |
| parser.add_argument("--max-retries", type=int, default=5) |
| parser.add_argument("--retry-interval", type=float, default=2.0) |
|
|
|
|
| def add_infer_args(parser: argparse.ArgumentParser) -> None: |
| add_api_args(parser) |
| parser.add_argument("--task-file", required=True) |
| parser.add_argument("--task-type", type=int, choices=[1, 2, 3], required=True) |
| parser.add_argument("--video-root", default=None, help="Root used to resolve relative video paths.") |
| parser.add_argument("--output", required=True) |
| parser.add_argument("--fps", type=float, default=5.0) |
| parser.add_argument("--max-frames", type=int, default=64) |
| parser.add_argument("--max-image-side", type=int, default=1024) |
| parser.add_argument("--jpeg-quality", type=int, default=90) |
| parser.add_argument("--image-detail", default="high", choices=["low", "high", "auto", ""]) |
| parser.add_argument("--workers", type=int, default=4) |
| parser.add_argument("--temperature", type=float, default=0.0) |
| parser.add_argument("--max-tokens", type=int, default=8192) |
|
|
|
|
| def add_parse_args(parser: argparse.ArgumentParser) -> None: |
| add_api_args(parser) |
| parser.add_argument("--input", required=True) |
| parser.add_argument("--task-type", type=int, choices=[1, 2, 3], required=True) |
| parser.add_argument("--output", required=True) |
| parser.add_argument("--parser", choices=["api", "local"], default="api") |
| parser.add_argument("--parse-model", default=None, help="Optional model for API-based parsing. Defaults to --model.") |
| parser.add_argument("--parse-temperature", type=float, default=0.0) |
| parser.add_argument("--parse-max-tokens", type=int, default=64) |
|
|
|
|
| def build_arg_parser() -> argparse.ArgumentParser: |
| parser = argparse.ArgumentParser(description="Public RealVideo-Bench eval script.") |
| subparsers = parser.add_subparsers(dest="command", required=True) |
|
|
| build_meta_parser = subparsers.add_parser("build-meta", help="Build task meta jsonl files.") |
| build_meta_parser.add_argument("--dataset-root", required=True) |
| build_meta_parser.add_argument("--output-dir", default="task") |
| build_meta_parser.add_argument("--tasks", type=int, nargs="+", choices=[1, 2, 3], default=[1, 2, 3]) |
| build_meta_parser.add_argument("--seed", type=int, default=42) |
| build_meta_parser.add_argument("--absolute-video-paths", action="store_true") |
| build_meta_parser.add_argument("--no-add-level", dest="add_level", action="store_false") |
| build_meta_parser.set_defaults(add_level=True, func=build_meta_files) |
|
|
| infer_parser = subparsers.add_parser("infer", help="Run model inference.") |
| add_infer_args(infer_parser) |
| infer_parser.set_defaults(func=run_inference) |
|
|
| parse_parser = subparsers.add_parser("parse", help="Parse raw model responses.") |
| add_parse_args(parse_parser) |
| parse_parser.set_defaults(func=parse_results) |
|
|
| accuracy_parser = subparsers.add_parser("accuracy", help="Calculate accuracy.") |
| accuracy_parser.add_argument("--input", required=True) |
| accuracy_parser.add_argument("--task-type", type=int, choices=[1, 2, 3], required=True) |
| accuracy_parser.add_argument("--meta-file", default=None) |
| accuracy_parser.add_argument("--output", default=None) |
| accuracy_parser.set_defaults(func=calculate_accuracy) |
|
|
| eval_parser = subparsers.add_parser("eval-task", help="Run inference, parsing, and accuracy for one task.") |
| add_infer_args(eval_parser) |
| eval_parser.add_argument("--parser", choices=["api", "local"], default="api") |
| eval_parser.add_argument("--parse-model", default=None) |
| eval_parser.add_argument("--parse-temperature", type=float, default=0.0) |
| eval_parser.add_argument("--parse-max-tokens", type=int, default=64) |
| eval_parser.add_argument("--parsed-output", required=True) |
| eval_parser.add_argument("--accuracy-output", default=None) |
| eval_parser.add_argument("--meta-file", default=None) |
| eval_parser.set_defaults(func=run_eval_task) |
|
|
| return parser |
|
|
|
|
| def main() -> None: |
| parser = build_arg_parser() |
| args = parser.parse_args() |
| if hasattr(args, "model") and not args.model and args.command in {"infer", "eval-task"}: |
| parser.error("--model is required for inference.") |
| args.func(args) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|