




'''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     =False

if is_vision_available():
   from PIL import Image

   from transformers import PixaStructImageProcessor


class 			_a  (	unittest.TestCase ):
       def __init__(	self						:	Optional[int]   ,				lowercase						:	Any   ,				lowercase						:	List[Any]=7   ,				lowercase						:	Dict=3   ,				lowercase						:	Optional[Any]=18   ,				lowercase						:	Dict=30   ,				lowercase						:	Optional[int]=400   ,				lowercase						:	Union[str, Any]=None   ,				lowercase						:	List[Any]=True   ,				lowercase						:	Optional[int]=True   ,				lowercase						:	List[Any]=None   ,				):



           '''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     A      (	self						:	Optional[Any]				):



           '''simple docstring'''

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







       def     A      (	self						:	List[str]				):



           '''simple docstring'''

           UpperCAmelCase			       =		'''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
           UpperCAmelCase			       =		Image.open(requests.get(lowercase   ,				stream=lowercase				).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  (	__a							,							unittest.TestCase ):
       __a				:     Optional[Any]   				=					PixaStructImageProcessor if is_vision_available() else None
       def     A      (	self						:	List[str]				):



           '''simple docstring'''

           UpperCAmelCase			       =		PixaStructImageProcessingTester(self				)
       @property
       def     A      (	self						:	Tuple				):



           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()
       def     A      (	self						:	Tuple				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.image_processing_class(**self.image_processor_dict				)
           self.assertTrue(hasattr(lowercase   ,				'''do_normalize'''				)				)
           self.assertTrue(hasattr(lowercase   ,				'''do_convert_rgb'''				)				)
       def     A      (	self						:	Any				):



           '''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(lowercase   ,				return_tensors='''pt'''   ,				max_patches=lowercase				)
           self.assertTrue(torch.allclose(inputs.flattened_patches.mean()   ,				torch.tensor(0.0606				)   ,				atol=1E-3   ,				rtol=1E-3				)				)
       def     A      (	self						:	List[str]				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.image_processing_class(**self.image_processor_dict				)
           # create random PIL images
           UpperCAmelCase			       =		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=lowercase				)
           for image in image_inputs:
               self.assertIsInstance(lowercase   ,				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=lowercase				).flattened_patches
               self.assertEqual(
                   encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

               # Test batched
               UpperCAmelCase			       =		image_processor(
                   lowercase   ,				return_tensors='''pt'''   ,				max_patches=lowercase				).flattened_patches
               self.assertEqual(
                   encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)
       def     A      (	self						:	int				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.image_processing_class(**self.image_processor_dict				)
           # create random PIL images
           UpperCAmelCase			       =		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=lowercase				)
           for image in image_inputs:
               self.assertIsInstance(lowercase   ,				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(lowercase				):
                   UpperCAmelCase			       =		image_processor(
                       image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=lowercase				).flattened_patches

               UpperCAmelCase			       =		'''Hello'''

               UpperCAmelCase			       =		image_processor(
                   image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=lowercase   ,				header_text=lowercase				).flattened_patches
               self.assertEqual(
                   encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

               # Test batched
               UpperCAmelCase			       =		image_processor(
                   lowercase   ,				return_tensors='''pt'''   ,				max_patches=lowercase   ,				header_text=lowercase				).flattened_patches
               self.assertEqual(
                   encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)
       def     A      (	self						:	List[Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.image_processing_class(**self.image_processor_dict				)
           # create random numpy tensors
           UpperCAmelCase			       =		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=lowercase   ,				numpify=lowercase				)
           for image in image_inputs:
               self.assertIsInstance(lowercase   ,				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=lowercase				).flattened_patches
               self.assertEqual(
                   encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

               # Test batched
               UpperCAmelCase			       =		image_processor(
                   lowercase   ,				return_tensors='''pt'''   ,				max_patches=lowercase				).flattened_patches
               self.assertEqual(
                   encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)







       def     A      (	self						:	List[Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.image_processing_class(**self.image_processor_dict				)
           # create random PyTorch tensors
           UpperCAmelCase			       =		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=lowercase   ,				torchify=lowercase				)
           for image in image_inputs:
               self.assertIsInstance(lowercase   ,				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=lowercase				).flattened_patches
               self.assertEqual(
                   encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

               # Test batched
               UpperCAmelCase			       =		image_processor(
                   lowercase   ,				return_tensors='''pt'''   ,				max_patches=lowercase				).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  (	__a							,							unittest.TestCase ):
       __a				:     Tuple   				=					PixaStructImageProcessor if is_vision_available() else None
       def     A      (	self						:	Dict				):



           '''simple docstring'''

           UpperCAmelCase			       =		PixaStructImageProcessingTester(self   ,				num_channels=4				)
           UpperCAmelCase			       =		3
       @property
       def     A      (	self						:	int				):



           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()
       def     A      (	self						:	List[Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.image_processing_class(**self.image_processor_dict				)
           self.assertTrue(hasattr(lowercase   ,				'''do_normalize'''				)				)
           self.assertTrue(hasattr(lowercase   ,				'''do_convert_rgb'''				)				)







       def     A      (	self						:	List[Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		self.image_processing_class(**self.image_processor_dict				)
           # create random PIL images
           UpperCAmelCase			       =		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=lowercase				)
           for image in image_inputs:
               self.assertIsInstance(lowercase   ,				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=lowercase				).flattened_patches
               self.assertEqual(
                   encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

               # Test batched
               UpperCAmelCase			       =		image_processor(
                   lowercase   ,				return_tensors='''pt'''   ,				max_patches=lowercase				).flattened_patches
               self.assertEqual(
                   encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)









from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


A__  :  List[str]								=					logging.get_logger(__name__)



class 				__snake_case						(     UpperCamelCase_						,UpperCamelCase_						):
							_a			      = '''maskformer-swin'''

							_a			      = {
							    '''num_attention_heads''': '''num_heads''',
							    '''num_hidden_layers''': '''num_layers''',
							}




							def __init__(       self     :       Union[str, Any]				,				A_     :       Dict=2_2_4				,				A_     :       Optional[Any]=4				,				A_     :       List[str]=3				,				A_     :       str=9_6				,				A_     :       Optional[Any]=[2, 2, 6, 2]				,				A_     :       Tuple=[3, 6, 1_2, 2_4]				,				A_     :       List[Any]=7				,				A_     :       List[Any]=4.0				,				A_     :       List[str]=True				,				A_     :       Dict=0.0				,				A_     :       int=0.0				,				A_     :       str=0.1				,				A_     :       Optional[int]="gelu"				,				A_     :       List[Any]=False				,				A_     :       int=0.02				,				A_     :       int=1e-5				,				A_     :       Optional[int]=None				,				A_     :       List[str]=None				,				**A_     :       List[Any]				,				):
									super().__init__(**A_)

									lowerCAmelCase_			:     Dict									= image_size
									lowerCAmelCase_			:     Optional[Any]									= patch_size
									lowerCAmelCase_			:     Tuple									= num_channels
									lowerCAmelCase_			:     Any									= embed_dim
									lowerCAmelCase_			:     List[str]									= depths
									lowerCAmelCase_			:     Union[str, Any]									= len(A_)
									lowerCAmelCase_			:     List[str]									= num_heads
									lowerCAmelCase_			:     Dict									= window_size
									lowerCAmelCase_			:     Optional[int]									= mlp_ratio
									lowerCAmelCase_			:     Dict									= qkv_bias
									lowerCAmelCase_			:     str									= hidden_dropout_prob
									lowerCAmelCase_			:     List[str]									= attention_probs_dropout_prob
									lowerCAmelCase_			:     Optional[int]									= drop_path_rate
									lowerCAmelCase_			:     Any									= hidden_act
									lowerCAmelCase_			:     str									= use_absolute_embeddings
									lowerCAmelCase_			:     List[str]									= layer_norm_eps
									lowerCAmelCase_			:     int									= initializer_range
									# we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
									# this indicates the channel dimension after the last stage of the model
									lowerCAmelCase_			:     str									= int(embed_dim * 2 ** (len(A_) - 1))
									lowerCAmelCase_			:     Optional[Any]									= ['''stem'''] + [F"""stage{idx}""" for idx in range(1				,				len(A_) + 1)]
									lowerCAmelCase_					,  lowerCAmelCase_			:     int									= get_aligned_output_features_output_indices(
									    out_features=A_				,				out_indices=A_				,				stage_names=self.stage_names)





