





'''simple docstring'''






import unittest

import numpy as np
import requests

from transformers.testing_utils import 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

      from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
      A__				:   int      =False

if is_vision_available():
      from PIL import Image

      from transformers import PixaStructImageProcessor




class  UpperCAmelCase     (			unittest.TestCase   ):




      def __init__(			self			: Union[str, Any]			,			__snake_case			: int			,			__snake_case			: Union[str, Any]=7			,			__snake_case			: Any=3			,			__snake_case			: Dict=18			,			__snake_case			: List[Any]=30			,			__snake_case			: int=4_00			,			__snake_case			: List[Any]=None			,			__snake_case			: List[str]=True			,			__snake_case			: Any=True			,			__snake_case			: Tuple=None			,			)				->      Union[str, Any]:
            _lowerCAmelCase							     =							size if size is not None else {"""height""": 20, """width""": 20}
            _lowerCAmelCase							     =							parent
            _lowerCAmelCase							     =							batch_size
            _lowerCAmelCase							     =							num_channels
            _lowerCAmelCase							     =							image_size
            _lowerCAmelCase							     =							min_resolution
            _lowerCAmelCase							     =							max_resolution
            _lowerCAmelCase							     =							size
            _lowerCAmelCase							     =							do_normalize
            _lowerCAmelCase							     =							do_convert_rgb
            _lowerCAmelCase							     =							[5_12, 10_24, 20_48, 40_96]
            _lowerCAmelCase							     =							patch_size if patch_size is not None else {"""height""": 16, """width""": 16}




      def 				lowercase__    (			self			: Any  )				->      str:
            return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}




      def 				lowercase__    (			self			: int  )				->      Optional[int]:
            _lowerCAmelCase							     =							"""https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"""
            _lowerCAmelCase							     =							Image.open(requests.get(__snake_case			,			stream=__snake_case  ).raw  ).convert("""RGB"""  )
            return raw_image




@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11							,		reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.'''							,		)
@require_torch
@require_vision
class  UpperCAmelCase     (			snake_case_							,		unittest.TestCase   ):
      _lowercase:			str						     =   PixaStructImageProcessor if is_vision_available() else None




      def 				lowercase__    (			self			: Optional[Any]  )				->      Optional[int]:
            _lowerCAmelCase							     =							PixaStructImageProcessingTester(self  )




      @property
      def 				lowercase__    (			self			: List[Any]  )				->      Any:
            return self.image_processor_tester.prepare_image_processor_dict()




      def 				lowercase__    (			self			: List[str]  )				->      Any:
            _lowerCAmelCase							     =							self.image_processing_class(**self.image_processor_dict  )
            self.assertTrue(hasattr(__snake_case			,			"""do_normalize"""  )  )
            self.assertTrue(hasattr(__snake_case			,			"""do_convert_rgb"""  )  )




      def 				lowercase__    (			self			: str  )				->      List[str]:
            _lowerCAmelCase							     =							self.image_processor_tester.prepare_dummy_image()

            _lowerCAmelCase							     =							self.image_processing_class(**self.image_processor_dict  )
            _lowerCAmelCase							     =							20_48

            _lowerCAmelCase							     =							image_processor(__snake_case			,			return_tensors="""pt"""			,			max_patches=__snake_case  )
            self.assertTrue(torch.allclose(inputs.flattened_patches.mean()			,			torch.tensor(0.06_06  )			,			atol=1E-3			,			rtol=1E-3  )  )




      def 				lowercase__    (			self			: Union[str, Any]  )				->      Tuple:
            # Initialize image_processor
            _lowerCAmelCase							     =							self.image_processing_class(**self.image_processor_dict  )
            # create random PIL images
            _lowerCAmelCase							     =							prepare_image_inputs(self.image_processor_tester			,			equal_resolution=__snake_case  )
            for image in image_inputs:
                  self.assertIsInstance(__snake_case			,			Image.Image  )

            # Test not batched input
            _lowerCAmelCase							     =							(
                (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
                * self.image_processor_tester.num_channels
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                  # Test not batched input
                  _lowerCAmelCase							     =							image_processor(
                      image_inputs[0]			,			return_tensors="""pt"""			,			max_patches=__snake_case  ).flattened_patches
                  self.assertEqual(
                      encoded_images.shape			,			(1, max_patch, expected_hidden_dim)			,			)

                  # Test batched
                  _lowerCAmelCase							     =							image_processor(
                      __snake_case			,			return_tensors="""pt"""			,			max_patches=__snake_case  ).flattened_patches
                  self.assertEqual(
                      encoded_images.shape			,			(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,			)




      def 				lowercase__    (			self			: Any  )				->      Tuple:
            # Initialize image_processor
            _lowerCAmelCase							     =							self.image_processing_class(**self.image_processor_dict  )
            # create random PIL images
            _lowerCAmelCase							     =							prepare_image_inputs(self.image_processor_tester			,			equal_resolution=__snake_case  )
            for image in image_inputs:
                  self.assertIsInstance(__snake_case			,			Image.Image  )

            # Test not batched input
            _lowerCAmelCase							     =							(
                (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
                * self.image_processor_tester.num_channels
            ) + 2

            _lowerCAmelCase							     =							True

            for max_patch in self.image_processor_tester.max_patches:
                  # Test not batched input
                  with self.assertRaises(__snake_case  ):
                        _lowerCAmelCase							     =							image_processor(
                            image_inputs[0]			,			return_tensors="""pt"""			,			max_patches=__snake_case  ).flattened_patches

                  _lowerCAmelCase							     =							"""Hello"""

                  _lowerCAmelCase							     =							image_processor(
                      image_inputs[0]			,			return_tensors="""pt"""			,			max_patches=__snake_case			,			header_text=__snake_case  ).flattened_patches
                  self.assertEqual(
                      encoded_images.shape			,			(1, max_patch, expected_hidden_dim)			,			)

                  # Test batched
                  _lowerCAmelCase							     =							image_processor(
                      __snake_case			,			return_tensors="""pt"""			,			max_patches=__snake_case			,			header_text=__snake_case  ).flattened_patches
                  self.assertEqual(
                      encoded_images.shape			,			(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,			)




      def 				lowercase__    (			self			: Optional[int]  )				->      Optional[int]:
            # Initialize image_processor
            _lowerCAmelCase							     =							self.image_processing_class(**self.image_processor_dict  )
            # create random numpy tensors
            _lowerCAmelCase							     =							prepare_image_inputs(self.image_processor_tester			,			equal_resolution=__snake_case			,			numpify=__snake_case  )
            for image in image_inputs:
                  self.assertIsInstance(__snake_case			,			np.ndarray  )

            _lowerCAmelCase							     =							(
                (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
                * self.image_processor_tester.num_channels
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                  # Test not batched input
                  _lowerCAmelCase							     =							image_processor(
                      image_inputs[0]			,			return_tensors="""pt"""			,			max_patches=__snake_case  ).flattened_patches
                  self.assertEqual(
                      encoded_images.shape			,			(1, max_patch, expected_hidden_dim)			,			)

                  # Test batched
                  _lowerCAmelCase							     =							image_processor(
                      __snake_case			,			return_tensors="""pt"""			,			max_patches=__snake_case  ).flattened_patches
                  self.assertEqual(
                      encoded_images.shape			,			(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,			)




      def 				lowercase__    (			self			: Optional[int]  )				->      Optional[Any]:
            # Initialize image_processor
            _lowerCAmelCase							     =							self.image_processing_class(**self.image_processor_dict  )
            # create random PyTorch tensors
            _lowerCAmelCase							     =							prepare_image_inputs(self.image_processor_tester			,			equal_resolution=__snake_case			,			torchify=__snake_case  )
            for image in image_inputs:
                  self.assertIsInstance(__snake_case			,			torch.Tensor  )

            # Test not batched input
            _lowerCAmelCase							     =							(
                (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
                * self.image_processor_tester.num_channels
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                  # Test not batched input
                  _lowerCAmelCase							     =							image_processor(
                      image_inputs[0]			,			return_tensors="""pt"""			,			max_patches=__snake_case  ).flattened_patches
                  self.assertEqual(
                      encoded_images.shape			,			(1, max_patch, expected_hidden_dim)			,			)

                  # Test batched
                  _lowerCAmelCase							     =							image_processor(
                      __snake_case			,			return_tensors="""pt"""			,			max_patches=__snake_case  ).flattened_patches
                  self.assertEqual(
                      encoded_images.shape			,			(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,			)




@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11							,		reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.'''							,		)
@require_torch
@require_vision
class  UpperCAmelCase     (			snake_case_							,		unittest.TestCase   ):
      _lowercase:			Tuple						     =   PixaStructImageProcessor if is_vision_available() else None




      def 				lowercase__    (			self			: Optional[Any]  )				->      int:
            _lowerCAmelCase							     =							PixaStructImageProcessingTester(self			,			num_channels=4  )
            _lowerCAmelCase							     =							3




      @property
      def 				lowercase__    (			self			: List[str]  )				->      Tuple:
            return self.image_processor_tester.prepare_image_processor_dict()




      def 				lowercase__    (			self			: Optional[Any]  )				->      List[str]:
            _lowerCAmelCase							     =							self.image_processing_class(**self.image_processor_dict  )
            self.assertTrue(hasattr(__snake_case			,			"""do_normalize"""  )  )
            self.assertTrue(hasattr(__snake_case			,			"""do_convert_rgb"""  )  )




      def 				lowercase__    (			self			: Optional[int]  )				->      Tuple:
            # Initialize image_processor
            _lowerCAmelCase							     =							self.image_processing_class(**self.image_processor_dict  )
            # create random PIL images
            _lowerCAmelCase							     =							prepare_image_inputs(self.image_processor_tester			,			equal_resolution=__snake_case  )
            for image in image_inputs:
                  self.assertIsInstance(__snake_case			,			Image.Image  )

            # Test not batched input
            _lowerCAmelCase							     =							(
                (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""])
                * (self.image_processor_tester.num_channels - 1)
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                  # Test not batched input
                  _lowerCAmelCase							     =							image_processor(
                      image_inputs[0]			,			return_tensors="""pt"""			,			max_patches=__snake_case  ).flattened_patches
                  self.assertEqual(
                      encoded_images.shape			,			(1, max_patch, expected_hidden_dim)			,			)

                  # Test batched
                  _lowerCAmelCase							     =							image_processor(
                      __snake_case			,			return_tensors="""pt"""			,			max_patches=__snake_case  ).flattened_patches
                  self.assertEqual(
                      encoded_images.shape			,			(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,			)











'''simple docstring'''





def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    lowerCAmelCase__ :  Tuple							      =					abs(UpperCamelCase			)
    lowerCAmelCase__ :  List[Any]							      =					0
    while n > 0:
        res += n % 10
        n //= 10
    return res
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    lowerCAmelCase__ :  Union[str, Any]							      =					abs(UpperCamelCase			)
    return n if n < 10 else n % 10 + sum_of_digits(n // 10			)
def    _SCREAMING_SNAKE_CASE  (       UpperCamelCase			):



    """simple docstring"""





    return sum(int(UpperCamelCase			) for c in str(abs(UpperCamelCase			)			)			)
def    _SCREAMING_SNAKE_CASE  (       ):



    """simple docstring"""





    from collections.abc import Callable
    from timeit import timeit

    def benchmark_a_function(UpperCamelCase							,    UpperCamelCase			) -> None:
        lowerCAmelCase__ :  str							      =					f"""{func.__name__}({value})"""
        lowerCAmelCase__ :  str							      =					timeit(f"""__main__.{call}"""							,    setup="""import __main__"""			)
        print(f"""{call:56} = {func(UpperCamelCase			)} -- {timing:.4f} seconds"""			)

    for value in (262144, 1125899906842624, 1267650600228229401496703205376):
        for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact):
            benchmark_a_function(UpperCamelCase							,    UpperCamelCase			)
        print()


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 benchmark()


