


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,
)


A			:						int        =  'hf-internal-testing/tiny-random-bert'
A			:						Optional[int]        =  os.path.join(TRANSFORMERS_CACHE, 'models--hf-internal-testing--tiny-random-bert')
A			:						Tuple        =  '9b8c223d42b2188cb49d29af482996f9d0f3e5a6'



class 				A       (			unittest.TestCase				):
					'''simple docstring'''






					def     lowerCamelCase__	(self       :		Tuple						)		->  Optional[int]:




							"""simple docstring"""


							lowercase__	     =						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:
									lowercase__	     =						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.
							lowercase__	     =						cached_file(_UpperCAmelCase ,   _UpperCAmelCase						)
							self.assertEqual(_UpperCAmelCase ,   _UpperCAmelCase						)

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

					def     lowerCamelCase__	(self       :		List[Any]						)		->  Optional[int]:




							"""simple docstring"""


							with self.assertRaisesRegex(_UpperCAmelCase ,   """is not a valid model identifier"""						):
									lowercase__	     =						cached_file("""tiny-random-bert""" ,   _UpperCAmelCase						)

							with self.assertRaisesRegex(_UpperCAmelCase ,   """is not a valid git identifier"""						):
									lowercase__	     =						cached_file(_UpperCAmelCase ,   _UpperCAmelCase ,   revision="""aaaa"""						)

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

					def     lowerCamelCase__	(self       :		List[Any]						)		->  Optional[Any]:




							"""simple docstring"""


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

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

							lowercase__	     =						cached_file(_UpperCAmelCase ,   """conf""" ,   _raise_exceptions_for_missing_entries=_UpperCAmelCase						)
							self.assertIsNone(_UpperCAmelCase						)

							lowercase__	     =						cached_file(_UpperCAmelCase ,   """conf""" ,   local_files_only=_UpperCAmelCase ,   _raise_exceptions_for_missing_entries=_UpperCAmelCase						)
							self.assertIsNone(_UpperCAmelCase						)

							lowercase__	     =						mock.Mock()
							lowercase__	     =						500
							lowercase__	     =						{}
							lowercase__	     =						HTTPError
							lowercase__	     =						{}

							# 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:
									lowercase__	     =						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       :		str						)		->  Union[str, 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       :		int						)		->  int:




							"""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"""						)

							lowercase__	     =						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.
							lowercase__	     =						json.loads(open(_UpperCAmelCase ,   """r"""						).read()						)
							self.assertEqual(config["""hidden_size"""] ,   768						)


					def     lowerCamelCase__	(self       :		List[str]						)		->  Optional[int]:




							"""simple docstring"""


							with tempfile.TemporaryDirectory() as tmp_dir:
									lowercase__	     =						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"""						)						)



import copy

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


__a         =   logging.get_logger(__name__)
class 					lowercase__(							UpperCAmelCase				):



	"""simple docstring"""




	a     :List[str]       	=      'encoder-decoder'
	a     :Any       	=      True
	def __init__(			self    :     List[Any]			,				**SCREAMING_SNAKE_CASE_    :     List[Any]			)			->	Optional[int]:
					super().__init__(**SCREAMING_SNAKE_CASE_			)
					assert (
					    "encoder" in kwargs and "decoder" in kwargs
					), "Config has to be initialized with encoder and decoder config"
					lowercase_	    =   kwargs.pop('''encoder'''			)
					lowercase_	    =   encoder_config.pop('''model_type'''			)
					lowercase_	    =   kwargs.pop('''decoder'''			)
					lowercase_	    =   decoder_config.pop('''model_type'''			)

					from ..auto.configuration_auto import AutoConfig

					lowercase_	    =   AutoConfig.for_model(SCREAMING_SNAKE_CASE_			,				**SCREAMING_SNAKE_CASE_			)
					lowercase_	    =   AutoConfig.for_model(SCREAMING_SNAKE_CASE_			,				**SCREAMING_SNAKE_CASE_			)
					lowercase_	    =   True
	@classmethod
	def 		_lowercase    (			cls    :     Optional[int]			,				SCREAMING_SNAKE_CASE_    :     PretrainedConfig			,				SCREAMING_SNAKE_CASE_    :     PretrainedConfig			,				**SCREAMING_SNAKE_CASE_    :     Optional[int]			)			->	PretrainedConfig:
					logger.info('''Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config'''			)
					lowercase_	    =   True
					lowercase_	    =   True

					return cls(encoder=encoder_config.to_dict()			,				decoder=decoder_config.to_dict()			,				**SCREAMING_SNAKE_CASE_			)




	def 		_lowercase    (			self    :     Tuple			)			->	List[Any]:
					lowercase_	    =   copy.deepcopy(self.__dict__			)
					lowercase_	    =   self.encoder.to_dict()
					lowercase_	    =   self.decoder.to_dict()
					lowercase_	    =   self.__class__.model_type
					return output




