
"""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:
      SCREAMING_SNAKE_CASE      =     False

if is_vision_available():
      from PIL import Image

      from transformers import PixaStructImageProcessor



class   __a  (      unittest.TestCase	):






       def __init__(  self :							Dict       ,      UpperCAmelCase_ :							Dict       ,      UpperCAmelCase_ :							Optional[Any]=7       ,      UpperCAmelCase_ :							List[Any]=3       ,      UpperCAmelCase_ :							Union[str, Any]=18       ,      UpperCAmelCase_ :							int=30       ,      UpperCAmelCase_ :							str=400       ,      UpperCAmelCase_ :							Tuple=None       ,      UpperCAmelCase_ :							Optional[int]=True       ,      UpperCAmelCase_ :							Union[str, Any]=True       ,      UpperCAmelCase_ :							Dict=None       ,      )->  int:







              """simple docstring"""
              UpperCamelCase					 =		size if size is not None else {"height": 20, "width": 20}
              UpperCamelCase					 =		parent
              UpperCamelCase					 =		batch_size
              UpperCamelCase					 =		num_channels
              UpperCamelCase					 =		image_size
              UpperCamelCase					 =		min_resolution
              UpperCamelCase					 =		max_resolution
              UpperCamelCase					 =		size
              UpperCamelCase					 =		do_normalize
              UpperCamelCase					 =		do_convert_rgb
              UpperCamelCase					 =		[512, 1_024, 2_048, 4_096]
              UpperCamelCase					 =		patch_size if patch_size is not None else {"height": 16, "width": 16}






       def 	_SCREAMING_SNAKE_CASE       (  self :							int			)->  Union[str, Any]:







              """simple docstring"""
              return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}






       def 	_SCREAMING_SNAKE_CASE       (  self :							str			)->  Dict:







              """simple docstring"""
              UpperCamelCase					 =		"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"
              UpperCamelCase					 =		Image.open(requests.get(UpperCAmelCase_       ,      stream=UpperCAmelCase_			).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   __a  (      _lowerCAmelCase    ,     unittest.TestCase	):
       UpperCamelCase_		:					Dict   =			PixaStructImageProcessor if is_vision_available() else None






       def 	_SCREAMING_SNAKE_CASE       (  self :							int			)->  List[Any]:







              """simple docstring"""
              UpperCamelCase					 =		PixaStructImageProcessingTester(self			)






       @property
       def 	_SCREAMING_SNAKE_CASE       (  self :							Optional[int]			)->  List[str]:







              """simple docstring"""
              return self.image_processor_tester.prepare_image_processor_dict()






       def 	_SCREAMING_SNAKE_CASE       (  self :							Optional[Any]			)->  Optional[Any]:







              """simple docstring"""
              UpperCamelCase					 =		self.image_processing_class(**self.image_processor_dict			)
              self.assertTrue(hasattr(UpperCAmelCase_       ,      "do_normalize"			)			)
              self.assertTrue(hasattr(UpperCAmelCase_       ,      "do_convert_rgb"			)			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							str			)->  str:







              """simple docstring"""
              UpperCamelCase					 =		self.image_processor_tester.prepare_dummy_image()

              UpperCamelCase					 =		self.image_processing_class(**self.image_processor_dict			)
              UpperCamelCase					 =		2_048

              UpperCamelCase					 =		image_processor(UpperCAmelCase_       ,      return_tensors="pt"       ,      max_patches=UpperCAmelCase_			)
              self.assertTrue(torch.allclose(inputs.flattened_patches.mean()       ,      torch.tensor(0.0606			)       ,      atol=1e-3       ,      rtol=1e-3			)			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							Tuple			)->  Union[str, Any]:







              """simple docstring"""
              # Initialize image_processor
              UpperCamelCase					 =		self.image_processing_class(**self.image_processor_dict			)
              # create random PIL images
              UpperCamelCase					 =		prepare_image_inputs(self.image_processor_tester       ,      equal_resolution=UpperCAmelCase_			)
              for image in image_inputs:
                     self.assertIsInstance(UpperCAmelCase_       ,      Image.Image			)

              # Test not batched input
              UpperCamelCase					 =		(
                  (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
                     UpperCamelCase					 =		image_processor(
                         image_inputs[0]       ,      return_tensors="pt"       ,      max_patches=UpperCAmelCase_			).flattened_patches
                     self.assertEqual(
                         encoded_images.shape       ,      (1, max_patch, expected_hidden_dim)       ,      )

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






       def 	_SCREAMING_SNAKE_CASE       (  self :							List[Any]			)->  Any:







              """simple docstring"""
              # Initialize image_processor
              UpperCamelCase					 =		self.image_processing_class(**self.image_processor_dict			)
              # create random PIL images
              UpperCamelCase					 =		prepare_image_inputs(self.image_processor_tester       ,      equal_resolution=UpperCAmelCase_			)
              for image in image_inputs:
                     self.assertIsInstance(UpperCAmelCase_       ,      Image.Image			)

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

              UpperCamelCase					 =		True

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

                     UpperCamelCase					 =		"Hello"

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

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






       def 	_SCREAMING_SNAKE_CASE       (  self :							List[Any]			)->  Union[str, Any]:







              """simple docstring"""
              # Initialize image_processor
              UpperCamelCase					 =		self.image_processing_class(**self.image_processor_dict			)
              # create random numpy tensors
              UpperCamelCase					 =		prepare_image_inputs(self.image_processor_tester       ,      equal_resolution=UpperCAmelCase_       ,      numpify=UpperCAmelCase_			)
              for image in image_inputs:
                     self.assertIsInstance(UpperCAmelCase_       ,      np.ndarray			)

              UpperCamelCase					 =		(
                  (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
                     UpperCamelCase					 =		image_processor(
                         image_inputs[0]       ,      return_tensors="pt"       ,      max_patches=UpperCAmelCase_			).flattened_patches
                     self.assertEqual(
                         encoded_images.shape       ,      (1, max_patch, expected_hidden_dim)       ,      )

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






       def 	_SCREAMING_SNAKE_CASE       (  self :							List[Any]			)->  str:







              """simple docstring"""
              # Initialize image_processor
              UpperCamelCase					 =		self.image_processing_class(**self.image_processor_dict			)
              # create random PyTorch tensors
              UpperCamelCase					 =		prepare_image_inputs(self.image_processor_tester       ,      equal_resolution=UpperCAmelCase_       ,      torchify=UpperCAmelCase_			)
              for image in image_inputs:
                     self.assertIsInstance(UpperCAmelCase_       ,      torch.Tensor			)

              # Test not batched input
              UpperCamelCase					 =		(
                  (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
                     UpperCamelCase					 =		image_processor(
                         image_inputs[0]       ,      return_tensors="pt"       ,      max_patches=UpperCAmelCase_			).flattened_patches
                     self.assertEqual(
                         encoded_images.shape       ,      (1, max_patch, expected_hidden_dim)       ,      )

                     # Test batched
                     UpperCamelCase					 =		image_processor(
                         UpperCAmelCase_       ,      return_tensors="pt"       ,      max_patches=UpperCAmelCase_			).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   __a  (      _lowerCAmelCase    ,     unittest.TestCase	):
       UpperCamelCase_		:					Any   =			PixaStructImageProcessor if is_vision_available() else None






       def 	_SCREAMING_SNAKE_CASE       (  self :							Tuple			)->  Optional[int]:







              """simple docstring"""
              UpperCamelCase					 =		PixaStructImageProcessingTester(self       ,      num_channels=4			)
              UpperCamelCase					 =		3






       @property
       def 	_SCREAMING_SNAKE_CASE       (  self :							int			)->  List[Any]:







              """simple docstring"""
              return self.image_processor_tester.prepare_image_processor_dict()






       def 	_SCREAMING_SNAKE_CASE       (  self :							int			)->  Optional[int]:







              """simple docstring"""
              UpperCamelCase					 =		self.image_processing_class(**self.image_processor_dict			)
              self.assertTrue(hasattr(UpperCAmelCase_       ,      "do_normalize"			)			)
              self.assertTrue(hasattr(UpperCAmelCase_       ,      "do_convert_rgb"			)			)






       def 	_SCREAMING_SNAKE_CASE       (  self :							str			)->  List[Any]:







              """simple docstring"""
              # Initialize image_processor
              UpperCamelCase					 =		self.image_processing_class(**self.image_processor_dict			)
              # create random PIL images
              UpperCamelCase					 =		prepare_image_inputs(self.image_processor_tester       ,      equal_resolution=UpperCAmelCase_			)
              for image in image_inputs:
                     self.assertIsInstance(UpperCAmelCase_       ,      Image.Image			)

              # Test not batched input
              UpperCamelCase					 =		(
                  (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
                     UpperCamelCase					 =		image_processor(
                         image_inputs[0]       ,      return_tensors="pt"       ,      max_patches=UpperCAmelCase_			).flattened_patches
                     self.assertEqual(
                         encoded_images.shape       ,      (1, max_patch, expected_hidden_dim)       ,      )

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







"""simple docstring"""


def 	lowerCamelCase__			(							UpperCAmelCase_				)->							int:







       """simple docstring"""
       if a < 0:
              raise ValueError("Input value must be a positive integer"				)
       elif isinstance(UpperCAmelCase_		,      UpperCAmelCase_				):
              raise TypeError("Input value must be a 'int' type"				)
       return bin(UpperCAmelCase_				).count("1"				)


if __name__ == "__main__":
      import doctest

      doctest.testmod()





