import ast import io import os from copy import deepcopy from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Set, Union import cv2 import numpy as np import pyarrow.parquet as pq import torch from arpeggio import Chord, DataloaderArgs, create_dataloader, register_transform from arpeggio.chord import Chord from arpeggio.tuners import Qwen3VLTransform from arpeggio.utils.conversation_utils import ( chatml_input_ids_to_labels, handle_message_extra_fields, sharegpt_to_hf_format, ) from arpeggio.utils.qwen_vl_utils import get_mrope_index_qwen3_vl from decord import VideoReader, cpu from PIL import Image from qwen_vl_utils import fetch_image, fetch_video, process_vision_info from qwen_vl_utils.vision_process import smart_resize from torchvision import transforms from torchvision.transforms import InterpolationMode from transformers import AutoTokenizer DISABLE_CV2_PATCH = os.getenv("DISABLE_CV2_PATCH", "0") == "1" # ==================== OpenCV Resize Monkey Patch ==================== # Patch PIL.Image.resize to use OpenCV _original_pil_resize = Image.Image.resize _PIL_TO_CV2_INTERP = { Image.Resampling.NEAREST: cv2.INTER_NEAREST, Image.Resampling.BILINEAR: cv2.INTER_LINEAR, Image.Resampling.BICUBIC: cv2.INTER_CUBIC, Image.Resampling.LANCZOS: cv2.INTER_LANCZOS4, # Compat with older PIL versions 0: cv2.INTER_NEAREST, 2: cv2.INTER_LINEAR, 3: cv2.INTER_CUBIC, 1: cv2.INTER_LANCZOS4, } def _cv2_resize(self, size, resample=None, box=None, reducing_gap=None): """OpenCV-accelerated PIL Image.resize().""" # Fall back to original for box parameter (crop + resize) if box is not None: return _original_pil_resize(self, size, resample=resample, box=box, reducing_gap=reducing_gap) if resample is None: resample = Image.Resampling.BICUBIC cv2_interp = _PIL_TO_CV2_INTERP.get(resample, cv2.INTER_LINEAR) target_w, target_h = size # Use INTER_AREA for downsampling (better quality) if target_w < self.width or target_h < self.height: cv2_interp = cv2.INTER_AREA img_array = np.asarray(self) resized = cv2.resize(img_array, (target_w, target_h), interpolation=cv2_interp) return Image.fromarray(resized) def enable_cv2_resize(): """Enable OpenCV-accelerated resize.""" Image.Image.resize = _cv2_resize def disable_cv2_resize(): """Restore original PIL resize.""" Image.Image.resize = _original_pil_resize # Enable by default if not DISABLE_CV2_PATCH: enable_cv2_resize() @dataclass class VideoData: """Processed video data with metadata.""" video: Union[torch.Tensor, List[Image.Image]] # video tensor or PIL frames metadata: dict # contains fps, total_num_frames, frames_indices sample_fps: float class ThothVLTransform(Qwen3VLTransform): """Qwen3-VL transform that supports Thoth/msswift-style data formats. Supports: - content_split: pretrain text data - caption: image captioning data - conversations/messages: multi-turn dialogue - Various image formats: bytes, path, dict, PIL.Image - Various video formats: frames, video bytes, gif - Nested conversations """ # ==================== Image Processing ==================== def _read_image( self, image: Union[bytes, str, Image.Image, dict, None], to_pil: bool = False, ) -> Optional[Image.Image]: """Convert various image formats to PIL Image.""" if image is None: return None if isinstance(image, Image.Image): return image if isinstance(image, bytes): return Image.open(io.BytesIO(image)) if isinstance(image, str): # Path to image - will be handled by fetch_image later return image if isinstance(image, dict): if image.get("bytes") is not None: img_bytes = image["bytes"] if isinstance(img_bytes, Image.Image): return img_bytes return Image.open(io.BytesIO(img_bytes)) elif image.get("path") is not None: return image["path"] return None if isinstance(image, (np.float64, np.float32)): return None raise ValueError(f"Unsupported image type: {type(image)}") def _process_images(self, item: dict) -> Optional[List]: """Extract and process images from item.""" raw_images = None if "jpg" in item: raw_images = [item.pop("jpg")] elif "image" in item: image_data = item.pop("image") if image_data is not None and not isinstance(image_data, (np.float64, np.float32)): raw_images = [image_data] elif "images" in item: raw_images = item.pop("images") if isinstance(raw_images, np.ndarray): raw_images = raw_images.tolist() elif isinstance(raw_images, dict): raw_images = [raw_images] if not raw_images: return None images = [] for raw in raw_images: img = self._read_image(raw, to_pil=True) if img is None: continue if isinstance(img, str): # Path - use fetch_image ele = {"type": "image", "image": img} self._patch_visual_element(ele) img = fetch_image(ele, image_patch_size=self._patch_size) images.append(img) return images if images else None # ==================== Video Processing ==================== def _read_gif(self, gif_bytes: bytes) -> List[Image.Image]: """Extract frames from a GIF.""" if not isinstance(gif_bytes, bytes): raise TypeError(f"Unsupported gif type: {type(gif_bytes)}") frames = [] with io.BytesIO(gif_bytes) as byte_stream: with Image.open(byte_stream) as img: try: while True: frames.append(img.copy()) img.seek(img.tell() + 1) except EOFError: pass return frames def _decode_video_bytes(self, video_bytes: bytes) -> tuple[torch.Tensor, dict, float]: """Decode video from bytes using decord. Returns (video_tensor, metadata, sample_fps) """ vr = VideoReader(io.BytesIO(video_bytes), ctx=cpu(0), num_threads=1) total_frames = len(vr) fps = vr.get_avg_fps() max_num_frames = self._video_ele_kwargs.get("max_frames") or int(os.environ.get("FPS_MAX_FRAMES", 32)) if total_frames <= max_num_frames: indices = list(range(total_frames)) else: indices = np.linspace(0, total_frames - 1, max_num_frames, dtype=int).tolist() # numpy array: [N, H, W, C] frames = vr.get_batch(indices).asnumpy() # [N, C, H, W] video_tensor = torch.from_numpy(frames).permute(0, 3, 1, 2) sample_fps = len(indices) / total_frames * fps if total_frames > 0 else 1.0 metadata = { "fps": fps, "total_num_frames": total_frames, "frames_indices": torch.tensor(indices), } return video_tensor, metadata, sample_fps def _process_videos(self, item: dict) -> Optional[List[VideoData]]: """Extract and process videos from item. Returns a list of VideoData, each containing video tensor/frames and metadata. Supported formats: - frames: List[bytes] - Each bytes is an image (frame) - video: bytes - Raw mp4 video bytes - video: str - Video file path - gif: bytes - GIF animation bytes - videos: List[...] - Multiple videos in various formats """ max_num_frames = int(os.environ.get("FPS_MAX_FRAMES", 16)) raw_videos = None if "frames" in item: raw_frames = item.pop("frames") frames = [] for frame in raw_frames: img = self._read_image(frame) if img is not None and isinstance(img, Image.Image): frames.append(img) if len(frames) > max_num_frames: indices = np.linspace(0, len(frames) - 1, max_num_frames, dtype=int) frames = [frames[i] for i in indices] if frames: raw_videos = [frames] elif "video" in item: raw_videos = [item.pop("video")] elif "gif" in item: raw_videos = [self._read_gif(item.pop("gif"))] elif "videos" in item: raw_videos = item.pop("videos") if isinstance(raw_videos, np.ndarray): raw_videos = raw_videos.tolist() if raw_videos and isinstance(raw_videos[0], np.ndarray): raw_videos = [v.tolist() for v in raw_videos] if not raw_videos: return None results = [] try: for raw in raw_videos: if isinstance(raw, list) and raw and isinstance(raw[0], Image.Image): # List of PIL Images (frames) num_frames = len(raw) metadata = { "fps": 1.0, "total_num_frames": num_frames, "frames_indices": torch.arange(num_frames), } results.append(VideoData(video=raw, metadata=metadata, sample_fps=1.0)) elif isinstance(raw, list) and raw and isinstance(raw[0], bytes): total_frames = len(raw) if total_frames > max_num_frames: indices = np.linspace(0, total_frames - 1, max_num_frames, dtype=int) else: indices = range(total_frames) frames = [] for i in indices: img = self._read_image(raw[i]) if img is not None and isinstance(img, Image.Image): frames.append(img) if frames: num_frames = len(frames) metadata = { "fps": 1.0, "total_num_frames": total_frames, "frames_indices": torch.tensor( list(indices) if total_frames > max_num_frames else list(range(num_frames)) ), } results.append(VideoData(video=frames, metadata=metadata, sample_fps=1.0)) elif isinstance(raw, bytes): # Video bytes - use decord video_tensor, metadata, sample_fps = self._decode_video_bytes(raw) results.append(VideoData(video=video_tensor, metadata=metadata, sample_fps=sample_fps)) elif isinstance(raw, str): # Video file path ele = {"type": "video", "video": raw} self._patch_visual_element(ele) result, sample_fps = fetch_video( ele, image_patch_size=self._patch_size, return_video_sample_fps=True, return_video_metadata=True, ) if isinstance(result, tuple): video_tensor, metadata = result else: video_tensor = result num_frames = video_tensor.shape[0] metadata = { "fps": sample_fps, "total_num_frames": num_frames, "frames_indices": torch.arange(num_frames), } results.append(VideoData(video=video_tensor, metadata=metadata, sample_fps=sample_fps)) elif isinstance(raw, torch.Tensor): num_frames = raw.shape[0] metadata = { "fps": 1.0, "total_num_frames": num_frames, "frames_indices": torch.arange(num_frames), } results.append(VideoData(video=raw, metadata=metadata, sample_fps=1.0)) except Exception as e: print(f"_process_videos error: {e}") raise e return results if results else None # ==================== Conversation Processing ==================== def _normalize_message_format(self, messages: List[Dict]) -> List[Dict]: """Convert from/value format to role/content format and filter system messages. Handles: - from: human/user -> role: user - from: gpt/assistant -> role: assistant - from: system -> filtered out - value -> content - Dirty data fix: if assistant message contains /