
"""simple docstring"""




import copy
import os
from typing import TYPE_CHECKING, List, Union


if TYPE_CHECKING:
  pass

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


A__   :					Dict							=   logging.get_logger(__name__)

A__   :					Tuple							=   {
    'kakaobrain/align-base': 'https://huggingface.co/kakaobrain/align-base/resolve/main/config.json',
}


class 			__magic_name__       (       UpperCAmelCase_ ):
       UpperCamelCase_   =		"align_text_model"
       def __init__(     self ,				A_=3_0522 ,				A_=768 ,				A_=12 ,				A_=12 ,				A_=3072 ,				A_="gelu" ,				A_=0.1 ,				A_=0.1 ,				A_=512 ,				A_=2 ,				A_=0.02 ,				A_=1E-12 ,				A_=0 ,				A_="absolute" ,				A_=True ,				**A_ ,				)     ->	Dict:





         """simple docstring"""




         super().__init__(**_snake_case       )

         _lowercase       =     vocab_size
         _lowercase       =     hidden_size
         _lowercase       =     num_hidden_layers
         _lowercase       =     num_attention_heads
         _lowercase       =     hidden_act
         _lowercase       =     intermediate_size
         _lowercase       =     hidden_dropout_prob
         _lowercase       =     attention_probs_dropout_prob
         _lowercase       =     max_position_embeddings
         _lowercase       =     type_vocab_size
         _lowercase       =     initializer_range
         _lowercase       =     layer_norm_eps
         _lowercase       =     position_embedding_type
         _lowercase       =     use_cache
         _lowercase       =     pad_token_id



       @classmethod
       def 							lowercase_							(     cls ,				A_ ,				**A_       )     ->	List[str]:





         """simple docstring"""




         cls._set_token_in_kwargs(_snake_case       )

         _lowercase ,				_lowercase       =     cls.get_config_dict(_snake_case ,				**_snake_case       )

         # get the text config dict if we are loading from AlignConfig
         if config_dict.get('''model_type'''       ) == "align":
           _lowercase       =     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 			__magic_name__       (       UpperCAmelCase_ ):
       UpperCamelCase_   =		"align_vision_model"
       def __init__(     self ,				A_ = 3 ,				A_ = 600 ,				A_ = 2.0 ,				A_ = 3.1 ,				A_ = 8 ,				A_ = [3, 3, 5, 3, 5, 5, 3] ,				A_ = [32, 16, 24, 40, 80, 112, 192] ,				A_ = [16, 24, 40, 80, 112, 192, 320] ,				A_ = [] ,				A_ = [1, 2, 2, 2, 1, 2, 1] ,				A_ = [1, 2, 2, 3, 3, 4, 1] ,				A_ = [1, 6, 6, 6, 6, 6, 6] ,				A_ = 0.25 ,				A_ = "swish" ,				A_ = 2560 ,				A_ = "mean" ,				A_ = 0.02 ,				A_ = 0.0_01 ,				A_ = 0.99 ,				A_ = 0.2 ,				**A_ ,				)     ->	Tuple:





         """simple docstring"""




         super().__init__(**_snake_case       )

         _lowercase       =     num_channels
         _lowercase       =     image_size
         _lowercase       =     width_coefficient
         _lowercase       =     depth_coefficient
         _lowercase       =     depth_divisor
         _lowercase       =     kernel_sizes
         _lowercase       =     in_channels
         _lowercase       =     out_channels
         _lowercase       =     depthwise_padding
         _lowercase       =     strides
         _lowercase       =     num_block_repeats
         _lowercase       =     expand_ratios
         _lowercase       =     squeeze_expansion_ratio
         _lowercase       =     hidden_act
         _lowercase       =     hidden_dim
         _lowercase       =     pooling_type
         _lowercase       =     initializer_range
         _lowercase       =     batch_norm_eps
         _lowercase       =     batch_norm_momentum
         _lowercase       =     drop_connect_rate
         _lowercase       =     sum(_snake_case       ) * 4



       @classmethod
       def 							lowercase_							(     cls ,				A_ ,				**A_       )     ->	List[Any]:





         """simple docstring"""




         cls._set_token_in_kwargs(_snake_case       )

         _lowercase ,				_lowercase       =     cls.get_config_dict(_snake_case ,				**_snake_case       )

         # get the vision config dict if we are loading from AlignConfig
         if config_dict.get('''model_type'''       ) == "align":
           _lowercase       =     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 			__magic_name__       (       UpperCAmelCase_ ):
       UpperCamelCase_   =		"align"
       UpperCamelCase_   =		True
       def __init__(     self ,				A_=None ,				A_=None ,				A_=640 ,				A_=1.0 ,				A_=0.02 ,				**A_ ,				)     ->	Optional[Any]:





         """simple docstring"""




         super().__init__(**_snake_case       )

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

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

         _lowercase       =     AlignTextConfig(**_snake_case       )
         _lowercase       =     AlignVisionConfig(**_snake_case       )

         _lowercase       =     projection_dim
         _lowercase       =     temperature_init_value
         _lowercase       =     initializer_range
       @classmethod
       def 							lowercase_							(     cls ,				A_ ,				A_ ,				**A_       )     ->	Dict:





         """simple docstring"""




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



       def 							lowercase_							(     self       )     ->	int:





         """simple docstring"""




         _lowercase       =     copy.deepcopy(self.__dict__       )
         _lowercase       =     self.text_config.to_dict()
         _lowercase       =     self.vision_config.to_dict()
         _lowercase       =     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,
)


A__   :					Any							=   'hf-internal-testing/tiny-random-bert'
A__   :					int							=   os.path.join(TRANSFORMERS_CACHE, 'models--hf-internal-testing--tiny-random-bert')
A__   :					Dict							=   '9b8c223d42b2188cb49d29af482996f9d0f3e5a6'


class 			__magic_name__       (       unittest.TestCase ):
       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




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

         # File is cached at the same place the second time.
         _lowercase:			List[Any]       =     cached_file(A_ ,				A_       )
         self.assertEqual(A_ ,				A_       )

         # Using a specific revision to test the full commit hash.
         _lowercase:			Union[str, Any]       =     cached_file(A_ ,				A_ ,				revision='''9b8c223'''       )
         self.assertEqual(A_ ,				os.path.join(A_ ,				'''snapshots''' ,				A_ ,				A_       )       )
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         with self.assertRaisesRegex(A_ ,				'''is not a valid model identifier'''       ):
           _lowercase:			Union[str, Any]       =     cached_file('''tiny-random-bert''' ,				A_       )

         with self.assertRaisesRegex(A_ ,				'''is not a valid git identifier'''       ):
           _lowercase:			List[Any]       =     cached_file(A_ ,				A_ ,				revision='''aaaa'''       )

         with self.assertRaisesRegex(A_ ,				'''does not appear to have a file named'''       ):
           _lowercase:			int       =     cached_file(A_ ,				'''conf'''       )
       def 							lowercase_							(     self       )     ->	Optional[int]:





         """simple docstring"""




         with self.assertRaisesRegex(A_ ,				'''does not appear to have a file named'''       ):
           _lowercase:			Dict       =     cached_file(A_ ,				'''conf'''       )

         with open(os.path.join(A_ ,				'''refs''' ,				'''main'''       )       ) as f:
           _lowercase:			int       =     f.read()
         self.assertTrue(os.path.isfile(os.path.join(A_ ,				'''.no_exist''' ,				A_ ,				'''conf'''       )       )       )

         _lowercase:			Optional[int]       =     cached_file(A_ ,				'''conf''' ,				_raise_exceptions_for_missing_entries=A_       )
         self.assertIsNone(A_       )

         _lowercase:			Optional[int]       =     cached_file(A_ ,				'''conf''' ,				local_files_only=A_ ,				_raise_exceptions_for_missing_entries=A_       )
         self.assertIsNone(A_       )

         _lowercase:			Optional[Any]       =     mock.Mock()
         _lowercase:			Optional[Any]       =     500
         _lowercase:			Optional[Any]       =     {}
         _lowercase:			Dict       =     HTTPError
         _lowercase:			Optional[Any]       =     {}

         # Under the mock environment we get a 500 error when trying to reach the tokenizer.
         with mock.patch('''requests.Session.request''' ,				return_value=A_       ) as mock_head:
           _lowercase:			Tuple       =     cached_file(A_ ,				'''conf''' ,				_raise_exceptions_for_connection_errors=A_       )
           self.assertIsNone(A_       )
           # This check we did call the fake head request
           mock_head.assert_called()
       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' ,				A_       )       )
         self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' ,				A_       )       )
         self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' ,				A_       )       )
       def 							lowercase_							(     self       )     ->	Tuple:





         """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(A_ ,				'''is not a valid model identifier'''       ):
           get_file_from_repo('''bert-base-case''' ,				A_       )

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

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



       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         with tempfile.TemporaryDirectory() as tmp_dir:
           _lowercase:			List[Any]       =     Path(A_       ) / '''a.txt'''
           filename.touch()
           self.assertEqual(get_file_from_repo(A_ ,				'''a.txt'''       ) ,				str(A_       )       )

           self.assertIsNone(get_file_from_repo(A_ ,				'''b.txt'''       )       )
