# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # This file was automatically generated from src/transformers/models/deepseek_ocr2/modular_deepseek_ocr2.py. # Do NOT edit this file manually as any edits will be overwritten by the generation of # the file from the modular. If any change should be done, please apply the change to the # modular_deepseek_ocr2.py file directly. One of our CI enforces this. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 # Copyright 2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from functools import lru_cache import torch from torchvision.transforms.v2 import functional as tvF from ...image_processing_backends import TorchvisionBackend from ...image_processing_utils import BatchFeature from ...image_transforms import group_images_by_shape, reorder_images from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, PILImageResampling, SizeDict from ...processing_utils import ImagesKwargs, Unpack from ...utils import TensorType, auto_docstring class DeepseekOcr2ImageProcessorKwargs(ImagesKwargs, total=False): r""" crop_to_patches (`bool`, *optional*, defaults to `self.crop_to_patches`): Whether to crop the image to patches. Can be overridden by the `crop_to_patches` parameter in the `preprocess` method. min_patches (`int`, *optional*, defaults to `self.min_patches`): The minimum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is set to `True`. Can be overridden by the `min_patches` parameter in the `preprocess` method. max_patches (`int`, *optional*, defaults to `self.max_patches`): The maximum number of patches to be extracted from the image. Only has an effect if `crop_to_patches` is set to `True`. Can be overridden by the `max_patches` parameter in the `preprocess` method. tile_size (`int`, *optional*, defaults to `768`): The size of each local tile. Must match the model's query embedding size. background_color (`list[int]`, *optional*, defaults to `[127, 127, 127]`): The background color for padding. """ crop_to_patches: bool min_patches: int max_patches: int tile_size: int background_color: list[int] @lru_cache(maxsize=10) def get_all_supported_aspect_ratios(min_image_tiles: int, max_image_tiles: int) -> list[tuple[int, int]]: """ Computes all allowed aspect ratios for a given minimum and maximum number of input tiles. This function calculates all possible arrangements of tiles that can be formed within the constraint of the minimum and maximum number of tiles. Each arrangement is represented by its aspect ratio (width/height) and the corresponding tile configuration. Args: min_image_tiles (`int`): The minimum number of tiles allowed. max_image_tiles (`int`): The maximum number of tiles allowed. Returns: `list[tuple[int, int]]`: A list of tuples, each tuple representing a valid (width, height) configuration in terms of number of tiles. Example: >>> get_all_supported_aspect_ratios(1, 4) [(1, 1), (1, 2), (2, 1), (1, 3), (3, 1), (1, 4), (2, 2), (4, 1)] """ aspect_ratios = [] for width in range(1, max_image_tiles + 1): for height in range(1, max_image_tiles + 1): if width * height <= max_image_tiles and width * height >= min_image_tiles: aspect_ratios.append((width, height)) aspect_ratios = sorted(aspect_ratios, key=lambda x: x[0] * x[1]) return aspect_ratios @lru_cache(maxsize=100) def get_optimal_tiled_canvas( original_image_size: tuple[int, int], target_tile_size: tuple[int, int], min_image_tiles: int, max_image_tiles: int, ) -> tuple[int, int]: """ Given a minimum and maximum number of tiles, find the canvas with the closest aspect ratio to the original image aspect ratio. In case of tie-breaking condition when two canvases have the same aspect ratio difference, we favor the canvas with more tiles, until the area covered by the tiles is more than twice the target area, in order to avoid unnecessarily excessive tiling. """ possible_tile_arrangements = get_all_supported_aspect_ratios(min_image_tiles, max_image_tiles) original_height, original_width = original_image_size target_tile_height, target_tile_width = target_tile_size aspect_ratio = original_width / original_height area = original_width * original_height # find the grid with the best aspect ratio best_ratio_diff = float("inf") best_grid = (1, 1) for grid in possible_tile_arrangements: grid_aspect_ratio = grid[0] / grid[1] ratio_diff = abs(aspect_ratio - grid_aspect_ratio) if ratio_diff < best_ratio_diff: best_ratio_diff = ratio_diff best_grid = grid elif ratio_diff == best_ratio_diff: # if the aspect ratio difference is the same, we favor the grid with more patches # until the area covered by the patches is more than twice the original image area if area > 0.5 * target_tile_height * target_tile_width * grid[0] * grid[1]: best_grid = grid return best_grid @auto_docstring class DeepseekOcr2ImageProcessor(TorchvisionBackend): valid_kwargs = DeepseekOcr2ImageProcessorKwargs resample = PILImageResampling.BICUBIC image_mean = IMAGENET_STANDARD_MEAN image_std = IMAGENET_STANDARD_STD size = {"height": 1024, "width": 1024} do_resize = True do_rescale = True do_normalize = True do_convert_rgb = True crop_to_patches = True min_patches = 2 max_patches = 6 tile_size = 768 background_color = [127, 127, 127] model_input_names = ["pixel_values", "num_local_patches"] def __init__(self, **kwargs: Unpack[DeepseekOcr2ImageProcessorKwargs]): super().__init__(**kwargs) def crop_image_to_patches( self, images: "torch.Tensor", min_patches: int, max_patches: int, tile_size: int, resample: PILImageResampling | None = None, ) -> tuple["torch.Tensor", int]: """ Crop batched images to patches based on optimal tiling. Args: images (`torch.Tensor`): The images to crop, shape `(batch, channels, height, width)`. min_patches (`int`): Minimum number of patches. max_patches (`int`): Maximum number of patches. tile_size (`int`): The size of each tile. resample (`PILImageResampling`, *optional*): Resampling filter for resizing. Returns: `tuple[torch.Tensor, int]`: Stacked patches `(batch, num_patches, channels, tile_size, tile_size)` and number of patches per image. """ original_height, original_width = images.shape[-2:] num_columns, num_rows = get_optimal_tiled_canvas( (original_height, original_width), (tile_size, tile_size), min_patches, max_patches ) target_width = tile_size * num_columns target_height = tile_size * num_rows num_blocks = num_columns * num_rows resized = self.resize(images, SizeDict(height=target_height, width=target_width), resample=resample) patches = [] for i in range(num_blocks): col = i % num_columns row = i // num_columns patch = resized[ ..., row * tile_size : (row + 1) * tile_size, col * tile_size : (col + 1) * tile_size, ] patches.append(patch) stacked_patches = torch.stack(patches, dim=1) return stacked_patches, num_blocks def _preprocess( self, images: list["torch.Tensor"], size: SizeDict, crop_to_patches: bool, min_patches: int, max_patches: int, tile_size: int, resample: PILImageResampling | None, do_rescale: bool, rescale_factor: float, do_normalize: bool, image_mean: float | list[float] | None, image_std: float | list[float] | None, disable_grouping: bool | None, return_tensors: str | TensorType | None, **kwargs, ) -> BatchFeature: # --- Local patches (batched by shape group) --- num_local_patches = {} local_patches_grouped = {} if crop_to_patches: grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) for key, stacked_images in grouped_images.items(): h, w = stacked_images.shape[-2:] if max(h, w) > tile_size: stacked_patches, n_patches = self.crop_image_to_patches( stacked_images, min_patches=min_patches, max_patches=max_patches, tile_size=tile_size, resample=resample, ) flat_patches = stacked_patches.reshape(-1, *stacked_patches.shape[2:]) flat_patches = self.rescale_and_normalize( flat_patches, do_rescale, rescale_factor, do_normalize, image_mean, image_std ) local_patches_grouped[key] = flat_patches.reshape(stacked_patches.shape) num_local_patches[key] = [n_patches] * stacked_images.shape[0] else: local_patches_grouped[key] = [None] * stacked_images.shape[0] num_local_patches[key] = [0] * stacked_images.shape[0] num_local_patches = reorder_images(num_local_patches, grouped_images_index) ordered_local = reorder_images(local_patches_grouped, grouped_images_index) else: num_local_patches = [0] * len(images) ordered_local = [] flat_local_list = [patch for item in ordered_local if item is not None for patch in item] # --- Global view (batched by shape group) --- global_target_size = size.height if crop_to_patches else tile_size grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) processed_global_grouped = {} for key, stacked in grouped_images.items(): h, w = stacked.shape[-2:] scale = global_target_size / max(h, w) new_h = round(h * scale) new_w = round(w * scale) stacked = self.resize(stacked, SizeDict(height=new_h, width=new_w), resample=resample) stacked = self.pad_to_square(stacked, background_color=self.background_color) stacked = self.rescale_and_normalize( stacked, do_rescale, rescale_factor, do_normalize, image_mean, image_std ) processed_global_grouped[key] = stacked all_pixel_values_global = reorder_images(processed_global_grouped, grouped_images_index) data = { "pixel_values": all_pixel_values_global, "num_local_patches": num_local_patches, } if flat_local_list: data["pixel_values_local"] = flat_local_list return BatchFeature(data=data, tensor_type=return_tensors) def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int: """ Returns the number of image patches for a given image size (1 global + local patches). """ images_kwargs = images_kwargs or {} min_patches = images_kwargs.get("min_patches", self.min_patches) max_patches = images_kwargs.get("max_patches", self.max_patches) tile_size = images_kwargs.get("tile_size", self.tile_size) crop_to_patches = images_kwargs.get("crop_to_patches", self.crop_to_patches) num_patches = 1 # global view if crop_to_patches and max(height, width) > tile_size: num_columns, num_rows = get_optimal_tiled_canvas( (height, width), (tile_size, tile_size), min_patches, max_patches ) num_patches += num_columns * num_rows return num_patches # Copied from transformers.models.llava.image_processing_llava.LlavaImageProcessor.pad_to_square def pad_to_square( self, images: "torch.Tensor", background_color: int | tuple[int, int, int] = 0, ) -> "torch.Tensor": """ Pads an image to a square based on the longest edge. Args: images (`torch.Tensor`): The images to pad. Shape: (batch_size, num_channels, height, width) or (num_channels, height, width). background_color (`int` or `tuple[int, int, int]`, *optional*, defaults to 0): The color to use for the padding. Can be an integer for single channel or a tuple of integers representing for multi-channel images. If passed as integer in multi-channel mode, it will default to `0` in subsequent channels. Returns: `torch.Tensor`: The padded images. """ height, width = images.shape[-2:] if height == width: return images num_channels = images.shape[1] if len(images.shape) == 4 else images.shape[0] if isinstance(background_color, int): background_color = [background_color] + [0] * (num_channels - 1) elif len(background_color) != num_channels: raise ValueError( f"background_color must have no more than {num_channels} elements to match the number of channels" ) max_dim = max(height, width) paste_x_left = (max_dim - width) // 2 paste_y_left = (max_dim - height) // 2 paste_x_right = max_dim - width - paste_x_left paste_y_right = max_dim - height - paste_y_left padded_images = tvF.pad( images, padding=[paste_x_left, paste_y_left, paste_x_right, paste_y_right], fill=background_color ) return padded_images __all__ = ["DeepseekOcr2ImageProcessor"]