





'''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)			,			)













from ...utils import (
    OptionalDependencyNotAvailable,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)


try:
	if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline
else:
	from .pipeline_unclip import UnCLIPPipeline
	from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline
	from .text_proj import UnCLIPTextProjModel
