



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_		(  snake_case_							):
       UpperCAmelCase__				:					str        =  '''pix2struct_text_model'''
       UpperCAmelCase__				:					Optional[int]        =  ['''past_key_values''']
       UpperCAmelCase__				:					Union[str, Any]        =  {
           '''hidden_size''': '''hidden_size''',
           '''num_attention_heads''': '''num_heads''',
           '''num_hidden_layers''': '''num_layers''',
       }
       def __init__(			self,			SCREAMING_SNAKE_CASE_=5_0244,			SCREAMING_SNAKE_CASE_=768,			SCREAMING_SNAKE_CASE_=64,			SCREAMING_SNAKE_CASE_=2048,			SCREAMING_SNAKE_CASE_=12,			SCREAMING_SNAKE_CASE_=12,			SCREAMING_SNAKE_CASE_=32,			SCREAMING_SNAKE_CASE_=128,			SCREAMING_SNAKE_CASE_=0.1,			SCREAMING_SNAKE_CASE_=1e-6,			SCREAMING_SNAKE_CASE_=1.0,			SCREAMING_SNAKE_CASE_="gelu_new",			SCREAMING_SNAKE_CASE_=0,			SCREAMING_SNAKE_CASE_=False,			SCREAMING_SNAKE_CASE_=0,			SCREAMING_SNAKE_CASE_=1,			SCREAMING_SNAKE_CASE_=False,			SCREAMING_SNAKE_CASE_=True,			**SCREAMING_SNAKE_CASE_,			)     ->		List[Any]:
          UpperCamelCase    :  str							=	vocab_size
          UpperCamelCase    :  Dict							=	hidden_size
          UpperCamelCase    :  int							=	d_kv
          UpperCamelCase    :  Optional[Any]							=	d_ff
          UpperCamelCase    :  Any							=	num_layers
          UpperCamelCase    :  Optional[Any]							=	num_heads
          UpperCamelCase    :  Tuple							=	relative_attention_num_buckets
          UpperCamelCase    :  Dict							=	relative_attention_max_distance
          UpperCamelCase    :  Union[str, Any]							=	dropout_rate
          UpperCamelCase    :  Any							=	layer_norm_epsilon
          UpperCamelCase    :  Dict							=	initializer_factor
          UpperCamelCase    :  Optional[Any]							=	use_cache

          UpperCamelCase    :  str							=	eos_token_id
          UpperCamelCase    :  List[Any]							=	decoder_start_token_id

          # for backwards compatibility
          UpperCamelCase    :  Optional[int]							=	dense_act_fn

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






       @classmethod
       def 					snake_case_       (			cls,			SCREAMING_SNAKE_CASE_,			**SCREAMING_SNAKE_CASE_       )     ->		"PretrainedConfig":
          cls._set_token_in_kwargs(UpperCamelCase__       )

          UpperCamelCase    :  Any							=	cls.get_config_dict(UpperCamelCase__,			**UpperCamelCase__       )

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






class 				lowerCAmelCase_		(  snake_case_							):
       UpperCAmelCase__				:					str        =  '''pix2struct_vision_model'''
       def __init__(			self,			SCREAMING_SNAKE_CASE_=768,			SCREAMING_SNAKE_CASE_=768,			SCREAMING_SNAKE_CASE_=2048,			SCREAMING_SNAKE_CASE_=64,			SCREAMING_SNAKE_CASE_=12,			SCREAMING_SNAKE_CASE_=12,			SCREAMING_SNAKE_CASE_="gelu_new",			SCREAMING_SNAKE_CASE_=1e-6,			SCREAMING_SNAKE_CASE_=0.0,			SCREAMING_SNAKE_CASE_=0.0,			SCREAMING_SNAKE_CASE_=1e-10,			SCREAMING_SNAKE_CASE_=1.0,			SCREAMING_SNAKE_CASE_=4096,			SCREAMING_SNAKE_CASE_=32,			SCREAMING_SNAKE_CASE_=128,			**SCREAMING_SNAKE_CASE_,			)     ->		Optional[int]:
          super().__init__(**UpperCamelCase__       )

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






       @classmethod
       def 					snake_case_       (			cls,			SCREAMING_SNAKE_CASE_,			**SCREAMING_SNAKE_CASE_       )     ->		"PretrainedConfig":
          cls._set_token_in_kwargs(UpperCamelCase__       )

          UpperCamelCase    :  Optional[int]							=	cls.get_config_dict(UpperCamelCase__,			**UpperCamelCase__       )

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






class 				lowerCAmelCase_		(  snake_case_							):
       UpperCAmelCase__				:					Optional[int]        =  '''pix2struct'''
       UpperCAmelCase__				:					str        =  True
       def __init__(			self,			SCREAMING_SNAKE_CASE_=None,			SCREAMING_SNAKE_CASE_=None,			SCREAMING_SNAKE_CASE_=1.0,			SCREAMING_SNAKE_CASE_=0.02,			SCREAMING_SNAKE_CASE_=False,			SCREAMING_SNAKE_CASE_=False,			SCREAMING_SNAKE_CASE_=True,			**SCREAMING_SNAKE_CASE_,			)     ->		Union[str, Any]:
          super().__init__(tie_word_embeddings=UpperCamelCase__,			is_encoder_decoder=UpperCamelCase__,			**UpperCamelCase__       )

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

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

          UpperCamelCase    :  Optional[int]							=	PixaStructTextConfig(**UpperCamelCase__       )
          UpperCamelCase    :  Any							=	PixaStructVisionConfig(**UpperCamelCase__       )

          UpperCamelCase    :  Any							=	self.text_config.decoder_start_token_id
          UpperCamelCase    :  Dict							=	self.text_config.pad_token_id
          UpperCamelCase    :  List[str]							=	self.text_config.eos_token_id

          UpperCamelCase    :  Optional[Any]							=	initializer_factor
          UpperCamelCase    :  List[Any]							=	initializer_range

          UpperCamelCase    :  List[Any]							=	self.initializer_range
          UpperCamelCase    :  Union[str, Any]							=	self.initializer_range

          UpperCamelCase    :  List[Any]							=	is_vqa
       @classmethod
       def 					snake_case_       (			cls,			SCREAMING_SNAKE_CASE_,			SCREAMING_SNAKE_CASE_,			**SCREAMING_SNAKE_CASE_       )     ->		Tuple:
          return cls(text_config=text_config.to_dict(),			vision_config=vision_config.to_dict(),			**UpperCamelCase__       )






       def 					snake_case_       (			self       )     ->		Optional[int]:
          UpperCamelCase    :  List[str]							=	copy.deepcopy(self.__dict__       )
          UpperCamelCase    :  List[Any]							=	self.text_config.to_dict()
          UpperCamelCase    :  Dict							=	self.vision_config.to_dict()
          UpperCamelCase    :  Optional[Any]							=	self.__class__.model_type
          return output







"""simple docstring"""



import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


__snake_case   			=    """hf-internal-testing/tiny-random-bert"""
__snake_case   			=    os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""")
__snake_case   			=    """9b8c223d42b2188cb49d29af482996f9d0f3e5a6"""







class _lowerCAmelCase				(      unittest.TestCase	):







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      int      					=    cached_file(UpperCamelCase__						,	UpperCamelCase__						)
       # Should have downloaded the file in here
       self.assertTrue(os.path.isdir(UpperCamelCase__						)						)
       # Cache should contain at least those three subfolders:
       for subfolder in ["blobs", "refs", "snapshots"]:
           self.assertTrue(os.path.isdir(os.path.join(UpperCamelCase__						,	UpperCamelCase__						)						)						)
       with open(os.path.join(UpperCamelCase__						,	"refs"						,	"main"						)						) as f:
           snake_case    :      Dict      					=    f.read()
       self.assertEqual(UpperCamelCase__						,	os.path.join(UpperCamelCase__						,	"snapshots"						,	UpperCamelCase__						,	UpperCamelCase__						)						)
       self.assertTrue(os.path.isfile(UpperCamelCase__						)						)

       # File is cached at the same place the second time.
       snake_case    :      List[str]      					=    cached_file(UpperCamelCase__						,	UpperCamelCase__						)
       self.assertEqual(UpperCamelCase__						,	UpperCamelCase__						)

       # Using a specific revision to test the full commit hash.
       snake_case    :      Any      					=    cached_file(UpperCamelCase__						,	UpperCamelCase__						,	revision="9b8c223"						)
       self.assertEqual(UpperCamelCase__						,	os.path.join(UpperCamelCase__						,	"snapshots"						,	UpperCamelCase__						,	UpperCamelCase__						)						)







   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       with self.assertRaisesRegex(UpperCamelCase__						,	"is not a valid model identifier"						):
           snake_case    :      Optional[Any]      					=    cached_file("tiny-random-bert"						,	UpperCamelCase__						)

       with self.assertRaisesRegex(UpperCamelCase__						,	"is not a valid git identifier"						):
           snake_case    :      Optional[Any]      					=    cached_file(UpperCamelCase__						,	UpperCamelCase__						,	revision="aaaa"						)

       with self.assertRaisesRegex(UpperCamelCase__						,	"does not appear to have a file named"						):
           snake_case    :      List[Any]      					=    cached_file(UpperCamelCase__						,	"conf"						)







   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       with self.assertRaisesRegex(UpperCamelCase__						,	"does not appear to have a file named"						):
           snake_case    :      Tuple      					=    cached_file(UpperCamelCase__						,	"conf"						)

       with open(os.path.join(UpperCamelCase__						,	"refs"						,	"main"						)						) as f:
           snake_case    :      Any      					=    f.read()
       self.assertTrue(os.path.isfile(os.path.join(UpperCamelCase__						,	".no_exist"						,	UpperCamelCase__						,	"conf"						)						)						)

       snake_case    :      Optional[Any]      					=    cached_file(UpperCamelCase__						,	"conf"						,	_raise_exceptions_for_missing_entries=UpperCamelCase__						)
       self.assertIsNone(UpperCamelCase__						)

       snake_case    :      Any      					=    cached_file(UpperCamelCase__						,	"conf"						,	local_files_only=UpperCamelCase__						,	_raise_exceptions_for_missing_entries=UpperCamelCase__						)
       self.assertIsNone(UpperCamelCase__						)

       snake_case    :      Any      					=    mock.Mock()
       snake_case    :      List[Any]      					=    500
       snake_case    :      int      					=    {}
       snake_case    :      Optional[int]      					=    HTTPError
       snake_case    :      Tuple      					=    {}

       # Under the mock environment we get a 500 error when trying to reach the tokenizer.
       with mock.patch("requests.Session.request"						,	return_value=UpperCamelCase__						) as mock_head:
           snake_case    :      Tuple      					=    cached_file(UpperCamelCase__						,	"conf"						,	_raise_exceptions_for_connection_errors=UpperCamelCase__						)
           self.assertIsNone(UpperCamelCase__						)
           # This check we did call the fake head request
           mock_head.assert_called()







   def  lowerCamelCase		(	self						)	->		Any:

       '''simple docstring'''




       self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only"						,	UpperCamelCase__						)						)
       self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"						,	UpperCamelCase__						)						)
       self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"						,	UpperCamelCase__						)						)







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       self.assertIsNone(get_file_from_repo("bert-base-cased"						,	"ahah.txt"						)						)

       # The function raises if the repository does not exist.
       with self.assertRaisesRegex(UpperCamelCase__						,	"is not a valid model identifier"						):
           get_file_from_repo("bert-base-case"						,	UpperCamelCase__						)

       # The function raises if the revision does not exist.
       with self.assertRaisesRegex(UpperCamelCase__						,	"is not a valid git identifier"						):
           get_file_from_repo("bert-base-cased"						,	UpperCamelCase__						,	revision="ahaha"						)

       snake_case    :      int      					=    get_file_from_repo("bert-base-cased"						,	UpperCamelCase__						)
       # The name is the cached name which is not very easy to test, so instead we load the content.
       snake_case    :      str      					=    json.loads(open(UpperCamelCase__						,	"r"						).read()						)
       self.assertEqual(config["hidden_size"]						,	768						)







   def  lowerCamelCase		(	self						)	->		Optional[Any]:

       '''simple docstring'''




       with tempfile.TemporaryDirectory() as tmp_dir:
           snake_case    :      int      					=    Path(UpperCamelCase__						) / "a.txt"
           filename.touch()
           self.assertEqual(get_file_from_repo(UpperCamelCase__						,	"a.txt"						)						,	str(UpperCamelCase__						)						)

           self.assertIsNone(get_file_from_repo(UpperCamelCase__						,	"b.txt"						)						)





