






"""simple docstring"""





from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
    import PIL


UpperCamelCase_	:				int										= logging.get_logger(__name__)


class      _lowercase (     lowerCAmelCase						):
      _a   :     Optional[Any]								=   ['''pixel_values''']


      def __init__(    self				:	Any							,   a				:	bool = True							,   a				:	Dict[str, int] = None							,   a				:	PILImageResampling = PILImageResampling.BICUBIC							,   a				:	bool = True							,   a				:	Union[int, float] = 1 / 2_5_5							,   a				:	bool = True							,   a				:	Optional[Union[float, List[float]]] = None							,   a				:	Optional[Union[float, List[float]]] = None							,   a				:	bool = True							,   **a				:	Union[str, Any]							,   ):





            """simple docstring"""







            super().__init__(**a						)
            __snake_case      :    Dict  			=size if size is not None else {'''height''': 3_8_4, '''width''': 3_8_4}
            __snake_case      :    Union[str, Any]  			=get_size_dict(a							,   default_to_square=a						)

            __snake_case      :    Optional[int]  			=do_resize
            __snake_case      :    List[Any]  			=size
            __snake_case      :    List[str]  			=resample
            __snake_case      :    str  			=do_rescale
            __snake_case      :    int  			=rescale_factor
            __snake_case      :    Optional[Any]  			=do_normalize
            __snake_case      :    Any  			=image_mean if image_mean is not None else OPENAI_CLIP_MEAN
            __snake_case      :    List[str]  			=image_std if image_std is not None else OPENAI_CLIP_STD
            __snake_case      :    int  			=do_convert_rgb


      def _UpperCamelCase						(    self				:	Tuple							,   a				:	np.ndarray							,   a				:	Dict[str, int]							,   a				:	PILImageResampling = PILImageResampling.BICUBIC							,   a				:	Optional[Union[str, ChannelDimension]] = None							,   **a				:	Dict							,   ):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=get_size_dict(a							,   default_to_square=a						)
            if "height" not in size or "width" not in size:
                  raise ValueError(f'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}'''						)
            __snake_case      :    Optional[int]  			=(size['''height'''], size['''width'''])
            return resize(a							,   size=a							,   resample=a							,   data_format=a							,   **a						)


      def _UpperCamelCase						(    self				:	Dict							,   a				:	np.ndarray							,   a				:	Union[int, float]							,   a				:	Optional[Union[str, ChannelDimension]] = None							,   **a				:	List[str]							,   ):





            """simple docstring"""







            return rescale(a							,   scale=a							,   data_format=a							,   **a						)


      def _UpperCamelCase						(    self				:	Tuple							,   a				:	np.ndarray							,   a				:	Union[float, List[float]]							,   a				:	Union[float, List[float]]							,   a				:	Optional[Union[str, ChannelDimension]] = None							,   **a				:	List[Any]							,   ):





            """simple docstring"""







            return normalize(a							,   mean=a							,   std=a							,   data_format=a							,   **a						)







      def _UpperCamelCase						(    self				:	Tuple							,   a				:	ImageInput							,   a				:	Optional[bool] = None							,   a				:	Optional[Dict[str, int]] = None							,   a				:	PILImageResampling = None							,   a				:	Optional[bool] = None							,   a				:	Optional[float] = None							,   a				:	Optional[bool] = None							,   a				:	Optional[Union[float, List[float]]] = None							,   a				:	Optional[Union[float, List[float]]] = None							,   a				:	Optional[Union[str, TensorType]] = None							,   a				:	bool = None							,   a				:	ChannelDimension = ChannelDimension.FIRST							,   **a				:	Dict							,   ):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=do_resize if do_resize is not None else self.do_resize
            __snake_case      :    List[str]  			=resample if resample is not None else self.resample
            __snake_case      :    int  			=do_rescale if do_rescale is not None else self.do_rescale
            __snake_case      :    Any  			=rescale_factor if rescale_factor is not None else self.rescale_factor
            __snake_case      :    int  			=do_normalize if do_normalize is not None else self.do_normalize
            __snake_case      :    Tuple  			=image_mean if image_mean is not None else self.image_mean
            __snake_case      :    List[str]  			=image_std if image_std is not None else self.image_std
            __snake_case      :    Optional[Any]  			=do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

            __snake_case      :    List[Any]  			=size if size is not None else self.size
            __snake_case      :    List[Any]  			=get_size_dict(a							,   default_to_square=a						)

            __snake_case      :    Tuple  			=make_list_of_images(a						)

            if not valid_images(a						):
                  raise ValueError(
                      '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                      '''torch.Tensor, tf.Tensor or jax.ndarray.'''						)

            if do_resize and size is None or resample is None:
                  raise ValueError('''Size and resample must be specified if do_resize is True.'''						)

            if do_rescale and rescale_factor is None:
                  raise ValueError('''Rescale factor must be specified if do_rescale is True.'''						)

            if do_normalize and (image_mean is None or image_std is None):
                  raise ValueError('''Image mean and std must be specified if do_normalize is True.'''						)

            # PIL RGBA images are converted to RGB
            if do_convert_rgb:
                  __snake_case      :    Optional[int]  			=[convert_to_rgb(a						) for image in images]

            # All transformations expect numpy arrays.
            __snake_case      :    str  			=[to_numpy_array(a						) for image in images]

            if do_resize:
                  __snake_case      :    int  			=[self.resize(image=a							,   size=a							,   resample=a						) for image in images]

            if do_rescale:
                  __snake_case      :    List[Any]  			=[self.rescale(image=a							,   scale=a						) for image in images]

            if do_normalize:
                  __snake_case      :    Any  			=[self.normalize(image=a							,   mean=a							,   std=a						) for image in images]

            __snake_case      :    Optional[int]  			=[to_channel_dimension_format(a							,   a						) for image in images]

            __snake_case      :    str  			=BatchFeature(data={'''pixel_values''': images}							,   tensor_type=a						)

            return encoded_outputs










"""simple docstring"""





import unittest

import numpy as np

from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import DonutImageProcessor


class      _lowercase (     unittest.TestCase						):


      def __init__(    self				:	List[Any]							,   a				:	int							,   a				:	Dict=7							,   a				:	int=3							,   a				:	int=1_8							,   a				:	Dict=3_0							,   a				:	Dict=4_0_0							,   a				:	Optional[Any]=True							,   a				:	Dict=None							,   a				:	int=True							,   a				:	Dict=False							,   a				:	int=True							,   a				:	str=True							,   a				:	List[str]=[0.5, 0.5, 0.5]							,   a				:	Optional[Any]=[0.5, 0.5, 0.5]							,   ):





            """simple docstring"""







            __snake_case      :    List[Any]  			=parent
            __snake_case      :    List[Any]  			=batch_size
            __snake_case      :    str  			=num_channels
            __snake_case      :    Dict  			=image_size
            __snake_case      :    str  			=min_resolution
            __snake_case      :    Tuple  			=max_resolution
            __snake_case      :    str  			=do_resize
            __snake_case      :    Any  			=size if size is not None else {'''height''': 1_8, '''width''': 2_0}
            __snake_case      :    List[Any]  			=do_thumbnail
            __snake_case      :    Tuple  			=do_align_axis
            __snake_case      :    Any  			=do_pad
            __snake_case      :    Dict  			=do_normalize
            __snake_case      :    List[Any]  			=image_mean
            __snake_case      :    Any  			=image_std







      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            return {
                "do_resize": self.do_resize,
                "size": self.size,
                "do_thumbnail": self.do_thumbnail,
                "do_align_long_axis": self.do_align_axis,
                "do_pad": self.do_pad,
                "do_normalize": self.do_normalize,
                "image_mean": self.image_mean,
                "image_std": self.image_std,
            }



@require_torch
@require_vision
class      _lowercase (     lowerCAmelCase		,  unittest.TestCase						):
      _a   :     str								=   DonutImageProcessor if is_vision_available() else None


      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=DonutImageProcessingTester(self						)


      @property
      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            return self.image_processor_tester.prepare_image_processor_dict()


      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=self.image_processing_class(**self.image_processor_dict						)
            self.assertTrue(hasattr(a							,   '''do_resize'''						)						)
            self.assertTrue(hasattr(a							,   '''size'''						)						)
            self.assertTrue(hasattr(a							,   '''do_thumbnail'''						)						)
            self.assertTrue(hasattr(a							,   '''do_align_long_axis'''						)						)
            self.assertTrue(hasattr(a							,   '''do_pad'''						)						)
            self.assertTrue(hasattr(a							,   '''do_normalize'''						)						)
            self.assertTrue(hasattr(a							,   '''image_mean'''						)						)
            self.assertTrue(hasattr(a							,   '''image_std'''						)						)


      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Dict  			=self.image_processing_class.from_dict(self.image_processor_dict						)
            self.assertEqual(image_processor.size							,   {'''height''': 1_8, '''width''': 2_0}						)

            __snake_case      :    List[Any]  			=self.image_processing_class.from_dict(self.image_processor_dict							,   size=4_2						)
            self.assertEqual(image_processor.size							,   {'''height''': 4_2, '''width''': 4_2}						)

            # Previous config had dimensions in (width, height) order
            __snake_case      :    Tuple  			=self.image_processing_class.from_dict(self.image_processor_dict							,   size=(4_2, 8_4)						)
            self.assertEqual(image_processor.size							,   {'''height''': 8_4, '''width''': 4_2}						)


      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            pass


      @is_flaky()
      def _UpperCamelCase						(    self				:	Union[str, Any]						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=self.image_processing_class(**self.image_processor_dict						)
            # create random PIL images
            __snake_case      :    List[Any]  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   Image.Image						)

            # Test not batched input
            __snake_case      :    str  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    Optional[int]  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )


      @is_flaky()
      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Tuple  			=self.image_processing_class(**self.image_processor_dict						)
            # create random numpy tensors
            __snake_case      :    Optional[int]  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a							,   numpify=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   np.ndarray						)

            # Test not batched input
            __snake_case      :    List[Any]  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    int  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )







      @is_flaky()
      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    Dict  			=self.image_processing_class(**self.image_processor_dict						)
            # create random PyTorch tensors
            __snake_case      :    Dict  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a							,   torchify=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   torch.Tensor						)

            # Test not batched input
            __snake_case      :    Dict  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    Optional[int]  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )


