





import copy
import os
from typing import Union

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


UpperCAmelCase_					:   str 							=						logging.get_logger(__name__)

UpperCAmelCase_					:   int 							=						{
    """BAAI/AltCLIP""": """https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json""",
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}





class      lowercase__    (							__A  ):
  __UpperCamelCase	     =  """altclip_text_model"""







  def __init__(	self    ,						_lowercase=250_002    ,						_lowercase=1_024    ,						_lowercase=24    ,						_lowercase=16    ,						_lowercase=4_096    ,						_lowercase="gelu"    ,						_lowercase=0.1    ,						_lowercase=0.1    ,						_lowercase=514    ,						_lowercase=1    ,						_lowercase=0.02    ,						_lowercase=0.02    ,						_lowercase=1e-05    ,						_lowercase=1    ,						_lowercase=0    ,						_lowercase=2    ,						_lowercase="absolute"    ,						_lowercase=True    ,						_lowercase=768    ,						**_lowercase    ,						):
       super().__init__(pad_token_id=_lowercase    ,						bos_token_id=_lowercase    ,						eos_token_id=_lowercase    ,						**_lowercase						)

       lowerCAmelCase_					:       Optional[int]    =		vocab_size
       lowerCAmelCase_					:       Optional[int]    =		hidden_size
       lowerCAmelCase_					:       Optional[Any]    =		num_hidden_layers
       lowerCAmelCase_					:       Tuple    =		num_attention_heads
       lowerCAmelCase_					:       List[str]    =		hidden_act
       lowerCAmelCase_					:       List[Any]    =		intermediate_size
       lowerCAmelCase_					:       Optional[int]    =		hidden_dropout_prob
       lowerCAmelCase_					:       Tuple    =		attention_probs_dropout_prob
       lowerCAmelCase_					:       List[str]    =		max_position_embeddings
       lowerCAmelCase_					:       Union[str, Any]    =		type_vocab_size
       lowerCAmelCase_					:       List[Any]    =		initializer_range
       lowerCAmelCase_					:       Optional[int]    =		initializer_factor
       lowerCAmelCase_					:       int    =		layer_norm_eps
       lowerCAmelCase_					:       List[Any]    =		position_embedding_type
       lowerCAmelCase_					:       str    =		use_cache
       lowerCAmelCase_					:       Tuple    =		project_dim





class      lowercase__    (							__A  ):
  __UpperCamelCase	     =  """altclip_vision_model"""







  def __init__(	self    ,						_lowercase=768    ,						_lowercase=3_072    ,						_lowercase=512    ,						_lowercase=12    ,						_lowercase=12    ,						_lowercase=3    ,						_lowercase=224    ,						_lowercase=32    ,						_lowercase="quick_gelu"    ,						_lowercase=1e-5    ,						_lowercase=0.0    ,						_lowercase=0.02    ,						_lowercase=1.0    ,						**_lowercase    ,						):
       super().__init__(**_lowercase						)

       lowerCAmelCase_					:       Optional[int]    =		hidden_size
       lowerCAmelCase_					:       Optional[int]    =		intermediate_size
       lowerCAmelCase_					:       str    =		projection_dim
       lowerCAmelCase_					:       Union[str, Any]    =		num_hidden_layers
       lowerCAmelCase_					:       str    =		num_attention_heads
       lowerCAmelCase_					:       int    =		num_channels
       lowerCAmelCase_					:       Dict    =		patch_size
       lowerCAmelCase_					:       Union[str, Any]    =		image_size
       lowerCAmelCase_					:       int    =		initializer_range
       lowerCAmelCase_					:       Any    =		initializer_factor
       lowerCAmelCase_					:       str    =		attention_dropout
       lowerCAmelCase_					:       Any    =		layer_norm_eps
       lowerCAmelCase_					:       List[Any]    =		hidden_act







  @classmethod
  def 	UpperCAmelCase__		(	cls    ,						_lowercase    ,						**_lowercase						):
       cls._set_token_in_kwargs(_lowercase						)

       lowerCAmelCase_   ,  lowerCAmelCase_					:       Tuple    =		cls.get_config_dict(_lowercase    ,						**_lowercase						)

       # get the vision config dict if we are loading from AltCLIPConfig
       if config_dict.get("""model_type"""						) == "altclip":
            lowerCAmelCase_					:       Optional[Any]    =		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(_lowercase    ,						**_lowercase						)





class      lowercase__    (							__A  ):
  __UpperCamelCase	     =  """altclip"""
  __UpperCamelCase	     =  True







  def __init__(	self    ,						_lowercase=None    ,						_lowercase=None    ,						_lowercase=768    ,						_lowercase=2.6592    ,						**_lowercase						):
       # If `_config_dict` exist, we use them for the backward compatibility.
       # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
       # of confusion!).
       lowerCAmelCase_					:       Any    =		kwargs.pop("""text_config_dict"""    ,						_lowercase						)
       lowerCAmelCase_					:       List[str]    =		kwargs.pop("""vision_config_dict"""    ,						_lowercase						)

       super().__init__(**_lowercase						)

       # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
       # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
       # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
       if text_config_dict is not None:
            if text_config is None:
                 lowerCAmelCase_					:       List[str]    =		{}

            # This is the complete result when using `text_config_dict`.
            lowerCAmelCase_					:       int    =		AltCLIPTextConfig(**_lowercase						).to_dict()

            # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
            for key, value in _text_config_dict.items():
                 if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
                      # If specified in `text_config_dict`
                      if key in text_config_dict:
                           lowerCAmelCase_					:       Optional[int]    =		(
                               F'`{key}` is found in both `text_config_dict` and `text_config` but with different values. '
                               F'The value `text_config_dict["{key}"]` will be used instead.'
                           )
                      # If inferred from default argument values (just to be super careful)
                      else:
                           lowerCAmelCase_					:       List[str]    =		(
                               F'`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '
                               F'value `text_config["{key}"]` will be overriden.'
                           )
                      logger.warning(_lowercase						)

            # Update all values in `text_config` with the ones in `_text_config_dict`.
            text_config.update(_text_config_dict						)

       if vision_config_dict is not None:
            if vision_config is None:
                 lowerCAmelCase_					:       Any    =		{}

            # This is the complete result when using `vision_config_dict`.
            lowerCAmelCase_					:       int    =		AltCLIPVisionConfig(**_lowercase						).to_dict()
            # convert keys to string instead of integer
            if "id2label" in _vision_config_dict:
                 lowerCAmelCase_					:       str    =		{
                     str(_lowercase						): value for key, value in _vision_config_dict["""id2label"""].items()
                 }

            # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
            for key, value in _vision_config_dict.items():
                 if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
                      # If specified in `vision_config_dict`
                      if key in vision_config_dict:
                           lowerCAmelCase_					:       Tuple    =		(
                               F'`{key}` is found in both `vision_config_dict` and `vision_config` but with different '
                               F'values. The value `vision_config_dict["{key}"]` will be used instead.'
                           )
                      # If inferred from default argument values (just to be super careful)
                      else:
                           lowerCAmelCase_					:       List[Any]    =		(
                               F'`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '
                               F'The value `vision_config["{key}"]` will be overriden.'
                           )
                      logger.warning(_lowercase						)

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
            vision_config.update(_vision_config_dict						)

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

       if vision_config is None:
            lowerCAmelCase_					:       Tuple    =		{}
            logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."""						)

       lowerCAmelCase_					:       int    =		AltCLIPTextConfig(**_lowercase						)
       lowerCAmelCase_					:       Dict    =		AltCLIPVisionConfig(**_lowercase						)

       lowerCAmelCase_					:       str    =		projection_dim
       lowerCAmelCase_					:       int    =		logit_scale_init_value
       lowerCAmelCase_					:       int    =		1.0







  @classmethod
  def 	UpperCAmelCase__		(	cls    ,						_lowercase    ,						_lowercase    ,						**_lowercase						):
       return cls(text_config=text_config.to_dict()    ,						vision_config=vision_config.to_dict()    ,						**_lowercase						)







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       List[Any]    =		copy.deepcopy(self.__dict__						)
       lowerCAmelCase_					:       Optional[int]    =		self.text_config.to_dict()
       lowerCAmelCase_					:       int    =		self.vision_config.to_dict()
       lowerCAmelCase_					:       Dict    =		self.__class__.model_type
       return output







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


UpperCAmelCase_					:   List[str] 							=						"""hf-internal-testing/tiny-random-bert"""
UpperCAmelCase_					:   List[Any] 							=						os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""")
UpperCAmelCase_					:   Tuple 							=						"""9b8c223d42b2188cb49d29af482996f9d0f3e5a6"""





class      lowercase__    (							unittest.TestCase  ):







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

       # File is cached at the same place the second time.
       lowerCAmelCase_					:       Dict    =		cached_file(_lowercase    ,						_lowercase						)
       self.assertEqual(_lowercase    ,						_lowercase						)

       # Using a specific revision to test the full commit hash.
       lowerCAmelCase_					:       Optional[int]    =		cached_file(_lowercase    ,						_lowercase    ,						revision="""9b8c223"""						)
       self.assertEqual(_lowercase    ,						os.path.join(_lowercase    ,						"""snapshots"""    ,						_lowercase    ,						_lowercase						)						)







  def 	UpperCAmelCase__		(	self						):
       with self.assertRaisesRegex(_lowercase    ,						"""is not a valid model identifier"""						):
            lowerCAmelCase_					:       Dict    =		cached_file("""tiny-random-bert"""    ,						_lowercase						)

       with self.assertRaisesRegex(_lowercase    ,						"""is not a valid git identifier"""						):
            lowerCAmelCase_					:       Tuple    =		cached_file(_lowercase    ,						_lowercase    ,						revision="""aaaa"""						)

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







  def 	UpperCAmelCase__		(	self						):
       with self.assertRaisesRegex(_lowercase    ,						"""does not appear to have a file named"""						):
            lowerCAmelCase_					:       Any    =		cached_file(_lowercase    ,						"""conf"""						)

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

       lowerCAmelCase_					:       Union[str, Any]    =		cached_file(_lowercase    ,						"""conf"""    ,						_raise_exceptions_for_missing_entries=_lowercase						)
       self.assertIsNone(_lowercase						)

       lowerCAmelCase_					:       Any    =		cached_file(_lowercase    ,						"""conf"""    ,						local_files_only=_lowercase    ,						_raise_exceptions_for_missing_entries=_lowercase						)
       self.assertIsNone(_lowercase						)

       lowerCAmelCase_					:       Any    =		mock.Mock()
       lowerCAmelCase_					:       Optional[Any]    =		500
       lowerCAmelCase_					:       Any    =		{}
       lowerCAmelCase_					:       List[str]    =		HTTPError
       lowerCAmelCase_					:       List[str]    =		{}

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







  def 	UpperCAmelCase__		(	self						):
       self.assertTrue(has_file("""hf-internal-testing/tiny-bert-pt-only"""    ,						_lowercase						)						)
       self.assertFalse(has_file("""hf-internal-testing/tiny-bert-pt-only"""    ,						_lowercase						)						)
       self.assertFalse(has_file("""hf-internal-testing/tiny-bert-pt-only"""    ,						_lowercase						)						)







  def 	UpperCAmelCase__		(	self						):
       # `get_file_from_repo` returns None if the file does not exist
       self.assertIsNone(get_file_from_repo("""bert-base-cased"""    ,						"""ahah.txt"""						)						)

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

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

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







  def 	UpperCAmelCase__		(	self						):
       with tempfile.TemporaryDirectory() as tmp_dir:
            lowerCAmelCase_					:       Optional[Any]    =		Path(_lowercase						) / """a.txt"""
            filename.touch()
            self.assertEqual(get_file_from_repo(_lowercase    ,						"""a.txt"""						)    ,						str(_lowercase						)						)

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