






import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch
			from torch import nn

			from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
			from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import DPTImageProcessor




class 							snake_case_       :

						"""simple docstring"""



						def __init__(self:					str ,					__UpperCAmelCase:					Union[str, Any] ,					__UpperCAmelCase:					int=2 ,					__UpperCAmelCase:					Dict=32 ,					__UpperCAmelCase:					Any=16 ,					__UpperCAmelCase:					Optional[Any]=3 ,					__UpperCAmelCase:					List[Any]=True ,					__UpperCAmelCase:					List[str]=True ,					__UpperCAmelCase:					Dict=32 ,					__UpperCAmelCase:					List[Any]=4 ,					__UpperCAmelCase:					str=[0, 1, 2, 3] ,					__UpperCAmelCase:					Any=4 ,					__UpperCAmelCase:					Union[str, Any]=37 ,					__UpperCAmelCase:					List[str]="gelu" ,					__UpperCAmelCase:					int=0.1 ,					__UpperCAmelCase:					Tuple=0.1 ,					__UpperCAmelCase:					Any=0.02 ,					__UpperCAmelCase:					Any=3 ,					__UpperCAmelCase:					Any=[1, 384, 24, 24] ,					__UpperCAmelCase:					Any=True ,					__UpperCAmelCase:					str=None ,					)    ->     Any:




											'''simple docstring'''



											__a					:						Tuple      =					parent
											__a					:						Optional[Any]      =					batch_size
											__a					:						Optional[int]      =					image_size
											__a					:						Optional[int]      =					patch_size
											__a					:						Optional[int]      =					num_channels
											__a					:						Any      =					is_training
											__a					:						Tuple      =					use_labels
											__a					:						int      =					hidden_size
											__a					:						Optional[Any]      =					num_hidden_layers
											__a					:						Optional[int]      =					backbone_out_indices
											__a					:						List[str]      =					num_attention_heads
											__a					:						Union[str, Any]      =					intermediate_size
											__a					:						Optional[int]      =					hidden_act
											__a					:						Tuple      =					hidden_dropout_prob
											__a					:						Optional[int]      =					attention_probs_dropout_prob
											__a					:						List[str]      =					initializer_range
											__a					:						Optional[int]      =					num_labels
											__a					:						List[str]      =					backbone_featmap_shape
											__a					:						int      =					scope
											__a					:						str      =					is_hybrid
											# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
											__a					:						Dict      =					(image_size // patch_size) ** 2
											__a					:						Optional[int]      =					num_patches + 1



						def        UpperCAmelCase__					(self:					Any   )    ->     Optional[int]:




											'''simple docstring'''



											__a					:						Union[str, Any]      =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

											__a					:						str      =					None
											if self.use_labels:
																__a					:						Optional[int]      =					ids_tensor([self.batch_size, self.image_size, self.image_size] ,					self.num_labels   )

											__a					:						List[Any]      =					self.get_config()

											return config, pixel_values, labels



						def        UpperCAmelCase__					(self:					Optional[int]   )    ->     str:




											'''simple docstring'''



											__a					:						List[str]      =					{
											    '''global_padding''': '''same''',
											    '''layer_type''': '''bottleneck''',
											    '''depths''': [3, 4, 9],
											    '''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
											    '''embedding_dynamic_padding''': True,
											    '''hidden_sizes''': [96, 192, 384, 768],
											    '''num_groups''': 2,
											}

											return DPTConfig(
											    image_size=self.image_size ,					patch_size=self.patch_size ,					num_channels=self.num_channels ,					hidden_size=self.hidden_size ,					num_hidden_layers=self.num_hidden_layers ,					backbone_out_indices=self.backbone_out_indices ,					num_attention_heads=self.num_attention_heads ,					intermediate_size=self.intermediate_size ,					hidden_act=self.hidden_act ,					hidden_dropout_prob=self.hidden_dropout_prob ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob ,					is_decoder=a__ ,					initializer_range=self.initializer_range ,					is_hybrid=self.is_hybrid ,					backbone_config=a__ ,					backbone_featmap_shape=self.backbone_featmap_shape ,					)



						def        UpperCAmelCase__					(self:					Any ,					__UpperCAmelCase:					Dict ,					__UpperCAmelCase:					List[str] ,					__UpperCAmelCase:					List[Any]   )    ->     List[Any]:




											'''simple docstring'''



											__a					:						Union[str, Any]      =					DPTModel(config=a__   )
											model.to(a__   )
											model.eval()
											__a					:						Optional[Any]      =					model(a__   )
											self.parent.assertEqual(result.last_hidden_state.shape ,					(self.batch_size, self.seq_length, self.hidden_size)   )



						def        UpperCAmelCase__					(self:					Optional[Any] ,					__UpperCAmelCase:					str ,					__UpperCAmelCase:					Union[str, Any] ,					__UpperCAmelCase:					Optional[int]   )    ->     str:




											'''simple docstring'''



											__a					:						Optional[int]      =					self.num_labels
											__a					:						List[Any]      =					DPTForDepthEstimation(a__   )
											model.to(a__   )
											model.eval()
											__a					:						str      =					model(a__   )
											self.parent.assertEqual(result.predicted_depth.shape ,					(self.batch_size, self.image_size, self.image_size)   )



						def        UpperCAmelCase__					(self:					Optional[Any] ,					__UpperCAmelCase:					Tuple ,					__UpperCAmelCase:					Any ,					__UpperCAmelCase:					Tuple   )    ->     List[Any]:




											'''simple docstring'''



											__a					:						List[Any]      =					self.num_labels
											__a					:						Optional[int]      =					DPTForSemanticSegmentation(a__   )
											model.to(a__   )
											model.eval()
											__a					:						List[Any]      =					model(a__ ,					labels=a__   )
											self.parent.assertEqual(
											    result.logits.shape ,					(self.batch_size, self.num_labels, self.image_size, self.image_size)   )



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




											'''simple docstring'''



											__a					:						Tuple      =					self.prepare_config_and_inputs()
											__a					:						Optional[Any]      =					config_and_inputs
											__a					:						Tuple      =					{'''pixel_values''': pixel_values}
											return config, inputs_dict




@require_torch
class 							snake_case_       (    lowerCamelCase__		,							lowerCamelCase__		,							unittest.TestCase      ):

						"""simple docstring"""



						snake_case__        =      (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
						snake_case__        =      (
						    {
						        """depth-estimation""": DPTForDepthEstimation,
						        """feature-extraction""": DPTModel,
						        """image-segmentation""": DPTForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						snake_case__        =      False
						snake_case__        =      False
						snake_case__        =      False



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




											'''simple docstring'''



											__a					:						Optional[int]      =					DPTModelTester(self   )
											__a					:						Tuple      =					ConfigTester(self ,					config_class=a__ ,					has_text_modality=a__ ,					hidden_size=37   )



						def        UpperCAmelCase__					(self:					Tuple   )    ->     List[Any]:




											'''simple docstring'''



											self.config_tester.run_common_tests()



						@unittest.skip(reason="DPT does not use inputs_embeds"   )
						def        UpperCAmelCase__					(self:					Dict   )    ->     Union[str, Any]:




											'''simple docstring'''



											pass



						def        UpperCAmelCase__					(self:					Dict   )    ->     Optional[int]:




											'''simple docstring'''



											__a					:						Union[str, Any]      =					self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__a					:						str      =					model_class(a__   )
																self.assertIsInstance(model.get_input_embeddings() ,					(nn.Module)   )
																__a					:						str      =					model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(a__ ,					nn.Linear   )   )



						def        UpperCAmelCase__					(self:					Optional[Any]   )    ->     Union[str, Any]:




											'''simple docstring'''



											__a					:						Any      =					self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__a					:						List[str]      =					model_class(a__   )
																__a					:						Optional[Any]      =					inspect.signature(model.forward   )
																# signature.parameters is an OrderedDict => so arg_names order is deterministic
																__a					:						Union[str, Any]      =					[*signature.parameters.keys()]

																__a					:						Tuple      =					['''pixel_values''']
																self.assertListEqual(arg_names[:1] ,					a__   )



						def        UpperCAmelCase__					(self:					List[Any]   )    ->     Tuple:




											'''simple docstring'''



											__a					:						Tuple      =					self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*a__   )



						def        UpperCAmelCase__					(self:					List[str]   )    ->     Optional[int]:




											'''simple docstring'''



											__a					:						List[str]      =					self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_depth_estimation(*a__   )



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




											'''simple docstring'''



											__a					:						Optional[Any]      =					self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*a__   )



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




											'''simple docstring'''



											for model_class in self.all_model_classes:
																if model_class.__name__ == "DPTForDepthEstimation":
																					continue

																__a					:						int      =					self.model_tester.prepare_config_and_inputs_for_common()
																__a					:						Any      =					True

																if model_class in get_values(a__   ):
																					continue

																__a					:						Optional[int]      =					model_class(a__   )
																model.to(a__   )
																model.train()
																__a					:						Optional[Any]      =					self._prepare_for_class(a__ ,					a__ ,					return_labels=a__   )
																__a					:						List[Any]      =					model(**a__   ).loss
																loss.backward()



						def        UpperCAmelCase__					(self:					Dict   )    ->     Optional[int]:




											'''simple docstring'''



											for model_class in self.all_model_classes:
																if model_class.__name__ == "DPTForDepthEstimation":
																					continue

																__a					:						Union[str, Any]      =					self.model_tester.prepare_config_and_inputs_for_common()
																__a					:						Tuple      =					False
																__a					:						str      =					True

																if model_class in get_values(a__   ) or not model_class.supports_gradient_checkpointing:
																					continue
																__a					:						Any      =					model_class(a__   )
																model.to(a__   )
																model.gradient_checkpointing_enable()
																model.train()
																__a					:						List[Any]      =					self._prepare_for_class(a__ ,					a__ ,					return_labels=a__   )
																__a					:						Optional[int]      =					model(**a__   ).loss
																loss.backward()



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




											'''simple docstring'''



											__a					:						Union[str, Any]      =					self.model_tester.prepare_config_and_inputs_for_common()

											__a					:						Any      =					_config_zero_init(a__   )
											for model_class in self.all_model_classes:
																__a					:						Union[str, Any]      =					model_class(config=a__   )
																# Skip the check for the backbone
																__a					:						Union[str, Any]      =					[]
																for name, module in model.named_modules():
																					if module.__class__.__name__ == "DPTViTHybridEmbeddings":
																										__a					:						List[Any]      =					[f'{name}.{key}' for key in module.state_dict().keys()]
																										break

																for name, param in model.named_parameters():
																					if param.requires_grad:
																										if name in backbone_params:
																															continue
																										self.assertIn(
																										    ((param.data.mean() * 1E9).round() / 1E9).item() ,					[0.0, 1.0] ,					msg=f'Parameter {name} of model {model_class} seems not properly initialized' ,					)



						@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."   )
						def        UpperCAmelCase__					(self:					str   )    ->     Optional[int]:




											'''simple docstring'''



											pass



						@slow
						def        UpperCAmelCase__					(self:					Optional[int]   )    ->     List[Any]:




											'''simple docstring'''



											for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
																__a					:						List[Any]      =					DPTModel.from_pretrained(a__   )
																self.assertIsNotNone(a__   )



						def        UpperCAmelCase__					(self:					List[str]   )    ->     Optional[int]:




											'''simple docstring'''



											__a					:						str      =					self.model_tester.prepare_config_and_inputs_for_common()
											__a					:						Dict      =					'''add'''
											with self.assertRaises(a__   ):
																__a					:						List[Any]      =					DPTForDepthEstimation(a__   )







def     a_   ()				->						Union[str, Any]:



					"""simple docstring"""
					__a					:						Tuple      =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
					return image




@require_torch
@require_vision
@slow
class 							snake_case_       (    unittest.TestCase      ):

						"""simple docstring"""



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




											'''simple docstring'''



											__a					:						str      =					DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas"   )
											__a					:						List[str]      =					DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas"   ).to(a__   )

											__a					:						Any      =					prepare_img()
											__a					:						str      =					image_processor(images=a__ ,					return_tensors="pt"   ).to(a__   )

											# forward pass
											with torch.no_grad():
																__a					:						Tuple      =					model(**a__   )
																__a					:						List[Any]      =					outputs.predicted_depth

											# verify the predicted depth
											__a					:						Any      =					torch.Size((1, 384, 384)   )
											self.assertEqual(predicted_depth.shape ,					a__   )

											__a					:						List[str]      =					torch.tensor(
											    [[[5.64_37, 5.61_46, 5.65_11], [5.43_71, 5.56_49, 5.59_58], [5.52_15, 5.51_84, 5.52_93]]]   ).to(a__   )

											self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 ,					a__ ,					atol=1E-4   )   )












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:
       _lowerCamelCase      							=   False

if is_vision_available():
       from PIL import Image

       from transformers import PixaStructImageProcessor







class       __A							(   unittest.TestCase	):




      """simple docstring"""







      def __init__(		self   ,				a__   ,				a__=7   ,				a__=3   ,				a__=18   ,				a__=30   ,				a__=400   ,				a__=None   ,				a__=True   ,				a__=True   ,				a__=None   ,				):



             """simple docstring"""





             _lowerCamelCase				:  str						=		size if size is not None else {'''height''': 20, '''width''': 20}
             _lowerCamelCase				:  int						=		parent
             _lowerCamelCase				:  Tuple						=		batch_size
             _lowerCamelCase				:  Union[str, Any]						=		num_channels
             _lowerCamelCase				:  Tuple						=		image_size
             _lowerCamelCase				:  Dict						=		min_resolution
             _lowerCamelCase				:  int						=		max_resolution
             _lowerCamelCase				:  Dict						=		size
             _lowerCamelCase				:  Dict						=		do_normalize
             _lowerCamelCase				:  List[Any]						=		do_convert_rgb
             _lowerCamelCase				:  Optional[int]						=		[512, 1024, 2048, 4096]
             _lowerCamelCase				:  Optional[int]						=		patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}


      def 					__snake_case      (		self):



             """simple docstring"""





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



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Dict						=		'''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
             _lowerCamelCase				:  Union[str, Any]						=		Image.open(requests.get(a__   ,				stream=a__).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	):




      """simple docstring"""







      UpperCAmelCase__							=   PixaStructImageProcessor if is_vision_available() else None


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  int						=		PixaStructImageProcessingTester(self)


      @property
      def 					__snake_case      (		self):



             """simple docstring"""





             return self.image_processor_tester.prepare_image_processor_dict()


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  int						=		self.image_processing_class(**self.image_processor_dict)
             self.assertTrue(hasattr(a__   ,				'''do_normalize'''))
             self.assertTrue(hasattr(a__   ,				'''do_convert_rgb'''))


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Any						=		self.image_processor_tester.prepare_dummy_image()

             _lowerCamelCase				:  List[Any]						=		self.image_processing_class(**self.image_processor_dict)
             _lowerCamelCase				:  Optional[int]						=		2048

             _lowerCamelCase				:  Any						=		image_processor(a__   ,				return_tensors='''pt'''   ,				max_patches=a__)
             self.assertTrue(torch.allclose(inputs.flattened_patches.mean()   ,				torch.tensor(0.0606)   ,				atol=1e-3   ,				rtol=1e-3))


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Dict						=		self.image_processing_class(**self.image_processor_dict)
             # create random PIL images
             _lowerCamelCase				:  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
             _lowerCamelCase				:  Optional[Any]						=		(
                 (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				:  Optional[int]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Dict						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Dict						=		self.image_processing_class(**self.image_processor_dict)
             # create random PIL images
             _lowerCamelCase				:  Optional[int]						=		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=a__)
             for image in image_inputs:
                    self.assertIsInstance(a__   ,				Image.Image)

             # Test not batched input
             _lowerCamelCase				:  List[str]						=		(
                 (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
                 * self.image_processor_tester.num_channels
             ) + 2

             _lowerCamelCase				:  Dict						=		True

             for max_patch in self.image_processor_tester.max_patches:
                    # Test not batched input
                    with self.assertRaises(a__):
                           _lowerCamelCase				:  List[Any]						=		image_processor(
                               image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches

                    _lowerCamelCase				:  List[Any]						=		'''Hello'''

                    _lowerCamelCase				:  int						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__   ,				header_text=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Dict						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__   ,				header_text=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		self.image_processing_class(**self.image_processor_dict)
             # create random numpy tensors
             _lowerCamelCase				:  Tuple						=		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=a__   ,				numpify=a__)
             for image in image_inputs:
                    self.assertIsInstance(a__   ,				np.ndarray)

             _lowerCamelCase				:  Any						=		(
                 (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				:  List[str]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Tuple						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Optional[int]						=		self.image_processing_class(**self.image_processor_dict)
             # create random PyTorch tensors
             _lowerCamelCase				:  str						=		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
             _lowerCamelCase				:  Tuple						=		(
                 (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				:  Optional[int]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  List[str]						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).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	):




      """simple docstring"""







      UpperCAmelCase__							=   PixaStructImageProcessor if is_vision_available() else None


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Optional[Any]						=		PixaStructImageProcessingTester(self   ,				num_channels=4)
             _lowerCamelCase				:  Union[str, Any]						=		3


      @property
      def 					__snake_case      (		self):



             """simple docstring"""





             return self.image_processor_tester.prepare_image_processor_dict()


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  str						=		self.image_processing_class(**self.image_processor_dict)
             self.assertTrue(hasattr(a__   ,				'''do_normalize'''))
             self.assertTrue(hasattr(a__   ,				'''do_convert_rgb'''))



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		self.image_processing_class(**self.image_processor_dict)
             # create random PIL images
             _lowerCamelCase				:  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
             _lowerCamelCase				:  List[Any]						=		(
                 (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				:  Union[str, Any]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Union[str, Any]						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)

