






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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


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


lowercase  :							Optional[int]			  =    '''▁'''

lowercase  :							int			  =    {'''vocab_file''': '''spiece.model'''}

lowercase  :							List[str]			  =    {
    '''vocab_file''': {
        '''google/reformer-crime-and-punishment''': (
            '''https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model'''
        )
    }
}

lowercase  :							Dict			  =    {
    '''google/reformer-crime-and-punishment''': 52_42_88,
}




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




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






						def __init__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE="</s>"		,				_SCREAMING_SNAKE_CASE="<unk>"		,				_SCREAMING_SNAKE_CASE=[]		,				_SCREAMING_SNAKE_CASE = None		,				**_SCREAMING_SNAKE_CASE		,				) ->				None:
								snake_case_				:							Union[str, Any]						 =       {} if sp_model_kwargs is None else sp_model_kwargs

								super().__init__(
								    eos_token=_SCREAMING_SNAKE_CASE		,				unk_token=_SCREAMING_SNAKE_CASE		,				additional_special_tokens=_SCREAMING_SNAKE_CASE		,				sp_model_kwargs=self.sp_model_kwargs		,				**_SCREAMING_SNAKE_CASE		,				)

								snake_case_				:							Dict						 =       vocab_file
								snake_case_				:							List[str]						 =       spm.SentencePieceProcessor(**self.sp_model_kwargs				)
								self.sp_model.Load(_SCREAMING_SNAKE_CASE				)






						@property
						def       _lowerCAmelCase       (	self				) ->				Union[str, Any]:
								return self.sp_model.get_piece_size()






						def       _lowerCAmelCase       (	self				) ->				Dict[str, int]:
								snake_case_				:							Dict						 =       {self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE				): i for i in range(self.vocab_size				)}
								vocab.update(self.added_tokens_encoder				)
								return vocab






						def __getstate__(	self				) ->				List[str]:
								snake_case_				:							Dict						 =       self.__dict__.copy()
								snake_case_				:							Tuple						 =       None
								return state






						def __setstate__(	self		,				_SCREAMING_SNAKE_CASE				) ->				Optional[Any]:
								snake_case_				:							Optional[Any]						 =       d

								# for backward compatibility
								if not hasattr(self		,				"sp_model_kwargs"				):
										snake_case_				:							List[str]						 =       {}

								snake_case_				:							Union[str, Any]						 =       spm.SentencePieceProcessor(**self.sp_model_kwargs				)
								self.sp_model.Load(self.vocab_file				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[str]:
								return self.sp_model.encode(_SCREAMING_SNAKE_CASE		,				out_type=_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				Dict:
								return self.sp_model.piece_to_id(_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				Optional[int]:
								if index < self.sp_model.get_piece_size():
										snake_case_				:							Optional[Any]						 =       self.sp_model.IdToPiece(_SCREAMING_SNAKE_CASE				)
								return token






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE				) ->				List[Any]:
								snake_case_				:							int						 =       []
								snake_case_				:							Tuple						 =       ""
								for token in tokens:
										# make sure that special tokens are not decoded using sentencepiece model
										if token in self.all_special_tokens:
												out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE				) + token
												snake_case_				:							Optional[Any]						 =       []
										else:
												current_sub_tokens.append(_SCREAMING_SNAKE_CASE				)
								out_string += self.sp_model.decode(_SCREAMING_SNAKE_CASE				)
								return out_string.strip()






						def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE = None				) ->				Tuple[str]:
								if not os.path.isdir(_SCREAMING_SNAKE_CASE				):
										logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''				)
										return
								snake_case_				:							List[Any]						 =       os.path.join(
								    _SCREAMING_SNAKE_CASE		,				(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]				)

								if os.path.abspath(self.vocab_file				) != os.path.abspath(_SCREAMING_SNAKE_CASE				) and os.path.isfile(self.vocab_file				):
										copyfile(self.vocab_file		,				_SCREAMING_SNAKE_CASE				)
								elif not os.path.isfile(self.vocab_file				):
										with open(_SCREAMING_SNAKE_CASE		,				"wb"				) as fi:
												snake_case_				:							Optional[int]						 =       self.sp_model.serialized_model_proto()
												fi.write(_SCREAMING_SNAKE_CASE				)

								return (out_vocab_file,)








import copy
import os
from typing import Union

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


lowercase  :							int			  =    logging.get_logger(__name__)

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




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						A     :   int						=					'altclip_text_model'






						def __init__(	self		,				_SCREAMING_SNAKE_CASE=25_0002		,				_SCREAMING_SNAKE_CASE=1024		,				_SCREAMING_SNAKE_CASE=24		,				_SCREAMING_SNAKE_CASE=16		,				_SCREAMING_SNAKE_CASE=4096		,				_SCREAMING_SNAKE_CASE="gelu"		,				_SCREAMING_SNAKE_CASE=0.1		,				_SCREAMING_SNAKE_CASE=0.1		,				_SCREAMING_SNAKE_CASE=514		,				_SCREAMING_SNAKE_CASE=1		,				_SCREAMING_SNAKE_CASE=0.02		,				_SCREAMING_SNAKE_CASE=0.02		,				_SCREAMING_SNAKE_CASE=1e-05		,				_SCREAMING_SNAKE_CASE=1		,				_SCREAMING_SNAKE_CASE=0		,				_SCREAMING_SNAKE_CASE=2		,				_SCREAMING_SNAKE_CASE="absolute"		,				_SCREAMING_SNAKE_CASE=True		,				_SCREAMING_SNAKE_CASE=768		,				**_SCREAMING_SNAKE_CASE		,				) ->				List[str]:
								super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE		,				bos_token_id=_SCREAMING_SNAKE_CASE		,				eos_token_id=_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				)

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




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						A     :   List[Any]						=					'altclip_vision_model'






						def __init__(	self		,				_SCREAMING_SNAKE_CASE=768		,				_SCREAMING_SNAKE_CASE=3072		,				_SCREAMING_SNAKE_CASE=512		,				_SCREAMING_SNAKE_CASE=12		,				_SCREAMING_SNAKE_CASE=12		,				_SCREAMING_SNAKE_CASE=3		,				_SCREAMING_SNAKE_CASE=224		,				_SCREAMING_SNAKE_CASE=32		,				_SCREAMING_SNAKE_CASE="quick_gelu"		,				_SCREAMING_SNAKE_CASE=1e-5		,				_SCREAMING_SNAKE_CASE=0.0		,				_SCREAMING_SNAKE_CASE=0.02		,				_SCREAMING_SNAKE_CASE=1.0		,				**_SCREAMING_SNAKE_CASE		,				) ->				Optional[Any]:
								super().__init__(**_SCREAMING_SNAKE_CASE				)

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






						@classmethod
						def       _lowerCAmelCase       (	cls		,				_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				) ->				"PretrainedConfig":
								cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE				)

								snake_case_ ,       snake_case_				:							str						 =       cls.get_config_dict(_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				)

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




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						A     :   str						=					'altclip'
						A     :   Dict						=					True






						def __init__(	self		,				_SCREAMING_SNAKE_CASE=None		,				_SCREAMING_SNAKE_CASE=None		,				_SCREAMING_SNAKE_CASE=768		,				_SCREAMING_SNAKE_CASE=2.6592		,				**_SCREAMING_SNAKE_CASE				) ->				Optional[int]:
								# 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!).
								snake_case_				:							Optional[Any]						 =       kwargs.pop("text_config_dict"		,				_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Dict						 =       kwargs.pop("vision_config_dict"		,				_SCREAMING_SNAKE_CASE				)

								super().__init__(**_SCREAMING_SNAKE_CASE				)

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

										# This is the complete result when using `text_config_dict`.
										snake_case_				:							str						 =       AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE				).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:
																snake_case_				:							Optional[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:
																snake_case_				:							Dict						 =       (
																    f'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '''
																    f'''value `text_config["{key}"]` will be overriden.'''
																)
														logger.warning(_SCREAMING_SNAKE_CASE				)

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

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

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

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

								if vision_config is None:
										snake_case_				:							Optional[Any]						 =       {}
										logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."				)

								snake_case_				:							List[Any]						 =       AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Union[str, Any]						 =       AltCLIPVisionConfig(**_SCREAMING_SNAKE_CASE				)

								snake_case_				:							Optional[int]						 =       projection_dim
								snake_case_				:							Tuple						 =       logit_scale_init_value
								snake_case_				:							List[Any]						 =       1.0






						@classmethod
						def       _lowerCAmelCase       (	cls		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				) ->				Optional[Any]:
								return cls(text_config=text_config.to_dict()		,				vision_config=vision_config.to_dict()		,				**_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				List[str]:
								snake_case_				:							Any						 =       copy.deepcopy(self.__dict__				)
								snake_case_				:							Union[str, Any]						 =       self.text_config.to_dict()
								snake_case_				:							List[Any]						 =       self.vision_config.to_dict()
								snake_case_				:							Tuple						 =       self.__class__.model_type
								return output
