-
Notifications
You must be signed in to change notification settings - Fork 31.7k
Add Fast Image Processor for Donut #37081
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
yonigozlan
merged 22 commits into
huggingface:main
from
rootonchair:donut_fast_image_processor
Apr 14, 2025
Merged
Changes from 2 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
b74aa2c
add donut fast image processor support
rootonchair 1930152
run make style
rootonchair 4f3b18b
Update src/transformers/models/donut/image_processing_donut_fast.py
rootonchair d38bfd0
update test, remove none default values
rootonchair 357bd0e
Merge branch 'donut_fast_image_processor' of github.com:rootonchair/t…
rootonchair 07ee506
add do_align_axis = True test, fix bug in slow image processor
rootonchair b14edcb
run make style
rootonchair c58ddb5
remove np usage
rootonchair 22dbfec
make style
rootonchair fc66a32
Apply suggestions from code review
rootonchair d91ae7c
Merge branch 'main' into donut_fast_image_processor
yonigozlan 0406e55
Update src/transformers/models/donut/image_processing_donut_fast.py
rootonchair 5443306
add size revert in preprocess
rootonchair 92d2f64
make style
rootonchair 98588ad
fix copies
rootonchair 73c901c
add test for preprocess with kwargs
rootonchair 6aafa0c
make style
rootonchair f2cfc94
Merge branch 'main' into donut_fast_image_processor
rootonchair 01fc2ff
handle None input_data_format in align_long_axis
rootonchair 93bcc22
Merge branch 'main' into donut_fast_image_processor
rootonchair dba0096
Merge branch 'donut_fast_image_processor' of github.com:rootonchair/t…
rootonchair 79d9198
Merge branch 'main' into donut_fast_image_processor
yonigozlan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
297 changes: 297 additions & 0 deletions
297
src/transformers/models/donut/image_processing_donut_fast.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,297 @@ | ||
| # coding=utf-8 | ||
| # Copyright 2025 The HuggingFace Inc. 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. | ||
| """Fast Image processor class for Donut.""" | ||
|
|
||
| from typing import Optional, Union | ||
|
|
||
| import numpy as np | ||
|
|
||
| from ...image_processing_utils_fast import ( | ||
| BASE_IMAGE_PROCESSOR_FAST_DOCSTRING, | ||
| BASE_IMAGE_PROCESSOR_FAST_DOCSTRING_PREPROCESS, | ||
| BaseImageProcessorFast, | ||
| BatchFeature, | ||
| DefaultFastImageProcessorKwargs, | ||
| ) | ||
| from ...image_transforms import ChannelDimension, group_images_by_shape, reorder_images | ||
| from ...image_utils import ( | ||
| IMAGENET_STANDARD_MEAN, | ||
| IMAGENET_STANDARD_STD, | ||
| ImageInput, | ||
| PILImageResampling, | ||
| SizeDict, | ||
| get_image_size, | ||
| ) | ||
| from ...processing_utils import Unpack | ||
| from ...utils import ( | ||
| TensorType, | ||
| add_start_docstrings, | ||
| is_torch_available, | ||
| is_torchvision_available, | ||
| is_torchvision_v2_available, | ||
| logging, | ||
| ) | ||
|
|
||
|
|
||
| logger = logging.get_logger(__name__) | ||
|
|
||
| if is_torch_available(): | ||
| import torch | ||
|
|
||
| if is_torchvision_available(): | ||
| if is_torchvision_v2_available(): | ||
| from torchvision.transforms.v2 import functional as F | ||
| else: | ||
| from torchvision.transforms import functional as F | ||
|
|
||
|
|
||
| class DonutFastImageProcessorKwargs(DefaultFastImageProcessorKwargs): | ||
| do_thumbnail: Optional[bool] | ||
| do_align_long_axis: Optional[bool] | ||
| do_pad: Optional[bool] | ||
|
|
||
|
|
||
| @add_start_docstrings( | ||
| "Constructs a fast Donut image processor.", | ||
| BASE_IMAGE_PROCESSOR_FAST_DOCSTRING, | ||
| """ | ||
| do_thumbnail (`bool`, *optional*, defaults to `self.do_thumbnail`): | ||
| Whether to resize the image using thumbnail method. | ||
| do_align_long_axis (`bool`, *optional*, defaults to `self.do_align_long_axis`): | ||
| Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees. | ||
| do_pad (`bool`, *optional*, defaults to `self.do_pad`): | ||
| Whether to pad the image. If `random_padding` is set to `True`, each image is padded with a random | ||
| amount of padding on each size, up to the largest image size in the batch. Otherwise, all images are | ||
| padded to the largest image size in the batch. | ||
| """, | ||
| ) | ||
| class DonutImageProcessorFast(BaseImageProcessorFast): | ||
| # This generated class can be used as a starting point for the fast image processor. | ||
| # if the image processor is only used for simple augmentations, such as resizing, center cropping, rescaling, or normalizing, | ||
| # only the default values should be set in the class. | ||
| # If the image processor requires more complex augmentations, methods from BaseImageProcessorFast can be overridden. | ||
| # In most cases, only the `_preprocess` method should be overridden. | ||
|
|
||
| # For an example of a fast image processor requiring more complex augmentations, see `LlavaNextImageProcessorFast`. | ||
|
|
||
| # Default values should be checked against the slow image processor | ||
| # None values left after checking can be removed | ||
| resample = PILImageResampling.BILINEAR | ||
| image_mean = IMAGENET_STANDARD_MEAN | ||
| image_std = IMAGENET_STANDARD_STD | ||
| size = {"height": 2560, "width": 1920} | ||
| default_to_square = None | ||
| crop_size = None | ||
| do_resize = True | ||
| do_center_crop = None | ||
| do_rescale = True | ||
| do_normalize = True | ||
| do_convert_rgb = None | ||
| do_thumbnail = True | ||
| do_align_long_axis = False | ||
| do_pad = True | ||
| valid_kwargs = DonutFastImageProcessorKwargs | ||
|
|
||
| def __init__(self, **kwargs: Unpack[DonutFastImageProcessorKwargs]): | ||
| super().__init__(**kwargs) | ||
rootonchair marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| @add_start_docstrings( | ||
| BASE_IMAGE_PROCESSOR_FAST_DOCSTRING_PREPROCESS, | ||
| """ | ||
| do_thumbnail (`bool`, *optional*, defaults to `self.do_thumbnail`): | ||
| Whether to resize the image using thumbnail method. | ||
| do_align_long_axis (`bool`, *optional*, defaults to `self.do_align_long_axis`): | ||
| Whether to align the long axis of the image with the long axis of `size` by rotating by 90 degrees. | ||
| do_pad (`bool`, *optional*, defaults to `self.do_pad`): | ||
| Whether to pad the image. If `random_padding` is set to `True`, each image is padded with a random | ||
| amount of padding on each size, up to the largest image size in the batch. Otherwise, all images are | ||
| padded to the largest image size in the batch. | ||
| """, | ||
| ) | ||
| def preprocess(self, images: ImageInput, **kwargs: Unpack[DonutFastImageProcessorKwargs]) -> BatchFeature: | ||
| return super().preprocess(images, **kwargs) | ||
|
|
||
| def align_long_axis( | ||
| self, | ||
| image: "torch.Tensor", | ||
| size: SizeDict, | ||
| ) -> "torch.Tensor": | ||
| """ | ||
| Align the long axis of the image to the longest axis of the specified size. | ||
|
|
||
| Args: | ||
| image (`torch.Tensor`): | ||
| The image to be aligned. | ||
| size (`Dict[str, int]`): | ||
| The size `{"height": h, "width": w}` to align the long axis to. | ||
|
|
||
| Returns: | ||
| `torch.Tensor`: The aligned image. | ||
| """ | ||
| input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST) | ||
rootonchair marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| output_height, output_width = size.height, size.width | ||
|
|
||
| if (output_width < output_height and input_width > input_height) or ( | ||
| output_width > output_height and input_width < input_height | ||
| ): | ||
| height_dim, width_dim = image.dim() - 2, image.dim() - 1 | ||
| image = torch.rot90(image, 3, dims=[height_dim, width_dim]) | ||
|
|
||
| return image | ||
|
|
||
| def pad_image( | ||
| self, | ||
| image: "torch.Tensor", | ||
| size: SizeDict, | ||
| random_padding: bool = False, | ||
| ) -> "torch.Tensor": | ||
| """ | ||
| Pad the image to the specified size. | ||
|
|
||
| Args: | ||
| image (`torch.Tensor`): | ||
| The image to be padded. | ||
| size (`Dict[str, int]`): | ||
| The size `{"height": h, "width": w}` to pad the image to. | ||
| random_padding (`bool`, *optional*, defaults to `False`): | ||
| Whether to use random padding or not. | ||
| data_format (`str` or `ChannelDimension`, *optional*): | ||
| The data format of the output image. If unset, the same format as the input image is used. | ||
| input_data_format (`ChannelDimension` or `str`, *optional*): | ||
| The channel dimension format of the input image. If not provided, it will be inferred. | ||
| """ | ||
| output_height, output_width = size.height, size.width | ||
| input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST) | ||
rootonchair marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| delta_width = output_width - input_width | ||
| delta_height = output_height - input_height | ||
|
|
||
| if random_padding: | ||
| pad_top = np.random.randint(low=0, high=delta_height + 1) | ||
| pad_left = np.random.randint(low=0, high=delta_width + 1) | ||
rootonchair marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| else: | ||
| pad_top = delta_height // 2 | ||
| pad_left = delta_width // 2 | ||
|
|
||
| pad_bottom = delta_height - pad_top | ||
| pad_right = delta_width - pad_left | ||
|
|
||
| padding = (pad_left, pad_top, pad_right, pad_bottom) | ||
| return F.pad(image, padding) | ||
|
|
||
| def pad(self, *args, **kwargs): | ||
| logger.info("pad is deprecated and will be removed in version 4.27. Please use pad_image instead.") | ||
| return self.pad_image(*args, **kwargs) | ||
|
|
||
| def thumbnail( | ||
| self, | ||
| image: "torch.Tensor", | ||
| size: SizeDict, | ||
| ) -> "torch.Tensor": | ||
| """ | ||
| Resize the image to make a thumbnail. The image is resized so that no dimension is larger than any | ||
| corresponding dimension of the specified size. | ||
|
|
||
| Args: | ||
| image (`np.ndarray`): | ||
| The image to be resized. | ||
| size (`Dict[str, int]`): | ||
| The size `{"height": h, "width": w}` to resize the image to. | ||
| resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`): | ||
| The resampling filter to use. | ||
| data_format (`Optional[Union[str, ChannelDimension]]`, *optional*): | ||
| The data format of the output image. If unset, the same format as the input image is used. | ||
| input_data_format (`ChannelDimension` or `str`, *optional*): | ||
| The channel dimension format of the input image. If not provided, it will be inferred. | ||
| """ | ||
| input_height, input_width = get_image_size(image, channel_dim=ChannelDimension.FIRST) | ||
rootonchair marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| output_height, output_width = size.height, size.width | ||
|
|
||
| # We always resize to the smallest of either the input or output size. | ||
| height = min(input_height, output_height) | ||
| width = min(input_width, output_width) | ||
|
|
||
| if height == input_height and width == input_width: | ||
| return image | ||
|
|
||
| if input_height > input_width: | ||
| width = int(input_width * height / input_height) | ||
| elif input_width > input_height: | ||
| height = int(input_height * width / input_width) | ||
|
|
||
| return self.resize( | ||
| image, | ||
| size=SizeDict(width=width, height=height), | ||
| interpolation=F.InterpolationMode.BICUBIC, | ||
| ) | ||
|
|
||
| def _preprocess( | ||
| self, | ||
| images: list["torch.Tensor"], | ||
| do_resize: bool, | ||
| do_thumbnail: bool, | ||
| do_align_long_axis: bool, | ||
| do_pad: bool, | ||
| size: SizeDict, | ||
| interpolation: Optional["F.InterpolationMode"], | ||
| do_center_crop: bool, | ||
| crop_size: SizeDict, | ||
| do_rescale: bool, | ||
| rescale_factor: float, | ||
| do_normalize: bool, | ||
| image_mean: Optional[Union[float, list[float]]], | ||
| image_std: Optional[Union[float, list[float]]], | ||
| return_tensors: Optional[Union[str, TensorType]], | ||
| **kwargs, | ||
| ) -> BatchFeature: | ||
| # Group images by size for batched resizing | ||
| grouped_images, grouped_images_index = group_images_by_shape(images) | ||
| resized_images_grouped = {} | ||
| for shape, stacked_images in grouped_images.items(): | ||
| if do_align_long_axis: | ||
| stacked_images = self.align_long_axis(image=stacked_images, size=size) | ||
| if do_resize: | ||
| shortest_edge = min(size.height, size.width) | ||
| stacked_images = self.resize( | ||
| image=stacked_images, size=SizeDict(shortest_edge=shortest_edge), interpolation=interpolation | ||
| ) | ||
| if do_thumbnail: | ||
| stacked_images = self.thumbnail(image=stacked_images, size=size) | ||
| if do_pad: | ||
| stacked_images = self.pad_image(image=stacked_images, size=size, random_padding=False) | ||
|
|
||
| resized_images_grouped[shape] = stacked_images | ||
| resized_images = reorder_images(resized_images_grouped, grouped_images_index) | ||
|
|
||
| # Group images by size for further processing | ||
| # Needed in case do_resize is False, or resize returns images with different sizes | ||
| grouped_images, grouped_images_index = group_images_by_shape(resized_images) | ||
| processed_images_grouped = {} | ||
| for shape, stacked_images in grouped_images.items(): | ||
| if do_center_crop: | ||
| stacked_images = self.center_crop(stacked_images, crop_size) | ||
| # Fused rescale and normalize | ||
| stacked_images = self.rescale_and_normalize( | ||
| stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std | ||
| ) | ||
| processed_images_grouped[shape] = stacked_images | ||
|
|
||
| processed_images = reorder_images(processed_images_grouped, grouped_images_index) | ||
| processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images | ||
|
|
||
| return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors) | ||
|
|
||
|
|
||
| __all__ = ["DonutImageProcessorFast"] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.