





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


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






class   UpperCAmelCase      (			unittest.TestCase							):
 def 	UpperCAmelCase_				(							self :str				)->				Tuple:
     A__							=     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:
         A__							=     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.
     A__							=     cached_file(lowercase_		,			lowercase_				)
     self.assertEqual(lowercase_		,			lowercase_				)

     # Using a specific revision to test the full commit hash.
     A__							=     cached_file(lowercase_		,			lowercase_		,			revision="9b8c223"				)
     self.assertEqual(lowercase_		,			os.path.join(lowercase_		,			"snapshots"		,			lowercase_		,			lowercase_				)				)
 def 	UpperCAmelCase_				(							self :Optional[int]				)->				List[Any]:
     with self.assertRaisesRegex(lowercase_		,			"is not a valid model identifier"				):
         A__							=     cached_file("tiny-random-bert"		,			lowercase_				)

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

     with self.assertRaisesRegex(lowercase_		,			"does not appear to have a file named"				):
         A__							=     cached_file(lowercase_		,			"conf"				)
 def 	UpperCAmelCase_				(							self :List[Any]				)->				Dict:
     with self.assertRaisesRegex(lowercase_		,			"does not appear to have a file named"				):
         A__							=     cached_file(lowercase_		,			"conf"				)

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

     A__							=     cached_file(lowercase_		,			"conf"		,			_raise_exceptions_for_missing_entries=lowercase_				)
     self.assertIsNone(lowercase_				)

     A__							=     cached_file(lowercase_		,			"conf"		,			local_files_only=lowercase_		,			_raise_exceptions_for_missing_entries=lowercase_				)
     self.assertIsNone(lowercase_				)

     A__							=     mock.Mock()
     A__							=     5_00
     A__							=     {}
     A__							=     HTTPError
     A__							=     {}

     # 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:
         A__							=     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 :int				)->				List[Any]:
     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 :int				)->				Union[str, Any]:
     # `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"				)

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



 def 	UpperCAmelCase_				(							self :List[str]				)->				Dict:
     with tempfile.TemporaryDirectory() as tmp_dir:
         A__							=     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"				)				)










'''simple docstring'''

import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


__lowerCAmelCase				:      Optional[Any]						      =logging.get_logger(__name__)

__lowerCAmelCase				:      List[Any]						      ={
    "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json",
}






class   UpperCAmelCase      (			UpperCamelCase__							):
 __lowercase  						=							"""blip_2_vision_model"""
 def __init__(							self :List[Any]		,			lowercase_ :List[str]=14_08		,			lowercase_ :int=61_44		,			lowercase_ :List[str]=39		,			lowercase_ :List[Any]=16		,			lowercase_ :Union[str, Any]=2_24		,			lowercase_ :List[str]=14		,			lowercase_ :Dict="gelu"		,			lowercase_ :Tuple=0.0_0_0_0_1		,			lowercase_ :Dict=0.0		,			lowercase_ :Optional[int]=1E-10		,			lowercase_ :Optional[Any]=True		,			**lowercase_ :List[str]		,			)->				int:
     super().__init__(**lowercase_				)

     A__							=     hidden_size
     A__							=     intermediate_size
     A__							=     num_hidden_layers
     A__							=     num_attention_heads
     A__							=     patch_size
     A__							=     image_size
     A__							=     initializer_range
     A__							=     attention_dropout
     A__							=     layer_norm_eps
     A__							=     hidden_act
     A__							=     qkv_bias



 @classmethod
 def 	UpperCAmelCase_				(							cls :Optional[Any]		,			lowercase_ :Union[str, os.PathLike]		,			**lowercase_ :Optional[Any]				)->				"PretrainedConfig":
     cls._set_token_in_kwargs(lowercase_				)

     A__,      A__							=     cls.get_config_dict(lowercase_		,			**lowercase_				)

     # get the vision config dict if we are loading from Blip2Config
     if config_dict.get("model_type"				) == "blip-2":
         A__							=     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   UpperCAmelCase      (			UpperCamelCase__							):
 __lowercase  						=							"""blip_2_qformer"""
 def __init__(							self :Dict		,			lowercase_ :int=3_05_22		,			lowercase_ :Union[str, Any]=7_68		,			lowercase_ :Tuple=12		,			lowercase_ :Union[str, Any]=12		,			lowercase_ :str=30_72		,			lowercase_ :Any="gelu"		,			lowercase_ :Optional[int]=0.1		,			lowercase_ :List[str]=0.1		,			lowercase_ :Dict=5_12		,			lowercase_ :Optional[int]=0.0_2		,			lowercase_ :Dict=1E-12		,			lowercase_ :List[Any]=0		,			lowercase_ :str="absolute"		,			lowercase_ :List[str]=2		,			lowercase_ :Tuple=14_08		,			**lowercase_ :Tuple		,			)->				List[Any]:
     super().__init__(pad_token_id=lowercase_		,			**lowercase_				)

     A__							=     vocab_size
     A__							=     hidden_size
     A__							=     num_hidden_layers
     A__							=     num_attention_heads
     A__							=     hidden_act
     A__							=     intermediate_size
     A__							=     hidden_dropout_prob
     A__							=     attention_probs_dropout_prob
     A__							=     max_position_embeddings
     A__							=     initializer_range
     A__							=     layer_norm_eps
     A__							=     position_embedding_type
     A__							=     cross_attention_frequency
     A__							=     encoder_hidden_size



 @classmethod
 def 	UpperCAmelCase_				(							cls :int		,			lowercase_ :Union[str, os.PathLike]		,			**lowercase_ :str				)->				"PretrainedConfig":
     cls._set_token_in_kwargs(lowercase_				)

     A__,      A__							=     cls.get_config_dict(lowercase_		,			**lowercase_				)

     # get the qformer config dict if we are loading from Blip2Config
     if config_dict.get("model_type"				) == "blip-2":
         A__							=     config_dict["qformer_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   UpperCAmelCase      (			UpperCamelCase__							):
 __lowercase  						=							"""blip-2"""
 __lowercase  						=							True
 def __init__(							self :int		,			lowercase_ :List[Any]=None		,			lowercase_ :Dict=None		,			lowercase_ :Tuple=None		,			lowercase_ :List[str]=32		,			**lowercase_ :Any				)->				Union[str, Any]:
     super().__init__(**lowercase_				)

     if vision_config is None:
         A__							=     {}
         logger.info("vision_config is None. initializing the Blip2VisionConfig with default values."				)

     if qformer_config is None:
         A__							=     {}
         logger.info("qformer_config is None. Initializing the Blip2QFormerConfig with default values."				)

     if text_config is None:
         A__							=     {}
         logger.info("text_config is None. Initializing the text config with default values (`OPTConfig`)."				)

     A__							=     BlipaVisionConfig(**lowercase_				)
     A__							=     BlipaQFormerConfig(**lowercase_				)
     A__							=     text_config["model_type"] if "model_type" in text_config else "opt"
     A__							=     CONFIG_MAPPING[text_model_type](**lowercase_				)

     A__							=     self.text_config.tie_word_embeddings
     A__							=     self.text_config.is_encoder_decoder

     A__							=     num_query_tokens
     A__							=     self.vision_config.hidden_size
     A__							=     self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
     A__							=     1.0
     A__							=     0.0_2
 @classmethod
 def 	UpperCAmelCase_				(							cls :Optional[Any]		,			lowercase_ :BlipaVisionConfig		,			lowercase_ :BlipaQFormerConfig		,			lowercase_ :PretrainedConfig		,			**lowercase_ :Any		,			)->				Optional[int]:
     return cls(
         vision_config=vision_config.to_dict()		,			qformer_config=qformer_config.to_dict()		,			text_config=text_config.to_dict()		,			**lowercase_		,			)



 def 	UpperCAmelCase_				(							self :Dict				)->				Any:
     A__							=     copy.deepcopy(self.__dict__				)
     A__							=     self.vision_config.to_dict()
     A__							=     self.qformer_config.to_dict()
     A__							=     self.text_config.to_dict()
     A__							=     self.__class__.model_type
     return output



