import argparse import json import os import re import math from torchvision import io, transforms from torchvision.transforms import InterpolationMode from pathlib import Path import matplotlib.pyplot as plt import numpy as np import torch import torch.nn.functional as F from tqdm import tqdm from transformers import AutoModelForImageTextToText, AutoProcessor try: import cv2 except ImportError: cv2 = None try: from scipy.ndimage import gaussian_filter except ImportError: gaussian_filter = None GENERAL_QUESTION = "Given this AI-generated video, does it successfully the requirement of the prompt: '<|prompt|>'? Respond with 'Yes' or 'No', Answer 'Yes' if the video perfectly matches the description. Answer 'No' if the video clearly contradicts the description. The presence of additional elements in the video is acceptable as long as they do not conflict with the core description. Please provide a brief explanation for your answer. \nProvide your analysis and explanation in JSON with keys: answer (e.g., Yes or No), explanation." def smart_resize(height, width, factor=28, min_pixels=56 * 56, max_pixels=14 * 14 * 4 * 1280): import math if max(height, width) / min(height, width) > 200: raise ValueError(f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}") h_bar = round(height / factor) * factor w_bar = round(width / factor) * factor if h_bar * w_bar > max_pixels: beta = math.sqrt((height * width) / max_pixels) h_bar = max(factor, math.floor(height / beta / factor) * factor) w_bar = max(factor, math.floor(width / beta / factor) * factor) elif h_bar * w_bar < min_pixels: beta = math.sqrt(min_pixels / (height * width)) h_bar = math.ceil(height * beta / factor) * factor w_bar = math.ceil(width * beta / factor) * factor return int(h_bar), int(w_bar) def smart_resize( num_frames: int, height: int, width: int, temporal_factor: int = 2, factor: int = 32, min_pixels: int = 128 * 128, max_pixels: int = 16 * 16 * 2 * 2 * 2 * 6144, ): if height < factor or width < factor: raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}") elif max(height, width) / min(height, width) > 200: raise ValueError( f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}" ) h_bar = round(height / factor) * factor w_bar = round(width / factor) * factor t_bar = math.ceil(num_frames / temporal_factor) * temporal_factor if t_bar * h_bar * w_bar > max_pixels: beta = math.sqrt((num_frames * height * width) / max_pixels) h_bar = max(factor, math.floor(height / beta / factor) * factor) w_bar = max(factor, math.floor(width / beta / factor) * factor) elif t_bar * h_bar * w_bar < min_pixels: beta = math.sqrt(min_pixels / (num_frames * height * width)) h_bar = math.ceil(height * beta / factor) * factor w_bar = math.ceil(width * beta / factor) * factor return h_bar, w_bar def resize_frames(frames, max_frame_pixels): B, C, T, H, W = frames.shape x = frames.permute(0, 2, 1, 3, 4) # [B, T, C, H, W] resized_height, resized_width = smart_resize( T, H, W, factor=32, # image factor min_pixels=16384, # 128*128 max_pixels=max_frame_pixels, ) frames_resized = [] for v in x: v_r = transforms.functional.resize( v, [resized_height, resized_width], interpolation=InterpolationMode.BICUBIC, antialias=True, ).float() frames_resized.append(v_r) frames_resized = torch.stack(frames_resized) return frames_resized def read_video(video_path, num_frames, resize_factor, min_pixels, max_pixels): try: import decord from decord import VideoReader, cpu except ImportError as e: raise ImportError("decord is required for reading videos. Please install decord.") from e decord.bridge.set_bridge("torch") vr = VideoReader(video_path, ctx=cpu(0)) total_frames = len(vr) if total_frames == 0: raise ValueError(f"Empty video: {video_path}") idx = torch.linspace(0, total_frames - 1, num_frames).round().long().tolist() video = vr.get_batch(idx).permute(0, 3, 1, 2).float() / 255.0 _, _, h0, w0 = video.shape video = resize_frames(video.unsqueeze(0), max_pixels).permute(0, 2, 1, 3, 4)[0] # [B, C, T, H, W] -> [B, T, C, H, W] return video def extract_yes_no_from_gt(gt_text): if not gt_text: return None try: obj = json.loads(gt_text) ans = str(obj.get("answer", "")).strip().lower() if ans in {"yes", "no"}: return ans except Exception: pass m = re.search(r'"answer"\s*:\s*"(Yes|No|yes|no)"', gt_text) if m: return m.group(1).lower() return None def token_id_set_for_yes_no(tokenizer, label=None): token_texts = [] if label == "yes": token_texts = ["Yes", "yes", " Yes", " yes"] elif label == "no": token_texts = ["No", "no", " No", " no"] else: token_texts = ["Yes", "yes", " Yes", " yes", "No", "no", " No", " no"] token_ids = set() for t in token_texts: ids = tokenizer.encode(t, add_special_tokens=False) if ids: token_ids.add(ids[0]) return token_ids def get_yes_token_id(tokenizer): for tok in ["Yes", " Yes", "yes", " yes"]: ids = tokenizer.encode(tok, add_special_tokens=False) if ids: return ids[0] raise RuntimeError("Cannot find a valid Yes token id in tokenizer.") def get_no_token_id(tokenizer): for tok in ["No", " No", "no", " no"]: ids = tokenizer.encode(tok, add_special_tokens=False) if ids: return ids[0] raise RuntimeError("Cannot find a valid No token id in tokenizer.") def find_yes_no_index_at_end(input_ids_1d, tokenizer, answer_label=None, search_window=256): seq = input_ids_1d.tolist() if hasattr(input_ids_1d, "tolist") else list(input_ids_1d) im_start_id = tokenizer.convert_tokens_to_ids("<|im_start|>") target_ids = token_id_set_for_yes_no(tokenizer, label=answer_label) # Align with preprocess logic: search backward near the end. start_pos = len(seq) - 1 end_pos = max(0, len(seq) - search_window) for i in range(start_pos, end_pos, -1): token_id = seq[i] if token_id == im_start_id: break if token_id in target_ids: return i return None def infer_token_grid(video_grid_thw, token_count, merge_size): grid_t, grid_h, grid_w = [int(x) for x in video_grid_thw] cands = [] if merge_size > 0 and grid_h % merge_size == 0 and grid_w % merge_size == 0: cands.append((grid_t, grid_h // merge_size, grid_w // merge_size)) cands.append((grid_t, grid_h, grid_w)) for t, h, w in cands: if t * h * w == token_count: return t, h, w raise ValueError( f"Cannot match token_count={token_count} with video_grid={video_grid_thw} and merge_size={merge_size}" ) def plot_smooth_heatmap_with_merge_correction( input_video, video_grid, token_grads, merge_size=2, blur_sigma=5.0, normalization_mode="local", global_scale=1.0, save_path="heatmap_smooth.png" ): """ blur_sigma: 高斯模糊的半径。 如果是一个 float (e.g., 5.0),则在时间、高度、宽度上应用相同的模糊。 如果是一个 tuple (e.g., (1.5, 8.0, 8.0)),则分别对应 (T, H, W) 方向的模糊程度。 """ T_in, C, H_in, W_in = input_video.shape grid_t, grid_h, grid_w = video_grid token_t = grid_t token_h = grid_h // merge_size token_w = grid_w // merge_size assert token_grads.numel() == token_t * token_h * token_w grads = token_grads.detach().cpu().float() if grads.dim() > 1: grads = grads.norm(dim=-1) heatmap_small = grads.view(1, 1, token_t, token_h, token_w) heatmap_upsampled = F.interpolate( heatmap_small, size=(T_in, H_in, W_in), mode='trilinear', align_corners=False ).squeeze() heatmap_np = heatmap_upsampled.numpy() if isinstance(blur_sigma, float) or isinstance(blur_sigma, int): sigma_spatial = blur_sigma sigma_temporal = max(0.5, blur_sigma / 3.0) current_sigma = (sigma_temporal, sigma_spatial, sigma_spatial) else: current_sigma = blur_sigma heatmap_smooth = gaussian_filter(heatmap_np, sigma=current_sigma) if normalization_mode == "local": heatmap_smooth = (heatmap_smooth - heatmap_smooth.min()) / (heatmap_smooth.max() - heatmap_smooth.min() + 1e-8) elif normalization_mode == "global": heatmap_smooth = np.clip(heatmap_smooth / max(float(global_scale), 1e-8), 0.0, 1.0) else: raise ValueError(f"Unsupported normalization_mode: {normalization_mode}") video_np = input_video.permute(0, 2, 3, 1).cpu().numpy() video_np = (video_np - video_np.min()) / (video_np.max() - video_np.min()) fig, axes = plt.subplots(2, T_in, figsize=(T_in * 2, 5)) plt.subplots_adjust(wspace=0.02, hspace=0.02, left=0.01, right=0.99) for t in range(T_in): img = video_np[t] hm = heatmap_smooth[t] ax_top = axes[0, t] ax_top.imshow(img) ax_top.imshow(hm, cmap='jet', alpha=0.5, vmin=0, vmax=1) ax_top.axis('off') ax_bot = axes[1, t] ax_bot.imshow(img) ax_bot.axis('off') if t == 0: ax_top.set_title("Smooth Heatmap", fontsize=10, x=-0.1, y=0.5, rotation=90) ax_bot.set_title("Original", fontsize=10, x=-0.1, y=0.5, rotation=90) ax_bot.text(0.5, -0.05, f"t={t}", transform=ax_bot.transAxes, ha='center', fontsize=8) plt.savefig(save_path, dpi=150, bbox_inches='tight') plt.close() return heatmap_smooth def save_overlay_png(video_uint8, heatmap, out_png): t_num = video_uint8.shape[0] fig, axes = plt.subplots(2, t_num, figsize=(max(10, t_num * 1.8), 4.5)) if t_num == 1: axes = np.array(axes).reshape(2, 1) plt.subplots_adjust(wspace=0.02, hspace=0.02, left=0.01, right=0.99) for t in range(t_num): ax0 = axes[0, t] ax0.imshow(video_uint8[t]) ax0.imshow(heatmap[t], cmap="jet", alpha=0.5, vmin=0, vmax=1) ax0.axis("off") ax1 = axes[1, t] ax1.imshow(video_uint8[t]) ax1.axis("off") ax1.text(0.5, -0.06, f"t={t}", transform=ax1.transAxes, ha="center", fontsize=8) axes[0, 0].set_title("Grad Heatmap", fontsize=10, x=-0.08, y=0.5, rotation=90) axes[1, 0].set_title("Original", fontsize=10, x=-0.08, y=0.5, rotation=90) plt.savefig(out_png, dpi=140, bbox_inches="tight") plt.close() def save_overlay_mp4(video_uint8, heatmap, out_mp4, fps=4): if cv2 is None: return False t_num, h, w, _ = video_uint8.shape writer = cv2.VideoWriter(out_mp4, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h)) for t in range(t_num): hm = plt.get_cmap("jet")(heatmap[t])[..., :3] frame = (0.5 * (video_uint8[t] / 255.0) + 0.5 * hm) * 255.0 frame = frame.astype(np.uint8) writer.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)) writer.release() return True def save_frame_images(video_uint8, heatmap, out_dir): out_dir = Path(out_dir) overlay_dir = out_dir / "frames_overlay" original_dir = out_dir / "frames_original" overlay_dir.mkdir(parents=True, exist_ok=True) original_dir.mkdir(parents=True, exist_ok=True) heatmap_np = heatmap if isinstance(heatmap, np.ndarray) else np.asarray(heatmap) t_num = video_uint8.shape[0] for t in range(t_num): hm_rgb = plt.get_cmap("jet")(heatmap_np[t])[..., :3] overlay = (0.5 * (video_uint8[t].astype(np.float32) / 255.0) + 0.5 * hm_rgb) * 255.0 overlay = np.clip(overlay, 0, 255).astype(np.uint8) if cv2 is not None: cv2.imwrite(str(overlay_dir / f"frame_{t:03d}.png"), cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR)) cv2.imwrite(str(original_dir / f"frame_{t:03d}.png"), cv2.cvtColor(video_uint8[t], cv2.COLOR_RGB2BGR)) else: plt.imsave(str(overlay_dir / f"frame_{t:03d}.png"), overlay) plt.imsave(str(original_dir / f"frame_{t:03d}.png"), video_uint8[t]) return str(overlay_dir), str(original_dir), t_num def build_messages(question): return [ { "role": "user", "content": [ {"type": "video", "video": "