

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

import sentencepiece as spm

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


if TYPE_CHECKING:
       from transformers.pipelines.conversational import Conversation

lowerCamelCase 	=   logging.get_logger(__name__)

lowerCamelCase 	=   {'''vocab_file''': '''tokenizer.model'''}

lowerCamelCase 	=   {
    '''vocab_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model''',
    },
    '''tokenizer_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json''',
    },
}
lowerCamelCase 	=   {
    '''hf-internal-testing/llama-tokenizer''': 2048,
}
lowerCamelCase 	=   '''▁'''

lowerCamelCase	,			lowerCamelCase 	=   '''[INST]''', '''[/INST]'''
lowerCamelCase	,			lowerCamelCase 	=   '''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
lowerCamelCase 	=   '''You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don\'t know the answer to a question, please don\'t share false information.'''







class 		__magic_name__     (				_UpperCAmelCase				):

   '''simple docstring'''




   lowerCamelCase__					:      List[Any]        =  VOCAB_FILES_NAMES
   lowerCamelCase__					:      Tuple        =  PRETRAINED_VOCAB_FILES_MAP
   lowerCamelCase__					:      Optional[int]        =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   lowerCamelCase__					:      List[str]        =  ["""input_ids""", """attention_mask"""]



   def __init__(							self,       lowercase_,       lowercase_="<unk>",       lowercase_="<s>",       lowercase_="</s>",       lowercase_=None,       lowercase_ = None,       lowercase_=True,       lowercase_=False,       lowercase_=False,       lowercase_=True,       **lowercase_,       )				->       List[Any]:






     """simple docstring"""






     a__    ={} if sp_model_kwargs is None else sp_model_kwargs
     a__    =AddedToken(snake_case_,       lstrip=snake_case_,       rstrip=snake_case_			) if isinstance(snake_case_,       snake_case_			) else bos_token
     a__    =AddedToken(snake_case_,       lstrip=snake_case_,       rstrip=snake_case_			) if isinstance(snake_case_,       snake_case_			) else eos_token
     a__    =AddedToken(snake_case_,       lstrip=snake_case_,       rstrip=snake_case_			) if isinstance(snake_case_,       snake_case_			) else unk_token
     a__    =AddedToken(snake_case_,       lstrip=snake_case_,       rstrip=snake_case_			) if isinstance(snake_case_,       snake_case_			) else pad_token
     super().__init__(
         bos_token=snake_case_,       eos_token=snake_case_,       unk_token=snake_case_,       pad_token=snake_case_,       add_bos_token=snake_case_,       add_eos_token=snake_case_,       sp_model_kwargs=self.sp_model_kwargs,       clean_up_tokenization_spaces=snake_case_,       legacy=snake_case_,       **snake_case_,       )
     if legacy:
       logger.warning_once(
           F"""You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to"""
           ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565'''			)
     a__    =legacy
     a__    =vocab_file
     a__    =add_bos_token
     a__    =add_eos_token
     a__    =spm.SentencePieceProcessor(**self.sp_model_kwargs			)
     self.sp_model.Load(snake_case_			)



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






     """simple docstring"""






     a__    =self.__dict__.copy()
     a__    =None
     a__    =self.sp_model.serialized_model_proto()
     return state



   def __setstate__(							self,       lowercase_			)				->       List[str]:






     """simple docstring"""






     a__    =d
     a__    =spm.SentencePieceProcessor(**self.sp_model_kwargs			)
     self.sp_model.LoadFromSerializedProto(self.sp_model_proto			)



   @property
   def 					_UpperCAmelCase					(							self			)				->       Dict:






     """simple docstring"""






     return self.sp_model.get_piece_size()



   def 					_UpperCAmelCase					(							self			)				->       Any:






     """simple docstring"""






     a__    ={self.convert_ids_to_tokens(snake_case_			): i for i in range(self.vocab_size			)}
     vocab.update(self.added_tokens_encoder			)
     return vocab



   def 					_UpperCAmelCase					(							self,       lowercase_,       **lowercase_			)				->       List[str]:






     """simple docstring"""






     if not self.legacy:
       a__    =SPIECE_UNDERLINE + text.replace(snake_case_,       ''' '''			)
     return super().tokenize(snake_case_,       **snake_case_			)



   def 					_UpperCAmelCase					(							self,       lowercase_			)				->       Dict:






     """simple docstring"""






     if not self.legacy:
       a__    =text.startswith(snake_case_			)
       if is_first:
         a__    =text[1:]

     a__    =self.sp_model.encode(snake_case_,       out_type=snake_case_			)

     if not self.legacy and not is_first and not text.startswith(''' '''			) and tokens[0].startswith(snake_case_			):
       a__    =([tokens[0][1:]] if len(tokens[0]			) > 1 else []) + tokens[1:]
     return tokens



   def 					_UpperCAmelCase					(							self,       lowercase_			)				->       List[str]:






     """simple docstring"""






     return self.sp_model.piece_to_id(snake_case_			)



   def 					_UpperCAmelCase					(							self,       lowercase_			)				->       List[str]:






     """simple docstring"""






     a__    =self.sp_model.IdToPiece(snake_case_			)
     return token



   def 					_UpperCAmelCase					(							self,       lowercase_			)				->       int:






     """simple docstring"""






     a__    =[]
     a__    =""
     a__    =False
     for i, token in enumerate(snake_case_			):
       # make sure that special tokens are not decoded using sentencepiece model
       if token in self.all_special_tokens:
         if not prev_is_special and i != 0:
           out_string += " "
         out_string += self.sp_model.decode(snake_case_			) + token
         a__    =True
         a__    =[]
       else:
         current_sub_tokens.append(snake_case_			)
         a__    =False
     out_string += self.sp_model.decode(snake_case_			)
     return out_string



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_ = None			)				->       Optional[int]:






     """simple docstring"""






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

     if os.path.abspath(self.vocab_file			) != os.path.abspath(snake_case_			) and os.path.isfile(self.vocab_file			):
       copyfile(self.vocab_file,       snake_case_			)
     elif not os.path.isfile(self.vocab_file			):
       with open(snake_case_,       '''wb'''			) as fi:
         a__    =self.sp_model.serialized_model_proto()
         fi.write(snake_case_			)

     return (out_vocab_file,)



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_=None			)				->       Optional[int]:






     """simple docstring"""






     a__    =[self.bos_token_id] if self.add_bos_token else []
     a__    =[self.eos_token_id] if self.add_eos_token else []

     a__    =bos_token_id + token_ids_a + eos_token_id

     if token_ids_a is not None:
       a__    =output + bos_token_id + token_ids_a + eos_token_id

     return output



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_ = None,       lowercase_ = False			)				->       str:






     """simple docstring"""






     if already_has_special_tokens:
       return super().get_special_tokens_mask(
           token_ids_a=snake_case_,       token_ids_a=snake_case_,       already_has_special_tokens=snake_case_			)

     a__    =[1] if self.add_bos_token else []
     a__    =[1] if self.add_eos_token else []

     if token_ids_a is None:
       return bos_token_id + ([0] * len(snake_case_			)) + eos_token_id
     return (
         bos_token_id
         + ([0] * len(snake_case_			))
         + eos_token_id
         + bos_token_id
         + ([0] * len(snake_case_			))
         + eos_token_id
     )



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_ = None			)				->       List[str]:






     """simple docstring"""






     a__    =[self.bos_token_id] if self.add_bos_token else []
     a__    =[self.eos_token_id] if self.add_eos_token else []

     a__    =[0] * len(bos_token_id + token_ids_a + eos_token_id			)

     if token_ids_a is not None:
       output += [1] * len(bos_token_id + token_ids_a + eos_token_id			)

     return output



   def 					_UpperCAmelCase					(							self,       lowercase_			)				->       List[str]:






     """simple docstring"""






     a__    =list(conversation.iter_texts()			)
     if not all([is_user for is_user, msg in dialogue[::2]]			) or not all(
         [not is_user for is_user, msg in dialogue[1::2]]			):
       raise ValueError(
           '''The model only supports \'user\' and \'assistant\' roles, starting with user and alternating (u/a/u/a/u...)'''			)

     a__    =[]
     if len(conversation.past_user_inputs			) > 0:
       if not conversation.past_user_inputs[0].startswith(snake_case_			) or E_SYS not in conversation.past_user_inputs[0]:
         a__    =(
             B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
         )
     elif not dialogue[0][1].startswith(snake_case_			) or E_SYS not in dialogue[0][1]:
       a__    =(dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

     dialog_tokens += sum(
         [
             [self.bos_token_id]
             + self.encode(
                 F"""{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} """,       add_special_tokens=snake_case_			)
             + [self.eos_token_id]
             for prompt, answer in zip(dialogue[::2],       dialogue[1::2]			)
         ],       [],       )
     if not (dialogue[-1][0]):
       raise ValueError(F"""Last message must be from user, got {dialogue[-1]["role"]}"""			)
     dialog_tokens += [self.bos_token_id] + self.encode(
         F"""{B_INST} {(dialogue[-1][1]).strip()} {E_INST}""",       add_special_tokens=snake_case_			)
     return dialog_tokens

'''simple docstring'''

import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding




class 		SCREAMING_SNAKE_CASE_					(_UpperCAmelCase      ):



			"""simple docstring"""






			__magic_name__ :				Dict   							=       ["""image_processor""", """tokenizer"""]
			__magic_name__ :				Union[str, Any]   							=       """VideoMAEImageProcessor"""
			__magic_name__ :				List[str]   							=       ("""CLIPTokenizer""", """CLIPTokenizerFast""")



			def __init__(							self				,			snake_case_=None				,			snake_case_=None				,			**snake_case_					):
									snake_case :       int				=    None
									if "feature_extractor" in kwargs:
															warnings.warn(
															    "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
															    " instead."				,			snake_case_				,			)
															snake_case :       Optional[int]				=    kwargs.pop("feature_extractor"					)

									snake_case :       Union[str, Any]				=    image_processor if image_processor is not None else feature_extractor
									if image_processor is None:
															raise ValueError("You need to specify an `image_processor`."					)
									if tokenizer is None:
															raise ValueError("You need to specify a `tokenizer`."					)

									super().__init__(snake_case_				,			snake_case_					)
									snake_case :       List[Any]				=    self.image_processor



			def __call__(							self				,			snake_case_=None				,			snake_case_=None				,			snake_case_=None				,			**snake_case_					):

									if text is None and videos is None:
															raise ValueError("You have to specify either text or videos. Both cannot be none."					)

									if text is not None:
															snake_case :       List[Any]				=    self.tokenizer(snake_case_				,			return_tensors=snake_case_				,			**snake_case_					)

									if videos is not None:
															snake_case :       List[Any]				=    self.image_processor(snake_case_				,			return_tensors=snake_case_				,			**snake_case_					)

									if text is not None and videos is not None:
															snake_case :       Tuple				=    image_features.pixel_values
															return encoding
									elif text is not None:
															return encoding
									else:
															return BatchEncoding(data=dict(**snake_case_					)				,			tensor_type=snake_case_					)



			def   lowerCamelCase (							self				,			*snake_case_				,			**snake_case_					):
									return self.tokenizer.batch_decode(*snake_case_				,			**snake_case_					)



			def   lowerCamelCase (							self				,			*snake_case_				,			**snake_case_					):
									return self.tokenizer.decode(*snake_case_				,			**snake_case_					)



			@property
			def   lowerCamelCase (							self					):
									return ["input_ids", "attention_mask", "position_ids", "pixel_values"]



			@property
			def   lowerCamelCase (							self					):
									warnings.warn(
									    "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."				,			snake_case_				,			)
									return self.image_processor_class






			@property
			def   lowerCamelCase (							self					):
									warnings.warn(
									    "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."				,			snake_case_				,			)
									return self.image_processor





