





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_torch_available,
)


SCREAMING_SNAKE_CASE__							:      Optional[Any]         =    {
    """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCRConfig"""],
    """processing_trocr""": ["""TrOCRProcessor"""],
}


try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  SCREAMING_SNAKE_CASE__							:      List[str]         =    [
      """TROCR_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """TrOCRForCausalLM""",
      """TrOCRPreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
  from .processing_trocr import TrOCRProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel

else:
  import sys

  SCREAMING_SNAKE_CASE__							:      List[Any]         =    _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)








import copy
import os
from typing import Union

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


SCREAMING_SNAKE_CASE__							:      Tuple         =    logging.get_logger(__name__)

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







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    Optional[int]  		=					"""pix2struct_text_model"""
   _UpperCamelCase			:    Dict  		=					["""past_key_values"""]
   _UpperCamelCase			:    Union[str, Any]  		=					{
       """hidden_size""": """hidden_size""",
       """num_attention_heads""": """num_heads""",
       """num_hidden_layers""": """num_layers""",
   }





   def __init__(			self       ,      snake_case=50_244       ,      snake_case=768       ,      snake_case=64       ,      snake_case=2_048       ,      snake_case=12       ,      snake_case=12       ,      snake_case=32       ,      snake_case=128       ,      snake_case=0.1       ,      snake_case=1E-6       ,      snake_case=1.0       ,      snake_case="gelu_new"       ,      snake_case=0       ,      snake_case=False       ,      snake_case=0       ,      snake_case=1       ,      snake_case=False       ,      snake_case=True       ,      **snake_case       ,      )					->	Dict:
      """simple docstring"""





      a__						:    Tuple   		=	vocab_size
      a__						:    List[str]   		=	hidden_size
      a__						:    Optional[Any]   		=	d_kv
      a__						:    List[str]   		=	d_ff
      a__						:    Optional[int]   		=	num_layers
      a__						:    Tuple   		=	num_heads
      a__						:    List[Any]   		=	relative_attention_num_buckets
      a__						:    Optional[int]   		=	relative_attention_max_distance
      a__						:    Optional[int]   		=	dropout_rate
      a__						:    List[Any]   		=	layer_norm_epsilon
      a__						:    List[str]   		=	initializer_factor
      a__						:    Any   		=	use_cache

      a__						:    Any   		=	eos_token_id
      a__						:    List[Any]   		=	decoder_start_token_id

      # for backwards compatibility
      a__						:    Tuple   		=	dense_act_fn

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





   @classmethod
   def 						_snake_case			(			cls       ,      snake_case       ,      **snake_case   )					->	"PretrainedConfig":
      """simple docstring"""





      cls._set_token_in_kwargs(snake_case   )

      a__		,  a__						:    Optional[Any]   		=	cls.get_config_dict(snake_case       ,      **snake_case   )

      # get the text config dict if we are loading from Pix2StructConfig
      if config_dict.get("model_type"   ) == "pix2struct":
         a__						:    Optional[int]   		=	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(snake_case       ,      **snake_case   )







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    int  		=					"""pix2struct_vision_model"""





   def __init__(			self       ,      snake_case=768       ,      snake_case=768       ,      snake_case=2_048       ,      snake_case=64       ,      snake_case=12       ,      snake_case=12       ,      snake_case="gelu_new"       ,      snake_case=1E-6       ,      snake_case=0.0       ,      snake_case=0.0       ,      snake_case=1E-10       ,      snake_case=1.0       ,      snake_case=4_096       ,      snake_case=32       ,      snake_case=128       ,      **snake_case       ,      )					->	Optional[Any]:
      """simple docstring"""





      super().__init__(**snake_case   )

      a__						:    Optional[Any]   		=	hidden_size
      a__						:    Tuple   		=	patch_embed_hidden_size
      a__						:    Tuple   		=	d_ff
      a__						:    List[Any]   		=	dropout_rate
      a__						:    Optional[Any]   		=	num_hidden_layers
      a__						:    Optional[Any]   		=	num_attention_heads
      a__						:    List[str]   		=	initializer_range
      a__						:    List[str]   		=	initializer_factor
      a__						:    List[Any]   		=	attention_dropout
      a__						:    Optional[int]   		=	layer_norm_eps
      a__						:    int   		=	dense_act_fn
      a__						:    Optional[Any]   		=	seq_len
      a__						:    List[Any]   		=	relative_attention_num_buckets
      a__						:    int   		=	relative_attention_max_distance
      a__						:    int   		=	d_kv





   @classmethod
   def 						_snake_case			(			cls       ,      snake_case       ,      **snake_case   )					->	"PretrainedConfig":
      """simple docstring"""





      cls._set_token_in_kwargs(snake_case   )

      a__		,  a__						:    int   		=	cls.get_config_dict(snake_case       ,      **snake_case   )

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







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    List[Any]  		=					"""pix2struct"""
   _UpperCamelCase			:    Dict  		=					True





   def __init__(			self       ,      snake_case=None       ,      snake_case=None       ,      snake_case=1.0       ,      snake_case=0.02       ,      snake_case=False       ,      snake_case=False       ,      snake_case=True       ,      **snake_case       ,      )					->	Optional[int]:
      """simple docstring"""





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

      if text_config is None:
         a__						:    Optional[Any]   		=	{}
         logger.info("text_config is None. Initializing the Pix2StructTextConfig with default values."   )

      if vision_config is None:
         a__						:    List[Any]   		=	{}
         logger.info("vision_config is None. Initializing the Pix2StructVisionConfig with default values."   )

      a__						:    List[str]   		=	PixaStructTextConfig(**snake_case   )
      a__						:    List[str]   		=	PixaStructVisionConfig(**snake_case   )

      a__						:    Tuple   		=	self.text_config.decoder_start_token_id
      a__						:    int   		=	self.text_config.pad_token_id
      a__						:    List[Any]   		=	self.text_config.eos_token_id

      a__						:    str   		=	initializer_factor
      a__						:    Dict   		=	initializer_range

      a__						:    Optional[int]   		=	self.initializer_range
      a__						:    Union[str, Any]   		=	self.initializer_range

      a__						:    Union[str, Any]   		=	is_vqa





   @classmethod
   def 						_snake_case			(			cls       ,      snake_case       ,      snake_case       ,      **snake_case   )					->	Dict:
      """simple docstring"""





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





   def 						_snake_case			(			self   )					->	int:
      """simple docstring"""





      a__						:    Tuple   		=	copy.deepcopy(self.__dict__   )
      a__						:    List[str]   		=	self.text_config.to_dict()
      a__						:    Union[str, Any]   		=	self.vision_config.to_dict()
      a__						:    List[Any]   		=	self.__class__.model_type
      return output

