



import copy
import os
from typing import Union

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


UpperCAmelCase__   =       logging.get_logger(__name__)

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







class 			__lowerCAmelCase    (			A						):
			UpperCamelCase   					=     '''pix2struct_text_model'''
			UpperCamelCase   					=     ['''past_key_values''']
			UpperCamelCase   					=     {
			    '''hidden_size''': '''hidden_size''',
			    '''num_attention_heads''': '''num_heads''',
			    '''num_hidden_layers''': '''num_layers''',
			}



			def __init__(						self   :  Optional[Any] ,		A   :  str=5_02_44 ,		A   :  str=7_68 ,		A   :  Optional[int]=64 ,		A   :  Optional[Any]=20_48 ,		A   :  Tuple=12 ,		A   :  List[str]=12 ,		A   :  List[Any]=32 ,		A   :  Tuple=1_28 ,		A   :  Optional[Any]=0.1 ,		A   :  Optional[Any]=1E-6 ,		A   :  int=1.0 ,		A   :  Optional[Any]="gelu_new" ,		A   :  Union[str, Any]=0 ,		A   :  Any=False ,		A   :  List[str]=0 ,		A   :  List[str]=1 ,		A   :  Any=False ,		A   :  List[Any]=True ,		**A   :  Optional[Any] ,		)   ->    int:



						"""simple docstring"""






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

						_UpperCAmelCase		       =   eos_token_id
						_UpperCAmelCase		       =   decoder_start_token_id

						# for backwards compatibility
						_UpperCAmelCase		       =   dense_act_fn

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



			@classmethod
			def     _lowerCamelCase       (						cls   :  Any ,		A   :  List[str] ,		**A   :  Tuple)   ->    "PretrainedConfig":



						"""simple docstring"""






						cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE)

						_UpperCAmelCase		       =   cls.get_config_dict(_SCREAMING_SNAKE_CASE ,		**_SCREAMING_SNAKE_CASE)

						# get the text config dict if we are loading from Pix2StructConfig
						if config_dict.get('model_type') == "pix2struct":
									_UpperCAmelCase		       =   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(_SCREAMING_SNAKE_CASE ,		**_SCREAMING_SNAKE_CASE)







class 			__lowerCAmelCase    (			A						):
			UpperCamelCase   					=     '''pix2struct_vision_model'''



			def __init__(						self   :  Optional[int] ,		A   :  str=7_68 ,		A   :  Optional[Any]=7_68 ,		A   :  Union[str, Any]=20_48 ,		A   :  Dict=64 ,		A   :  List[Any]=12 ,		A   :  str=12 ,		A   :  List[Any]="gelu_new" ,		A   :  List[str]=1E-6 ,		A   :  Optional[int]=0.0 ,		A   :  Tuple=0.0 ,		A   :  Tuple=1E-10 ,		A   :  int=1.0 ,		A   :  List[Any]=40_96 ,		A   :  Optional[Any]=32 ,		A   :  int=1_28 ,		**A   :  str ,		)   ->    Optional[int]:



						"""simple docstring"""






						super().__init__(**_SCREAMING_SNAKE_CASE)

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



			@classmethod
			def     _lowerCamelCase       (						cls   :  List[Any] ,		A   :  Any ,		**A   :  Any)   ->    "PretrainedConfig":



						"""simple docstring"""






						cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE)

						_UpperCAmelCase		       =   cls.get_config_dict(_SCREAMING_SNAKE_CASE ,		**_SCREAMING_SNAKE_CASE)

						# get the vision config dict if we are loading from Pix2StructConfig
						if config_dict.get('model_type') == "pix2struct":
									_UpperCAmelCase		       =   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(_SCREAMING_SNAKE_CASE ,		**_SCREAMING_SNAKE_CASE)







class 			__lowerCAmelCase    (			A						):
			UpperCamelCase   					=     '''pix2struct'''
			UpperCamelCase   					=     True



			def __init__(						self   :  List[Any] ,		A   :  int=None ,		A   :  Any=None ,		A   :  Union[str, Any]=1.0 ,		A   :  Union[str, Any]=0.0_2 ,		A   :  Dict=False ,		A   :  int=False ,		A   :  Optional[Any]=True ,		**A   :  Optional[int] ,		)   ->    Any:



						"""simple docstring"""






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

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

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

						_UpperCAmelCase		       =   PixaStructTextConfig(**_SCREAMING_SNAKE_CASE)
						_UpperCAmelCase		       =   PixaStructVisionConfig(**_SCREAMING_SNAKE_CASE)

						_UpperCAmelCase		       =   self.text_config.decoder_start_token_id
						_UpperCAmelCase		       =   self.text_config.pad_token_id
						_UpperCAmelCase		       =   self.text_config.eos_token_id

						_UpperCAmelCase		       =   initializer_factor
						_UpperCAmelCase		       =   initializer_range

						_UpperCAmelCase		       =   self.initializer_range
						_UpperCAmelCase		       =   self.initializer_range

						_UpperCAmelCase		       =   is_vqa



			@classmethod
			def     _lowerCamelCase       (						cls   :  Optional[Any] ,		A   :  Optional[Any] ,		A   :  Optional[int] ,		**A   :  Optional[int])   ->    Union[str, Any]:



						"""simple docstring"""






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



			def     _lowerCamelCase       (						self   :  Optional[Any])   ->    Dict:



						"""simple docstring"""






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




from typing import Dict

from .base import GenericTensor, Pipeline






class   _lowerCamelCase (					UpperCamelCase			):




       """simple docstring"""



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE=None				,       _SCREAMING_SNAKE_CASE=None				,       _SCREAMING_SNAKE_CASE=None				,       **_SCREAMING_SNAKE_CASE		)->List[Any]:




         '''simple docstring'''





         if tokenize_kwargs is None:
           A_      :				Optional[int]		     =					{}

         if truncation is not None:
           if "truncation" in tokenize_kwargs:
             raise ValueError(
                 '''truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)'''		)
           A_      :				List[str]		     =					truncation

         A_      :				str		     =					tokenize_kwargs

         A_      :				Optional[Any]		     =					{}
         if return_tensors is not None:
           A_      :				Union[str, Any]		     =					return_tensors

         return preprocess_params, {}, postprocess_params



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       **_SCREAMING_SNAKE_CASE		)->Dict[str, GenericTensor]:




         '''simple docstring'''





         A_      :				str		     =					self.framework
         A_      :				Any		     =					self.tokenizer(_SCREAMING_SNAKE_CASE				,       return_tensors=_SCREAMING_SNAKE_CASE				,       **_SCREAMING_SNAKE_CASE		)
         return model_inputs



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




         '''simple docstring'''





         A_      :				Optional[int]		     =					self.model(**_SCREAMING_SNAKE_CASE		)
         return model_outputs



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE=False		)->List[Any]:




         '''simple docstring'''





         if return_tensors:
           return model_outputs[0]
         if self.framework == "pt":
           return model_outputs[0].tolist()
         elif self.framework == "tf":
           return model_outputs[0].numpy().tolist()







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




         '''simple docstring'''





         return super().__call__(*_SCREAMING_SNAKE_CASE				,       **_SCREAMING_SNAKE_CASE		)




