import os import json import argparse from tqdm import tqdm import time from PIL import Image import numpy as np import av import torch from transformers import LlavaNextVideoProcessor, LlavaNextVideoForConditionalGeneration def get_media_type(file_path: str) -> str: ext = os.path.splitext(file_path)[1].lower() if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']: return 'video' elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']: return 'image' else: raise ValueError(f"Unsupported file format: {ext} in file {file_path}") def read_video_pyav(container, indices): frames = [] container.seek(0) start_index = indices[0] end_index = indices[-1] for i, frame in enumerate(container.decode(video=0)): if i > end_index: break if i >= start_index and i in indices: frames.append(frame) if not frames: raise ValueError("Could not decode specified frames from the video.") return np.stack([x.to_ndarray(format="rgb24") for x in frames]) def process_file(dataset_json_path: str, model, processor, result_suffix: str, device: str): json_filename = os.path.basename(dataset_json_path) result_json_path = os.path.join( os.path.dirname(dataset_json_path), f"{os.path.splitext(json_filename)[0]}{result_suffix}" ) if os.path.exists(result_json_path): print(f"[INFO] Result file '{os.path.basename(result_json_path)}' already exists. Skipping.") return try: with open(dataset_json_path, 'r', encoding='utf-8') as f: data = json.load(f) except (json.JSONDecodeError, FileNotFoundError) as e: print(f"Failed to read or parse JSON file {dataset_json_path}: {e}") return all_results = [] base_path = os.path.dirname(dataset_json_path) for item in tqdm(data, desc=f" Inferring on {json_filename}"): start_time = time.time() model_output = "N/A" try: prompt_text = item['conversations'][0]['value'] ground_truth = item['conversations'][1]['value'] media_path_key = 'image' if 'image' in item else 'video' media_relative_path = item.get(media_path_key) if not media_relative_path: raise ValueError("JSON item is missing 'image' or 'video' key.") media_full_path = os.path.join(base_path, media_relative_path) if not os.path.exists(media_full_path): raise FileNotFoundError(f"Media file not found: {media_full_path}") media_type = get_media_type(media_full_path) clean_prompt = prompt_text.replace("", "").replace("