
import copy
import os
from typing import Union

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


__magic_name__            =  logging.get_logger(__name__)

__magic_name__            =  {
    '''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 					_SCREAMING_SNAKE_CASE  (      __UpperCamelCase ):
      _A						:		List[Any]    	=     'blip_text_model'
      def __init__(			self		,	lowerCamelCase=3_05_24		,	lowerCamelCase=7_68		,	lowerCamelCase=7_68		,	lowerCamelCase=30_72		,	lowerCamelCase=7_68		,	lowerCamelCase=12		,	lowerCamelCase=8		,	lowerCamelCase=5_12		,	lowerCamelCase="gelu"		,	lowerCamelCase=1e-12		,	lowerCamelCase=0.0		,	lowerCamelCase=0.0		,	lowerCamelCase=0.0_2		,	lowerCamelCase=3_05_22		,	lowerCamelCase=2		,	lowerCamelCase=0		,	lowerCamelCase=1_02		,	lowerCamelCase=True		,	lowerCamelCase=True		,	**lowerCamelCase		,	):
          super().__init__(
              pad_token_id=lowerCamelCase		,	bos_token_id=lowerCamelCase		,	eos_token_id=lowerCamelCase		,	sep_token_id=lowerCamelCase		,	**lowerCamelCase		,	)

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



      @classmethod
      def A_			(			cls		,	lowerCamelCase		,	**lowerCamelCase ):
          cls._set_token_in_kwargs(lowerCamelCase )

          snake_case__						,					snake_case__						=				cls.get_config_dict(lowerCamelCase		,	**lowerCamelCase )

          # get the text config dict if we are loading from BlipConfig
          if config_dict.get("model_type" ) == "blip":
              snake_case__						=				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 					_SCREAMING_SNAKE_CASE  (      __UpperCamelCase ):
      _A						:		Tuple    	=     'blip_vision_model'
      def __init__(			self		,	lowerCamelCase=7_68		,	lowerCamelCase=30_72		,	lowerCamelCase=5_12		,	lowerCamelCase=12		,	lowerCamelCase=12		,	lowerCamelCase=3_84		,	lowerCamelCase=16		,	lowerCamelCase="gelu"		,	lowerCamelCase=1e-5		,	lowerCamelCase=0.0		,	lowerCamelCase=1e-10		,	**lowerCamelCase		,	):
          super().__init__(**lowerCamelCase )

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



      @classmethod
      def A_			(			cls		,	lowerCamelCase		,	**lowerCamelCase ):
          cls._set_token_in_kwargs(lowerCamelCase )

          snake_case__						,					snake_case__						=				cls.get_config_dict(lowerCamelCase		,	**lowerCamelCase )

          # get the vision config dict if we are loading from BlipConfig
          if config_dict.get("model_type" ) == "blip":
              snake_case__						=				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 					_SCREAMING_SNAKE_CASE  (      __UpperCamelCase ):
      _A						:		List[str]    	=     'blip'
      _A						:		Optional[int]    	=     True
      def __init__(			self		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase=5_12		,	lowerCamelCase=2.6_5_9_2		,	lowerCamelCase=2_56		,	**lowerCamelCase		,	):
          super().__init__(**lowerCamelCase )

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

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

          snake_case__						=				BlipTextConfig(**lowerCamelCase )
          snake_case__						=				BlipVisionConfig(**lowerCamelCase )

          snake_case__						=				self.vision_config.hidden_size

          snake_case__						=				projection_dim
          snake_case__						=				logit_scale_init_value
          snake_case__						=				1.0
          snake_case__						=				0.0_2
          snake_case__						=				image_text_hidden_size
      @classmethod
      def A_			(			cls		,	lowerCamelCase		,	lowerCamelCase		,	**lowerCamelCase ):
          return cls(text_config=text_config.to_dict()		,	vision_config=vision_config.to_dict()		,	**lowerCamelCase )



      def A_			(			self ):
          snake_case__						=				copy.deepcopy(self.__dict__ )
          snake_case__						=				self.text_config.to_dict()
          snake_case__						=				self.vision_config.to_dict()
          snake_case__						=				self.__class__.model_type
          return output





import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
     from .tokenization_pegasus import PegasusTokenizer
else:
     __magic_name__            =  None


__magic_name__            =  logging.get_logger(__name__)


__magic_name__            =  '''▁'''

__magic_name__            =  {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''}

__magic_name__            =  {
    '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''},
    '''tokenizer_file''': {
        '''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/tokenizer.json'''
    },
}

__magic_name__            =  {
    '''google/pegasus-xsum''': 512,
}




class 					_SCREAMING_SNAKE_CASE  (      __UpperCamelCase ):
      _A						:		int    	=     VOCAB_FILES_NAMES
      _A						:		Dict    	=     PRETRAINED_VOCAB_FILES_MAP
      _A						:		Any    	=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      _A						:		Tuple    	=     PegasusTokenizer
      _A						:		str    	=     ['input_ids', 'attention_mask']
      def __init__(			self		,	lowerCamelCase=None		,	lowerCamelCase=None		,	lowerCamelCase="<pad>"		,	lowerCamelCase="</s>"		,	lowerCamelCase="<unk>"		,	lowerCamelCase="<mask_2>"		,	lowerCamelCase="<mask_1>"		,	lowerCamelCase=None		,	lowerCamelCase=1_03		,	**lowerCamelCase		,	):
          snake_case__						=				offset

          if additional_special_tokens is not None:
              if not isinstance(lowerCamelCase		,	lowerCamelCase ):
                  raise TypeError(
                      F"""additional_special_tokens should be of type {type(lowerCamelCase )}, but is"""
                      F""" {type(lowerCamelCase )}""" )

              snake_case__						=				(
                  ([mask_token_sent] + additional_special_tokens)
                  if mask_token_sent not in additional_special_tokens and mask_token_sent is not None
                  else additional_special_tokens
              )
              # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken
              additional_special_tokens_extended += [
                  F"""<unk_{i}>""" for i in range(len(lowerCamelCase )		,	self.offset - 1 )
              ]

              if len(set(lowerCamelCase ) ) != len(lowerCamelCase ):
                  raise ValueError(
                      "Please make sure that the provided additional_special_tokens do not contain an incorrectly"
                      F""" shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.""" )
              snake_case__						=				additional_special_tokens_extended
          else:
              snake_case__						=				[mask_token_sent] if mask_token_sent is not None else []
              additional_special_tokens += [F"""<unk_{i}>""" for i in range(2		,	self.offset )]

          super().__init__(
              lowerCamelCase		,	tokenizer_file=lowerCamelCase		,	pad_token=lowerCamelCase		,	eos_token=lowerCamelCase		,	unk_token=lowerCamelCase		,	mask_token=lowerCamelCase		,	mask_token_sent=lowerCamelCase		,	offset=lowerCamelCase		,	additional_special_tokens=lowerCamelCase		,	**lowerCamelCase		,	)
          snake_case__						=				vocab_file
          snake_case__						=				False if not self.vocab_file else True
      def A_			(			self		,	lowerCamelCase ):
          snake_case__						=				set(self.all_special_ids )  # call it once instead of inside list comp
          all_special_ids.remove(self.unk_token_id )  # <unk> is only sometimes special

          if all_special_ids != set(range(len(self.additional_special_tokens ) + 3 ) ):
              raise ValueError(
                  "There should be 3 special tokens: mask_token, pad_token, and eos_token +"
                  F""" {len(self.additional_special_tokens )} additional_special_tokens, but got {all_special_ids}""" )

          return [1 if x in all_special_ids else 0 for x in seq]
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase = None		,	lowerCamelCase = False ):
          if already_has_special_tokens:
              return self._special_token_mask(lowerCamelCase )
          elif token_ids_a is None:
              return self._special_token_mask(lowerCamelCase ) + [1]
          else:
              return self._special_token_mask(token_ids_a + token_ids_a ) + [1]
      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase=None ):
          if token_ids_a is None:
              return token_ids_a + [self.eos_token_id]
          # We don't expect to process pairs, but leave the pair logic for API consistency
          return token_ids_a + token_ids_a + [self.eos_token_id]



      def A_			(			self		,	lowerCamelCase		,	lowerCamelCase = None ):
          if not self.can_save_slow_tokenizer:
              raise ValueError(
                  "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
                  "tokenizer." )

          if not os.path.isdir(lowerCamelCase ):
              logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
              return
          snake_case__						=				os.path.join(
              lowerCamelCase		,	(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )

          if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCamelCase ):
              copyfile(self.vocab_file		,	lowerCamelCase )

          return (out_vocab_file,)



