# SPDX-License-Identifier: Apache-2.0 """Image / video-frame preprocessing, bit-exact with transformers ``Gemma4ImageProcessor`` (torchvision backend) and ``EmbeddingGemma2VideoProcessor``: RGB uint8 -> aspect-ratio-preserving bicubic antialiased resize (torch ``interpolate`` on uint8, the path torchvision takes on CPU) -> * 1/255 -> 16x16 patches in (py, px, c) order with (x, y) patch positions. Padding to ``max_patches`` is left to the caller (the device buckets by real patch count).""" from __future__ import annotations import math from dataclasses import dataclass from typing import Tuple import numpy as np from .. import model_spec as S def target_size(height: int, width: int, max_soft_tokens: int, patch: int = S.V_PATCH, k: int = S.V_POOL ) -> Tuple[int, int]: """``get_aspect_ratio_preserving_size`` (largest size with <= max_soft_tokens * k^2 patches, sides % (k*patch)).""" max_patches = max_soft_tokens * k * k target_px = max_patches * patch * patch factor = math.sqrt(target_px / (height * width)) side = k * patch th = int(math.floor(factor * height / side)) * side tw = int(math.floor(factor * width / side)) * side if th == 0 and tw == 0: raise ValueError("image too small / degenerate aspect ratio for the patch budget") max_side = (max_patches // (k * k)) * side if th == 0: th = side tw = min(int(math.floor(width / height)) * side, max_side) elif tw == 0: tw = side th = min(int(math.floor(height / width)) * side, max_side) if th * tw > target_px: raise ValueError(f"resize {height}x{width} -> {th}x{tw} exceeds {max_patches} patches") return th, tw @dataclass class Patches: pixels: np.ndarray # [P, 768] float32 in [0, 1], (py, px, c) inner order positions: np.ndarray # [P, 2] int32 (x, y) grid: Tuple[int, int] # (patch rows, patch cols) n_tokens: int # soft tokens = P / 9 @property def n_patches(self) -> int: return int(self.pixels.shape[0]) def to_rgb_pil(img): """PIL image -> RGB PIL image, transparency composited onto WHITE: transformers' ``convert_to_rgb`` (the official processor's ``do_convert_rgb``): RGBA / LA / PA and palette / L / RGB images with a ``transparency`` entry go through RGBA + ``alpha_composite`` on an opaque white background; other modes ``convert("RGB")``.""" from PIL import Image if img.mode == "RGB": return img if "A" in img.getbands() or img.info.get("transparency") is not None: rgba = img.convert("RGBA") white = Image.new("RGBA", rgba.size, (255, 255, 255, 255)) return Image.alpha_composite(white, rgba).convert("RGB") return img.convert("RGB") def composite_rgba_array(a: "np.ndarray") -> "np.ndarray": """HxWx4 array (uint8, or float in [0, 1]) -> HxWx3 of the same dtype, alpha composited onto white exactly as the official torchvision backend does for array / tensor inputs (float32: rgb * a + (1 - a); back to uint8 with torchvision's ``to_dtype`` scaling, x * 255.999 truncated).""" import torch t = torch.from_numpy(np.ascontiguousarray(a)) if t.dtype == torch.uint8: f = t.to(torch.float32).mul_(1.0 / 255) else: f = t.to(torch.float32) if float(f.min()) < 0.0 or float(f.max()) > 1.0: raise ValueError("a float RGBA image must be in [0, 1]") f = f[..., :3] * f[..., 3:] + (1 - f[..., 3:]) if t.dtype == torch.uint8: return f.mul(255 + 1.0 - 1e-3).to(torch.uint8).numpy() return f.numpy().astype(a.dtype) def to_uint8_chw(img) -> "np.ndarray": """PIL image or HxWx3 / HxWx4 / HxW array -> [3, H, W] uint8 (RGB conversion like ``do_convert_rgb``: transparency is composited onto white, see ``to_rgb_pil`` / ``composite_rgba_array``).""" if hasattr(img, "convert"): img = np.asarray(to_rgb_pil(img), dtype=np.uint8) a = np.asarray(img) if a.ndim == 2: a = np.stack([a] * 3, axis=-1) if a.ndim != 3: raise ValueError(f"image array must be HxWx3, got {a.shape}") if a.shape[-1] == 4: a = composite_rgba_array(a) if a.shape[-1] != 3: raise ValueError(f"image array must have 3 channels, got {a.shape}") if a.dtype != np.uint8: if np.issubdtype(a.dtype, np.floating) and a.max() <= 1.0: a = np.round(a * 255.0) a = np.clip(a, 0, 255).astype(np.uint8) return np.ascontiguousarray(a.transpose(2, 0, 1)) def resize_uint8(chw: np.ndarray, h: int, w: int) -> np.ndarray: """[C, H, W] uint8 -> [C, h, w] uint8, bicubic antialias (torch native uint8 kernel, as torchvision on CPU).""" import torch import torch.nn.functional as F if chw.shape[1:] == (h, w): return chw t = torch.from_numpy(chw)[None] # channels_last restride like torchvision (output memory format only; values identical) out = F.interpolate(t, size=[h, w], mode="bicubic", align_corners=False, antialias=True) return out[0].numpy() def patchify(chw_u8: np.ndarray, max_soft_tokens: int) -> Patches: _, H, W = chw_u8.shape th, tw = target_size(H, W, max_soft_tokens) img = resize_uint8(chw_u8, th, tw).astype(np.float32) * np.float32(0.00392156862745098) p = S.V_PATCH nh, nw = th // p, tw // p x = img.reshape(3, nh, p, nw, p).transpose(1, 3, 2, 4, 0).reshape(nh * nw, p * p * 3) gx, gy = np.meshgrid(np.arange(nw), np.arange(nh), indexing="xy") pos = np.stack([gx, gy], axis=-1).reshape(nh * nw, 2).astype(np.int32) return Patches(np.ascontiguousarray(x, dtype=np.float32), pos, (nh, nw), (nh * nw) // (S.V_POOL ** 2)) def preprocess_image(img, max_soft_tokens: int = S.V_DEFAULT_IMAGE_TOKENS) -> Patches: if max_soft_tokens not in S.V_SOFT_TOKENS: raise ValueError(f"max_soft_tokens must be one of {S.V_SOFT_TOKENS}") return patchify(to_uint8_chw(img), max_soft_tokens) def pool_order(positions: np.ndarray) -> np.ndarray: """Output slot of every patch for the 3x3 pooler: kx + (W/3) * ky (row-major over pooled cells).""" k = S.V_POOL max_x = int(positions[:, 0].max()) + 1 return (positions[:, 0] // k + (max_x // k) * (positions[:, 1] // k)).astype(np.int64)