

import copy
import os
from typing import Union

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


_a		       =   logging.get_logger(__name__)

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






class 							A_ (		__lowerCAmelCase					):
     _lowercase			:     str								=	'altclip_text_model'


     def __init__(							self			:		Dict			,  UpperCAmelCase			:		Union[str, Any]=2_5_0_0_0_2			,  UpperCAmelCase			:		List[Any]=1_0_2_4			,  UpperCAmelCase			:		Optional[int]=2_4			,  UpperCAmelCase			:		Any=1_6			,  UpperCAmelCase			:		Dict=4_0_9_6			,  UpperCAmelCase			:		Optional[Any]="gelu"			,  UpperCAmelCase			:		Any=0.1			,  UpperCAmelCase			:		Union[str, Any]=0.1			,  UpperCAmelCase			:		List[Any]=5_1_4			,  UpperCAmelCase			:		Optional[Any]=1			,  UpperCAmelCase			:		Any=0.02			,  UpperCAmelCase			:		Dict=0.02			,  UpperCAmelCase			:		Any=1E-05			,  UpperCAmelCase			:		Optional[int]=1			,  UpperCAmelCase			:		Union[str, Any]=0			,  UpperCAmelCase			:		Any=2			,  UpperCAmelCase			:		Union[str, Any]="absolute"			,  UpperCAmelCase			:		Dict=True			,  UpperCAmelCase			:		Any=7_6_8			,  **UpperCAmelCase			:		Dict			,  )							->	Any:
      super().__init__(pad_token_id=UpperCAmelCase			,  bos_token_id=UpperCAmelCase			,  eos_token_id=UpperCAmelCase			,  **UpperCAmelCase					)

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







class 							A_ (		__lowerCAmelCase					):
     _lowercase			:     Any								=	'altclip_vision_model'


     def __init__(							self			:		Union[str, Any]			,  UpperCAmelCase			:		int=7_6_8			,  UpperCAmelCase			:		List[Any]=3_0_7_2			,  UpperCAmelCase			:		List[Any]=5_1_2			,  UpperCAmelCase			:		List[str]=1_2			,  UpperCAmelCase			:		Optional[int]=1_2			,  UpperCAmelCase			:		Dict=3			,  UpperCAmelCase			:		Optional[int]=2_2_4			,  UpperCAmelCase			:		List[str]=3_2			,  UpperCAmelCase			:		str="quick_gelu"			,  UpperCAmelCase			:		Dict=1E-5			,  UpperCAmelCase			:		Optional[int]=0.0			,  UpperCAmelCase			:		List[str]=0.02			,  UpperCAmelCase			:		List[str]=1.0			,  **UpperCAmelCase			:		Dict			,  )							->	List[str]:
      super().__init__(**UpperCAmelCase					)

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


     @classmethod
     def   UpperCAmelCase  (							cls			:		Tuple			,  UpperCAmelCase			:		List[Any]			,  **UpperCAmelCase			:		Any					)							->	"PretrainedConfig":
      cls._set_token_in_kwargs(UpperCAmelCase					)

      __lowerCAmelCase:   int   	=      cls.get_config_dict(UpperCAmelCase			,  **UpperCAmelCase					)

      # get the vision config dict if we are loading from AltCLIPConfig
      if config_dict.get('model_type'					) == "altclip":
       __lowerCAmelCase:   str   	=      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(UpperCAmelCase			,  **UpperCAmelCase					)







class 							A_ (		__lowerCAmelCase					):
     _lowercase			:     Optional[Any]								=	'altclip'
     _lowercase			:     Optional[int]								=	True


     def __init__(							self			:		List[str]			,  UpperCAmelCase			:		Any=None			,  UpperCAmelCase			:		Dict=None			,  UpperCAmelCase			:		Dict=7_6_8			,  UpperCAmelCase			:		str=2.6592			,  **UpperCAmelCase			:		int					)							->	str:
      __lowerCAmelCase:   List[Any]   	=      kwargs.pop('text_config_dict'			,  UpperCAmelCase					)
      __lowerCAmelCase:   Tuple   	=      kwargs.pop('vision_config_dict'			,  UpperCAmelCase					)

      super().__init__(**UpperCAmelCase					)

      # 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:   str   	=      {}

       # This is the complete result when using `text_config_dict`.
       __lowerCAmelCase:   int   	=      AltCLIPTextConfig(**UpperCAmelCase					).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:   Union[str, Any]   	=      (
              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:   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(UpperCAmelCase					)

        # 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:   Optional[Any]   	=      {}

       # This is the complete result when using `vision_config_dict`.
       __lowerCAmelCase:   List[str]   	=      AltCLIPVisionConfig(**UpperCAmelCase					).to_dict()
       # convert keys to string instead of integer
       if "id2label" in _vision_config_dict:
        __lowerCAmelCase:   str   	=      {
            str(UpperCAmelCase					): 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:   List[str]   	=      (
              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:   Optional[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(UpperCAmelCase					)

        # 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:   Union[str, Any]   	=      {}
       logger.info('`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.'					)

      __lowerCAmelCase:   int   	=      AltCLIPTextConfig(**UpperCAmelCase					)
      __lowerCAmelCase:   Optional[int]   	=      AltCLIPVisionConfig(**UpperCAmelCase					)

      __lowerCAmelCase:   Optional[Any]   	=      projection_dim
      __lowerCAmelCase:   List[str]   	=      logit_scale_init_value
      __lowerCAmelCase:   int   	=      1.0


     @classmethod
     def   UpperCAmelCase  (							cls			:		Dict			,  UpperCAmelCase			:		Tuple			,  UpperCAmelCase			:		int			,  **UpperCAmelCase			:		Any					)							->	Any:
      return cls(text_config=text_config.to_dict()			,  vision_config=vision_config.to_dict()			,  **UpperCAmelCase					)


     def   UpperCAmelCase  (							self			:		Optional[Any]					)							->	str:
      __lowerCAmelCase:   Optional[Any]   	=      copy.deepcopy(self.__dict__					)
      __lowerCAmelCase:   Tuple   	=      self.text_config.to_dict()
      __lowerCAmelCase:   Optional[int]   	=      self.vision_config.to_dict()
      __lowerCAmelCase:   str   	=      self.__class__.model_type
      return output






"""simple docstring"""
import unittest

from transformers import CamembertTokenizer, CamembertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.utils import is_torch_available

from ...test_tokenization_common import TokenizerTesterMixin


lowercase__					       =	get_tests_dir('fixtures/test_sentencepiece.model')
lowercase__					       =	get_tests_dir('fixtures/test_sentencepiece_bpe.model')

lowercase__					       =	'pt' if is_torch_available() else 'tf'




@require_sentencepiece
@require_tokenizers
class    __snake_case       (     __lowerCAmelCase       ,      unittest.TestCase				):
      a__        =		CamembertTokenizer
      a__        =		CamembertTokenizerFast
      a__        =		True
      a__        =		True



      def   lowerCamelCase_   (						self)	->			Union[str, Any]:





        '''simple docstring'''





        super().setUp()

        # We have a SentencePiece fixture for testing
        a__:     Tuple										=	CamembertTokenizer(lowercase)
        tokenizer.save_pretrained(self.tmpdirname)



      def   lowerCamelCase_   (						self)	->			List[str]:





        '''simple docstring'''





        a__:     Optional[Any]										=	'<pad>'
        a__:     List[Any]										=	1

        self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase)    ,			lowercase)
        self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase)    ,			lowercase)



      def   lowerCamelCase_   (						self)	->			Any:





        '''simple docstring'''





        a__:     str										=	list(self.get_tokenizer().get_vocab().keys())

        self.assertEqual(vocab_keys[0]    ,			'<s>NOTUSED')
        self.assertEqual(vocab_keys[1]    ,			'<pad>')
        self.assertEqual(vocab_keys[-1]    ,			'<mask>')
        self.assertEqual(len(lowercase)    ,			10_04)



      def   lowerCamelCase_   (						self)	->			Any:





        '''simple docstring'''





        self.assertEqual(self.get_tokenizer().vocab_size    ,			10_05)



      def   lowerCamelCase_   (						self)	->			Optional[Any]:





        '''simple docstring'''





        a__:     Optional[Any]										=	CamembertTokenizer(lowercase)
        tokenizer.save_pretrained(self.tmpdirname)
        a__:     List[Any]										=	CamembertTokenizerFast.from_pretrained(self.tmpdirname)

        a__:     Dict										=	'I was born in 92000, and this is falsé.'

        a__:     Optional[int]										=	tokenizer.encode(lowercase)
        a__:     Any										=	rust_tokenizer.encode(lowercase)
        self.assertListEqual(lowercase    ,			lowercase)

        a__:     Optional[Any]										=	tokenizer.encode(lowercase    ,			add_special_tokens=lowercase)
        a__:     str										=	rust_tokenizer.encode(lowercase    ,			add_special_tokens=lowercase)
        self.assertListEqual(lowercase    ,			lowercase)

        # <unk> tokens are not the same for `rust` than for `slow`.
        # Because spm gives back raw token instead of `unk` in EncodeAsPieces
        # tokens = tokenizer.tokenize(sequence)
        a__:     Tuple										=	tokenizer.convert_ids_to_tokens(lowercase)
        a__:     Tuple										=	rust_tokenizer.tokenize(lowercase)
        self.assertListEqual(lowercase    ,			lowercase)



      def   lowerCamelCase_   (						self)	->			Dict:





        '''simple docstring'''





        if not self.test_rust_tokenizer:
          return

        a__:     Dict										=	self.get_tokenizer()
        a__:     str										=	self.get_rust_tokenizer()

        a__:     int										=	'I was born in 92000, and this is falsé.'

        a__:     Optional[Any]										=	tokenizer.tokenize(lowercase)
        a__:     List[Any]										=	rust_tokenizer.tokenize(lowercase)
        self.assertListEqual(lowercase    ,			lowercase)

        a__:     str										=	tokenizer.encode(lowercase    ,			add_special_tokens=lowercase)
        a__:     str										=	rust_tokenizer.encode(lowercase    ,			add_special_tokens=lowercase)
        self.assertListEqual(lowercase    ,			lowercase)

        a__:     Tuple										=	self.get_rust_tokenizer()
        a__:     Union[str, Any]										=	tokenizer.encode(lowercase)
        a__:     List[Any]										=	rust_tokenizer.encode(lowercase)
        self.assertListEqual(lowercase    ,			lowercase)



      @slow
      def   lowerCamelCase_   (						self)	->			Optional[Any]:





        '''simple docstring'''





        a__:     Union[str, Any]										=	{'input_ids': [[5, 54, 71_96, 2_97, 30, 23, 7_76, 18, 11, 32_15, 37_05, 82_52, 22, 31_64, 11_81, 21_16, 29, 16, 8_13, 25, 7_91, 33_14, 20, 34_46, 38, 2_75_75, 1_20, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_68, 17, 11, 90_88, 20, 15_17, 8, 2_28_04, 1_88_18, 10, 38, 6_29, 6_07, 6_07, 1_42, 19, 71_96, 8_67, 56, 1_03_26, 24, 22_67, 20, 4_16, 50_72, 1_56_12, 2_33, 7_34, 7, 23_99, 27, 16, 30_15, 16_49, 7, 24, 20, 43_38, 23_99, 27, 13, 34_00, 14, 13, 61_89, 8, 9_30, 9, 6]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}  # noqa: E501
        # fmt: on

        # camembert is a french model. So we also use french texts.
        a__:     int										=	[
            'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, '
            'utilisé principalement dans le domaine du traitement automatique des langues (TAL).',
            'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus '
            'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches '
            'telles que la traduction et la synthèse de texte.',
        ]

        self.tokenizer_integration_test_util(
            expected_encoding=lowercase    ,			model_name='camembert-base'    ,			revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf'    ,			sequences=lowercase    ,			)


