import math import numpy as np import torch from transformers.video_utils import VideoMetadata from videojev_hf.videojev_temporal import pair_timeline NATIVE_ALIGNMENT = 32 NATIVE_QUERY_CONTEXT = 32768 class LegacyProcessorAdapter: """Expose the prompt helpers using native Transformers 5.6.2 formatting.""" def __init__(self, processor): self.processor = processor def __getattr__(self, name): return getattr(self.processor, name) def __call__(self, *args, **kwargs): return self.processor(*args, **kwargs) def replace_video_token(self, video_inputs, *, video_idx): grid = video_inputs['video_grid_thw'][video_idx] metadata = video_inputs['video_metadata'][video_idx] timestamps = self._calculate_timestamps( list(metadata.frames_indices), metadata.fps, self.video_processor.temporal_patch_size) spatial = int(np.prod(grid[1:])) // self.video_processor.merge_size**2 return ''.join( f'<{timestamp:.1f} seconds>{self.vision_start_token}' f'{self.video_token * spatial}{self.vision_end_token}' for timestamp in timestamps[:int(grid[0])]) def get_text_with_replacements(self, texts, images, videos, audio): if len(texts) != 1 or len(videos) != 1 or images or audio: raise ValueError('This compatibility adapter supports one video-only prompt') placeholder = self.vision_start_token + self.video_token + self.vision_end_token if placeholder not in texts[0]: placeholder = self.video_token if placeholder not in texts[0]: raise ValueError('No native video placeholder in the prompt') return [texts[0].replace(placeholder, videos[0], 1)], None def encode_screenshot(model, processor, views): count = len(views) if not views or len({view.size for view in views}) != 1: raise ValueError('Native frames must have one matching nonempty canvas size') width, height = views[0].size video_processor = processor.video_processor if (video_processor.patch_size * video_processor.merge_size != NATIVE_ALIGNMENT or width % NATIVE_ALIGNMENT or height % NATIVE_ALIGNMENT): raise ValueError('Native canvases must be padded to the checkpoint\'s 32-pixel alignment') options = dict(do_resize=False, size=dict(shortest_edge=4096, longest_edge=count * width * height)) metadata = VideoMetadata(total_num_frames=count, fps=2., frames_indices=list(range(count))) native = video_processor( videos=[np.stack([np.asarray(view) for view in views])], video_metadata=[metadata], do_sample_frames=False, return_tensors='pt', **options) grid = native['video_grid_thw'][0].tolist() expected = [math.ceil(count / video_processor.temporal_patch_size), height // video_processor.patch_size, width // video_processor.patch_size] if grid != expected: raise ValueError(f'Native full resolution was changed by the processor: {grid} != {expected}') times, bounds = pair_timeline(np.arange(count) / 2., count / 2.) record = dict(frames=count, fps=2., grid_thw=grid, tokens=int(np.prod(grid)) // 4, view_size='native', canvas_size=list(views[0].size), processor_resize=False, context=NATIVE_QUERY_CONTEXT, score_times=times.tolist(), score_bounds=bounds.tolist(), sampled_duration=count / 2.) if record['tokens'] >= record['context']: raise ValueError('Visual tokens leave no room for questions; no automatic downscaling is allowed') features = model.encode_video(native['pixel_values_videos'], torch.tensor([grid])) return features, record