



import copy
import os
from typing import Union

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


a__      :				List[Any]   	=			logging.get_logger(__name__)

a__      :				Dict   	=			{
    "Salesforce/blip-vqa-base": "https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json",
    "Salesforce/blip-vqa-capfit-large": (
        "https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json"
    ),
    "Salesforce/blip-image-captioning-base": (
        "https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json"
    ),
    "Salesforce/blip-image-captioning-large": (
        "https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json"
    ),
    "Salesforce/blip-itm-base-coco": "https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json",
    "Salesforce/blip-itm-large-coco": "https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json",
    "Salesforce/blip-itm-base-flikr": "https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json",
    "Salesforce/blip-itm-large-flikr": (
        "https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json"
    ),
}



class       UpperCAmelCase__(							lowerCamelCase	):

   '''simple docstring'''




   A    :  List[Any]       				=    "blip_text_model"


   def __init__(						self  :			int			,				lowerCAmelCase  :			Dict=3_05_24			,				lowerCAmelCase  :			Dict=7_68			,				lowerCAmelCase  :			Dict=7_68			,				lowerCAmelCase  :			Union[str, Any]=30_72			,				lowerCAmelCase  :			Any=7_68			,				lowerCAmelCase  :			Dict=12			,				lowerCAmelCase  :			int=8			,				lowerCAmelCase  :			List[Any]=5_12			,				lowerCAmelCase  :			str="gelu"			,				lowerCAmelCase  :			Union[str, Any]=1E-1_2			,				lowerCAmelCase  :			Tuple=0.0			,				lowerCAmelCase  :			List[str]=0.0			,				lowerCAmelCase  :			int=0.02			,				lowerCAmelCase  :			str=3_05_22			,				lowerCAmelCase  :			List[Any]=2			,				lowerCAmelCase  :			str=0			,				lowerCAmelCase  :			Optional[Any]=1_02			,				lowerCAmelCase  :			Optional[int]=True			,				lowerCAmelCase  :			Dict=True			,				**lowerCAmelCase  :			List[str]			,				)	->				List[str]:




         """simple docstring"""

         super().__init__(
             pad_token_id=lowerCAmelCase			,				bos_token_id=lowerCAmelCase			,				eos_token_id=lowerCAmelCase			,				sep_token_id=lowerCAmelCase			,				**lowerCAmelCase			,				)

         lowercase__     =  vocab_size
         lowercase__     =  hidden_size
         lowercase__     =  encoder_hidden_size
         lowercase__     =  intermediate_size
         lowercase__     =  projection_dim
         lowercase__     =  hidden_dropout_prob
         lowercase__     =  num_hidden_layers
         lowercase__     =  num_attention_heads
         lowercase__     =  max_position_embeddings
         lowercase__     =  layer_norm_eps
         lowercase__     =  hidden_act
         lowercase__     =  initializer_range
         lowercase__     =  attention_probs_dropout_prob
         lowercase__     =  is_decoder
         lowercase__     =  use_cache



   @classmethod
   def 			UpperCAmelCase		(						cls  :			Union[str, Any]			,				lowerCAmelCase  :			Union[str, os.PathLike]			,				**lowerCAmelCase  :			List[Any])	->				"PretrainedConfig":




         """simple docstring"""

         cls._set_token_in_kwargs(lowerCAmelCase)

         lowercase__,	lowercase__     =  cls.get_config_dict(lowerCAmelCase			,				**lowerCAmelCase)

         # get the text config dict if we are loading from BlipConfig
         if config_dict.get('model_type') == "blip":
               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(lowerCAmelCase			,				**lowerCAmelCase)



class       UpperCAmelCase__(							lowerCamelCase	):

   '''simple docstring'''




   A    :  Dict       				=    "blip_vision_model"


   def __init__(						self  :			Any			,				lowerCAmelCase  :			Union[str, Any]=7_68			,				lowerCAmelCase  :			int=30_72			,				lowerCAmelCase  :			Optional[Any]=5_12			,				lowerCAmelCase  :			List[Any]=12			,				lowerCAmelCase  :			Optional[int]=12			,				lowerCAmelCase  :			Optional[Any]=3_84			,				lowerCAmelCase  :			Any=16			,				lowerCAmelCase  :			str="gelu"			,				lowerCAmelCase  :			int=1E-5			,				lowerCAmelCase  :			Tuple=0.0			,				lowerCAmelCase  :			List[str]=1E-1_0			,				**lowerCAmelCase  :			Any			,				)	->				Optional[Any]:




         """simple docstring"""

         super().__init__(**lowerCAmelCase)

         lowercase__     =  hidden_size
         lowercase__     =  intermediate_size
         lowercase__     =  projection_dim
         lowercase__     =  num_hidden_layers
         lowercase__     =  num_attention_heads
         lowercase__     =  patch_size
         lowercase__     =  image_size
         lowercase__     =  initializer_range
         lowercase__     =  attention_dropout
         lowercase__     =  layer_norm_eps
         lowercase__     =  hidden_act



   @classmethod
   def 			UpperCAmelCase		(						cls  :			str			,				lowerCAmelCase  :			Union[str, os.PathLike]			,				**lowerCAmelCase  :			Dict)	->				"PretrainedConfig":




         """simple docstring"""

         cls._set_token_in_kwargs(lowerCAmelCase)

         lowercase__,	lowercase__     =  cls.get_config_dict(lowerCAmelCase			,				**lowerCAmelCase)

         # get the vision config dict if we are loading from BlipConfig
         if config_dict.get('model_type') == "blip":
               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(lowerCAmelCase			,				**lowerCAmelCase)



class       UpperCAmelCase__(							lowerCamelCase	):

   '''simple docstring'''




   A    :  int       				=    "blip"
   A    :  str       				=    True


   def __init__(						self  :			Optional[Any]			,				lowerCAmelCase  :			List[str]=None			,				lowerCAmelCase  :			Optional[int]=None			,				lowerCAmelCase  :			Optional[int]=5_12			,				lowerCAmelCase  :			Tuple=2.65_92			,				lowerCAmelCase  :			List[Any]=2_56			,				**lowerCAmelCase  :			str			,				)	->				int:




         """simple docstring"""

         super().__init__(**lowerCAmelCase)

         if text_config is None:
               lowercase__     =  {}
               logger.info('`text_config` is `None`. Initializing the `BlipTextConfig` with default values.')

         if vision_config is None:
               lowercase__     =  {}
               logger.info('`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.')

         lowercase__     =  BlipTextConfig(**lowerCAmelCase)
         lowercase__     =  BlipVisionConfig(**lowerCAmelCase)

         lowercase__     =  self.vision_config.hidden_size

         lowercase__     =  projection_dim
         lowercase__     =  logit_scale_init_value
         lowercase__     =  1.0
         lowercase__     =  0.02
         lowercase__     =  image_text_hidden_size


   @classmethod
   def 			UpperCAmelCase		(						cls  :			Dict			,				lowerCAmelCase  :			BlipTextConfig			,				lowerCAmelCase  :			BlipVisionConfig			,				**lowerCAmelCase  :			Dict)	->				str:




         """simple docstring"""

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



   def 			UpperCAmelCase		(						self  :			List[Any])	->				Any:




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





import os
from typing import List, Optional, Union

from ...tokenization_utils import PreTrainedTokenizer
from ...tokenization_utils_base import AddedToken
from ...utils import logging


a__      :				int   	=			logging.get_logger(__name__)

a__      :				Tuple   	=			{"vocab_file": "vocab.txt"}

a__      :				int   	=			{
    "vocab_file": {
        "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt",
        "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt",
    },
}

a__      :				Dict   	=			{
    "facebook/esm2_t6_8M_UR50D": 10_24,
    "facebook/esm2_t12_35M_UR50D": 10_24,
}

def   _lowerCAmelCase   (						A__	):
      with open(A__						,  'r'	) as f:
            lowercase__     =  f.read().splitlines()
            return [l.strip() for l in lines]



class       UpperCAmelCase__(							lowerCamelCase	):

   '''simple docstring'''




   A    :  Union[str, Any]       				=    VOCAB_FILES_NAMES
   A    :  str       				=    PRETRAINED_VOCAB_FILES_MAP
   A    :  int       				=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   A    :  List[Any]       				=    ["input_ids", "attention_mask"]


   def __init__(						self  :			Union[str, Any]			,				lowerCAmelCase  :			Any			,				lowerCAmelCase  :			Optional[int]="<unk>"			,				lowerCAmelCase  :			Dict="<cls>"			,				lowerCAmelCase  :			List[str]="<pad>"			,				lowerCAmelCase  :			Union[str, Any]="<mask>"			,				lowerCAmelCase  :			Optional[Any]="<eos>"			,				**lowerCAmelCase  :			Any			,				)	->				Optional[Any]:




         """simple docstring"""

         super().__init__(**lowerCAmelCase)
         lowercase__     =  load_vocab_file(lowerCAmelCase)
         lowercase__     =  dict(enumerate(self.all_tokens))
         lowercase__     =  {tok: ind for ind, tok in enumerate(self.all_tokens)}
         lowercase__     =  unk_token
         lowercase__     =  cls_token
         lowercase__     =  pad_token
         lowercase__     =  mask_token
         lowercase__     =  eos_token
         lowercase__     =  self.all_tokens
         self._create_trie(self.unique_no_split_tokens)


   def 			UpperCAmelCase		(						self  :			List[Any]			,				lowerCAmelCase  :			int)	->				str:




         """simple docstring"""

         return self._id_to_token.get(lowerCAmelCase			,				self.unk_token)


   def 			UpperCAmelCase		(						self  :			Dict			,				lowerCAmelCase  :			str)	->				int:




         """simple docstring"""

         return self._token_to_id.get(lowerCAmelCase			,				self._token_to_id.get(self.unk_token))


   def 			UpperCAmelCase		(						self  :			Optional[Any]			,				lowerCAmelCase  :			str			,				**lowerCAmelCase  :			Union[str, Any])	->				Dict:




         """simple docstring"""

         return text.split()


   def 			UpperCAmelCase		(						self  :			Union[str, Any]			,				lowerCAmelCase  :			Any=False)	->				Union[str, Any]:




         """simple docstring"""

         return len(self._id_to_token)


   def 			UpperCAmelCase		(						self  :			Tuple)	->				int:




         """simple docstring"""

         return {token: i for i, token in enumerate(self.all_tokens)}


   def 			UpperCAmelCase		(						self  :			Optional[Any]			,				lowerCAmelCase  :			str)	->				int:




         """simple docstring"""

         return self._token_to_id.get(lowerCAmelCase			,				self._token_to_id.get(self.unk_token))


   def 			UpperCAmelCase		(						self  :			Dict			,				lowerCAmelCase  :			int)	->				str:




         """simple docstring"""

         return self._id_to_token.get(lowerCAmelCase			,				self.unk_token)


   def 			UpperCAmelCase		(						self  :			Any			,				lowerCAmelCase  :			List[int]			,				lowerCAmelCase  :			Optional[List[int]] = None)	->				List[int]:




         """simple docstring"""

         lowercase__     =  [self.cls_token_id]
         lowercase__     =  [self.eos_token_id]  # No sep token in ESM vocabulary
         if token_ids_a is None:
               if self.eos_token_id is None:
                     return cls + token_ids_a
               else:
                     return cls + token_ids_a + sep
         elif self.eos_token_id is None:
               raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!')
         return cls + token_ids_a + sep + token_ids_a + sep  # Multiple inputs always have an EOS token


   def 			UpperCAmelCase		(						self  :			Union[str, Any]			,				lowerCAmelCase  :			List			,				lowerCAmelCase  :			Optional[List] = None			,				lowerCAmelCase  :			bool = False)	->				List[int]:




         """simple docstring"""

         if already_has_special_tokens:
               if token_ids_a is not None:
                     raise ValueError(
                         'You should not supply a second sequence if the provided sequence of '
                         'ids is already formatted with special tokens for the model.')

               return [1 if token in self.all_special_ids else 0 for token in token_ids_a]
         lowercase__     =  [1] + ([0] * len(lowerCAmelCase)) + [1]
         if token_ids_a is not None:
               mask += [0] * len(lowerCAmelCase) + [1]
         return mask


   def 			UpperCAmelCase		(						self  :			Union[str, Any]			,				lowerCAmelCase  :			Tuple			,				lowerCAmelCase  :			Optional[int])	->				Dict:




         """simple docstring"""

         lowercase__     =  os.path.join(lowerCAmelCase			,				(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt')
         with open(lowerCAmelCase			,				'w') as f:
               f.write('\n'.join(self.all_tokens))
         return (vocab_file,)


   @property
   def 			UpperCAmelCase		(						self  :			Optional[int])	->				int:




         """simple docstring"""

         return self.get_vocab_size(with_added_tokens=lowerCAmelCase)



   def 			UpperCAmelCase		(						self  :			Optional[Any]			,				lowerCAmelCase  :			Union[List[str], List[AddedToken]]			,				lowerCAmelCase  :			bool = False)	->				int:




         """simple docstring"""

         return super()._add_tokens(lowerCAmelCase			,				special_tokens=lowerCAmelCase)
