



import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase__						:	Any					=logging.get_logger(__name__)

lowerCAmelCase__						:	Tuple					={
    '''google/pix2struct-textcaps-base''': (
        '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json'''
    ),
}

class   UpperCAmelCase_    (  __A			):

						'''simple docstring'''




						UpperCamelCase__     :					List[Any]							    =    '''pix2struct_text_model'''
						UpperCamelCase__     :					Tuple							    =    ['''past_key_values''']
						UpperCamelCase__     :					Tuple							    =    {
						    '''hidden_size''': '''hidden_size''',
						    '''num_attention_heads''': '''num_heads''',
						    '''num_hidden_layers''': '''num_layers''',
						}






						def __init__(       self ,				_A=50_244 ,				_A=768 ,				_A=64 ,				_A=2_048 ,				_A=12 ,				_A=12 ,				_A=32 ,				_A=128 ,				_A=0.1 ,				_A=1e-6 ,				_A=1.0 ,				_A="gelu_new" ,				_A=0 ,				_A=False ,				_A=0 ,				_A=1 ,				_A=False ,				_A=True ,				**_A ,				):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE										=   vocab_size
													__SCREAMING_SNAKE_CASE										=   hidden_size
													__SCREAMING_SNAKE_CASE										=   d_kv
													__SCREAMING_SNAKE_CASE										=   d_ff
													__SCREAMING_SNAKE_CASE										=   num_layers
													__SCREAMING_SNAKE_CASE										=   num_heads
													__SCREAMING_SNAKE_CASE										=   relative_attention_num_buckets
													__SCREAMING_SNAKE_CASE										=   relative_attention_max_distance
													__SCREAMING_SNAKE_CASE										=   dropout_rate
													__SCREAMING_SNAKE_CASE										=   layer_norm_epsilon
													__SCREAMING_SNAKE_CASE										=   initializer_factor
													__SCREAMING_SNAKE_CASE										=   use_cache

													__SCREAMING_SNAKE_CASE										=   eos_token_id
													__SCREAMING_SNAKE_CASE										=   decoder_start_token_id

													# for backwards compatibility
													__SCREAMING_SNAKE_CASE										=   dense_act_fn

													super().__init__(
													    pad_token_id=lowerCAmelCase_ ,				eos_token_id=lowerCAmelCase_ ,				decoder_start_token_id=lowerCAmelCase_ ,				tie_word_embeddings=lowerCAmelCase_ ,				is_decoder=lowerCAmelCase_ ,				**lowerCAmelCase_ ,				)






						@classmethod
						def 			_A      (       cls ,				_A ,				**_A						):







													'''simple docstring'''

													cls._set_token_in_kwargs(lowerCAmelCase_						)

													__SCREAMING_SNAKE_CASE										=   cls.get_config_dict(lowerCAmelCase_ ,				**lowerCAmelCase_						)

													# get the text config dict if we are loading from Pix2StructConfig
													if config_dict.get('model_type'						) == "pix2struct":
																				__SCREAMING_SNAKE_CASE										=   config_dict["text_config"]

													if "model_type" in config_dict and hasattr(cls ,				'model_type'						) and config_dict["model_type"] != cls.model_type:
																				logger.warning(
																				    f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
																				    f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""						)

													return cls.from_dict(lowerCAmelCase_ ,				**lowerCAmelCase_						)







class   UpperCAmelCase_    (  __A			):

						'''simple docstring'''




						UpperCamelCase__     :					Union[str, Any]							    =    '''pix2struct_vision_model'''






						def __init__(       self ,				_A=768 ,				_A=768 ,				_A=2_048 ,				_A=64 ,				_A=12 ,				_A=12 ,				_A="gelu_new" ,				_A=1e-6 ,				_A=0.0 ,				_A=0.0 ,				_A=1e-10 ,				_A=1.0 ,				_A=4_096 ,				_A=32 ,				_A=128 ,				**_A ,				):







													'''simple docstring'''

													super().__init__(**lowerCAmelCase_						)

													__SCREAMING_SNAKE_CASE										=   hidden_size
													__SCREAMING_SNAKE_CASE										=   patch_embed_hidden_size
													__SCREAMING_SNAKE_CASE										=   d_ff
													__SCREAMING_SNAKE_CASE										=   dropout_rate
													__SCREAMING_SNAKE_CASE										=   num_hidden_layers
													__SCREAMING_SNAKE_CASE										=   num_attention_heads
													__SCREAMING_SNAKE_CASE										=   initializer_range
													__SCREAMING_SNAKE_CASE										=   initializer_factor
													__SCREAMING_SNAKE_CASE										=   attention_dropout
													__SCREAMING_SNAKE_CASE										=   layer_norm_eps
													__SCREAMING_SNAKE_CASE										=   dense_act_fn
													__SCREAMING_SNAKE_CASE										=   seq_len
													__SCREAMING_SNAKE_CASE										=   relative_attention_num_buckets
													__SCREAMING_SNAKE_CASE										=   relative_attention_max_distance
													__SCREAMING_SNAKE_CASE										=   d_kv






						@classmethod
						def 			_A      (       cls ,				_A ,				**_A						):







													'''simple docstring'''

													cls._set_token_in_kwargs(lowerCAmelCase_						)

													__SCREAMING_SNAKE_CASE										=   cls.get_config_dict(lowerCAmelCase_ ,				**lowerCAmelCase_						)

													# get the vision config dict if we are loading from Pix2StructConfig
													if config_dict.get('model_type'						) == "pix2struct":
																				__SCREAMING_SNAKE_CASE										=   config_dict["vision_config"]

													if "model_type" in config_dict and hasattr(cls ,				'model_type'						) and config_dict["model_type"] != cls.model_type:
																				logger.warning(
																				    f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """
																				    f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""						)

													return cls.from_dict(lowerCAmelCase_ ,				**lowerCAmelCase_						)







class   UpperCAmelCase_    (  __A			):

						'''simple docstring'''




						UpperCamelCase__     :					Union[str, Any]							    =    '''pix2struct'''
						UpperCamelCase__     :					Optional[Any]							    =    True






						def __init__(       self ,				_A=None ,				_A=None ,				_A=1.0 ,				_A=0.0_2 ,				_A=False ,				_A=False ,				_A=True ,				**_A ,				):







													'''simple docstring'''

													super().__init__(tie_word_embeddings=lowerCAmelCase_ ,				is_encoder_decoder=lowerCAmelCase_ ,				**lowerCAmelCase_						)

													if text_config is None:
																				__SCREAMING_SNAKE_CASE										=   {}
																				logger.info('text_config is None. Initializing the Pix2StructTextConfig with default values.'						)

													if vision_config is None:
																				__SCREAMING_SNAKE_CASE										=   {}
																				logger.info('vision_config is None. Initializing the Pix2StructVisionConfig with default values.'						)

													__SCREAMING_SNAKE_CASE										=   PixaStructTextConfig(**lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   PixaStructVisionConfig(**lowerCAmelCase_						)

													__SCREAMING_SNAKE_CASE										=   self.text_config.decoder_start_token_id
													__SCREAMING_SNAKE_CASE										=   self.text_config.pad_token_id
													__SCREAMING_SNAKE_CASE										=   self.text_config.eos_token_id

													__SCREAMING_SNAKE_CASE										=   initializer_factor
													__SCREAMING_SNAKE_CASE										=   initializer_range

													__SCREAMING_SNAKE_CASE										=   self.initializer_range
													__SCREAMING_SNAKE_CASE										=   self.initializer_range

													__SCREAMING_SNAKE_CASE										=   is_vqa






						@classmethod
						def 			_A      (       cls ,				_A ,				_A ,				**_A						):







													'''simple docstring'''

													return cls(text_config=text_config.to_dict() ,				vision_config=vision_config.to_dict() ,				**lowerCAmelCase_						)






						def 			_A      (       self						):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE										=   copy.deepcopy(self.__dict__						)
													__SCREAMING_SNAKE_CASE										=   self.text_config.to_dict()
													__SCREAMING_SNAKE_CASE										=   self.vision_config.to_dict()
													__SCREAMING_SNAKE_CASE										=   self.__class__.model_type
													return output














"""simple docstring"""
import unittest

import numpy as np

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

if is_vision_available():
			from PIL import Image

			from transformers import ViTImageProcessor







class      UpperCamelCase_			(unittest.TestCase	):





	def __init__( self   :					Optional[int]      ,      lowerCAmelCase_   :					Tuple      ,      lowerCAmelCase_   :					List[str]=13      ,      lowerCAmelCase_   :					Union[str, Any]=3      ,      lowerCAmelCase_   :					Union[str, Any]=224      ,      lowerCAmelCase_   :					List[Any]=30      ,      lowerCAmelCase_   :					Any=400      ,      lowerCAmelCase_   :					Any=True      ,      lowerCAmelCase_   :					Dict=None      ,      lowerCAmelCase_   :					int=True      ,      lowerCAmelCase_   :					Any=[0.5, 0.5, 0.5]      ,      lowerCAmelCase_   :					str=[0.5, 0.5, 0.5]      ,      )		->     Dict:
				UpperCAmelCase_	:					int     	=   size if size is not None else {"height": 18, "width": 18}
				UpperCAmelCase_	:					List[Any]     	=   parent
				UpperCAmelCase_	:					int     	=   batch_size
				UpperCAmelCase_	:					Optional[int]     	=   num_channels
				UpperCAmelCase_	:					Dict     	=   image_size
				UpperCAmelCase_	:					Union[str, Any]     	=   min_resolution
				UpperCAmelCase_	:					List[str]     	=   max_resolution
				UpperCAmelCase_	:					Dict     	=   do_resize
				UpperCAmelCase_	:					Optional[int]     	=   size
				UpperCAmelCase_	:					List[str]     	=   do_normalize
				UpperCAmelCase_	:					List[Any]     	=   image_mean
				UpperCAmelCase_	:					Dict     	=   image_std





	def 	_SCREAMING_SNAKE_CASE ( self   :					int		)		->     Union[str, Any]:
				return {
				    "image_mean": self.image_mean,
				    "image_std": self.image_std,
				    "do_normalize": self.do_normalize,
				    "do_resize": self.do_resize,
				    "size": self.size,
				}







@require_torch
@require_vision
class      UpperCamelCase_			(__A							,		unittest.TestCase	):
	__magic_name__       =							ViTImageProcessor if is_vision_available() else None





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]		)		->     Optional[Any]:
				UpperCAmelCase_	:					Optional[Any]     	=   EfficientFormerImageProcessorTester(self		)





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     List[Any]:
				return self.image_proc_tester.prepare_image_processor_dict()





	def 	_SCREAMING_SNAKE_CASE ( self   :					Tuple		)		->     str:
				UpperCAmelCase_	:					Tuple     	=   self.image_processing_class(**self.image_processor_dict		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "image_mean"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "image_std"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "do_normalize"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "do_resize"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "size"		)		)





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





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     int:
				# Initialize image_processor
				UpperCAmelCase_	:					str     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random PIL images
				UpperCAmelCase_	:					int     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      Image.Image		)

				# Test not batched input
				UpperCAmelCase_	:					Optional[Any]     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					str     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )





	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     List[Any]:
				# Initialize image_processor
				UpperCAmelCase_	:					List[str]     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random numpy tensors
				UpperCAmelCase_	:					List[str]     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_      ,      numpify=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      np.ndarray		)

				# Test not batched input
				UpperCAmelCase_	:					str     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					Dict     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     List[Any]:
				# Initialize image_processor
				UpperCAmelCase_	:					Optional[Any]     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random PyTorch tensors
				UpperCAmelCase_	:					Dict     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_      ,      torchify=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      torch.Tensor		)

				# Test not batched input
				UpperCAmelCase_	:					Optional[int]     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					Optional[int]     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )



