

"""simple docstring"""






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__			:					Optional[Any]							  =					logging.get_logger(__name__)

lowerCamelCase__			:					List[str]							  =					{'''vocab_file''': '''tokenizer.model'''}

lowerCamelCase__			:					Tuple							  =					{
    '''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__			:					Union[str, Any]							  =					{
    '''hf-internal-testing/llama-tokenizer''': 20_48,
}
lowerCamelCase__			:					str							  =					'''▁'''

lowerCamelCase__  ,					lowerCamelCase__			:					Optional[int]							  =					'''[INST]''', '''[/INST]'''
lowerCamelCase__  ,					lowerCamelCase__			:					Tuple							  =					'''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
lowerCamelCase__			:					Optional[Any]							  =					'''You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
that your responses are socially unbiased and positive in nature.

If a question does not make any sense, or is not factually coherent, explain why instead of answering something not\
correct. If you don\'t know the answer to a question, please don\'t share false information.'''






class       _UpperCAmelCase     (						__a):
			__a	:    Dict			   =							VOCAB_FILES_NAMES
			__a	:    int			   =							PRETRAINED_VOCAB_FILES_MAP
			__a	:    Union[str, Any]			   =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			__a	:    Any			   =							["""input_ids""", """attention_mask"""]
			def __init__(						self ,						_A ,						_A="<unk>" ,						_A="<s>" ,						_A="</s>" ,						_A=None ,						_A = None ,						_A=True ,						_A=False ,						_A=False ,						_A=True ,						**_A ,						)      ->      List[Any]:






				'''simple docstring'''







				_UpperCAmelCase      :							str       =   {} if sp_model_kwargs is None else sp_model_kwargs
				_UpperCAmelCase      :							int       =   AddedToken(_A ,						lstrip=_A ,						rstrip=_A       ) if isinstance(_A ,						_A       ) else bos_token
				_UpperCAmelCase      :							Optional[int]       =   AddedToken(_A ,						lstrip=_A ,						rstrip=_A       ) if isinstance(_A ,						_A       ) else eos_token
				_UpperCAmelCase      :							Tuple       =   AddedToken(_A ,						lstrip=_A ,						rstrip=_A       ) if isinstance(_A ,						_A       ) else unk_token
				_UpperCAmelCase      :							Tuple       =   AddedToken(_A ,						lstrip=_A ,						rstrip=_A       ) if isinstance(_A ,						_A       ) else pad_token
				super().__init__(
				    bos_token=_A ,						eos_token=_A ,						unk_token=_A ,						pad_token=_A ,						add_bos_token=_A ,						add_eos_token=_A ,						sp_model_kwargs=self.sp_model_kwargs ,						clean_up_tokenization_spaces=_A ,						legacy=_A ,						**_A ,						)
				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"""       )
				_UpperCAmelCase      :							Tuple       =   legacy
				_UpperCAmelCase      :							Optional[Any]       =   vocab_file
				_UpperCAmelCase      :							List[str]       =   add_bos_token
				_UpperCAmelCase      :							int       =   add_eos_token
				_UpperCAmelCase      :							Any       =   spm.SentencePieceProcessor(**self.sp_model_kwargs       )
				self.sp_model.Load(_A       )
			def __getstate__(						self       )      ->      str:






				'''simple docstring'''







				_UpperCAmelCase      :							Dict       =   self.__dict__.copy()
				_UpperCAmelCase      :							str       =   None
				_UpperCAmelCase      :							List[Any]       =   self.sp_model.serialized_model_proto()
				return state
			def __setstate__(						self ,						_A       )      ->      List[Any]:






				'''simple docstring'''







				_UpperCAmelCase      :							str       =   d
				_UpperCAmelCase      :							List[Any]       =   spm.SentencePieceProcessor(**self.sp_model_kwargs       )
				self.sp_model.LoadFromSerializedProto(self.sp_model_proto       )
			@property
			def 							__snake_case	(						self       )      ->      Tuple:






				'''simple docstring'''







				return self.sp_model.get_piece_size()
			def 							__snake_case	(						self       )      ->      str:






				'''simple docstring'''







				_UpperCAmelCase      :							Tuple       =   {self.convert_ids_to_tokens(_A       ): i for i in range(self.vocab_size       )}
				vocab.update(self.added_tokens_encoder       )
				return vocab
			def 							__snake_case	(						self ,						_A ,						**_A       )      ->      List[str]:






				'''simple docstring'''







				if not self.legacy:
					_UpperCAmelCase      :							Tuple       =   SPIECE_UNDERLINE + text.replace(_A ,						""" """       )
				return super().tokenize(_A ,						**_A       )
			def 							__snake_case	(						self ,						_A       )      ->      int:






				'''simple docstring'''







				if not self.legacy:
					_UpperCAmelCase      :							Any       =   text.startswith(_A       )
					if is_first:
						_UpperCAmelCase      :							int       =   text[1:]

				_UpperCAmelCase      :							Dict       =   self.sp_model.encode(_A ,						out_type=_A       )

				if not self.legacy and not is_first and not text.startswith(""" """       ) and tokens[0].startswith(_A       ):
					_UpperCAmelCase      :							Union[str, Any]       =   ([tokens[0][1:]] if len(tokens[0]       ) > 1 else []) + tokens[1:]
				return tokens
			def 							__snake_case	(						self ,						_A       )      ->      int:






				'''simple docstring'''







				return self.sp_model.piece_to_id(_A       )
			def 							__snake_case	(						self ,						_A       )      ->      Union[str, Any]:






				'''simple docstring'''







				_UpperCAmelCase      :							Any       =   self.sp_model.IdToPiece(_A       )
				return token
			def 							__snake_case	(						self ,						_A       )      ->      Union[str, Any]:






				'''simple docstring'''







				_UpperCAmelCase      :							Optional[Any]       =   []
				_UpperCAmelCase      :							str       =   """"""
				_UpperCAmelCase      :							Tuple       =   False
				for i, token in enumerate(_A       ):
					# 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(_A       ) + token
						_UpperCAmelCase      :							Any       =   True
						_UpperCAmelCase      :							Optional[Any]       =   []
					else:
						current_sub_tokens.append(_A       )
						_UpperCAmelCase      :							int       =   False
				out_string += self.sp_model.decode(_A       )
				return out_string
			def 							__snake_case	(						self ,						_A ,						_A = None       )      ->      Tuple[str]:






				'''simple docstring'''







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

				if os.path.abspath(self.vocab_file       ) != os.path.abspath(_A       ) and os.path.isfile(self.vocab_file       ):
					copyfile(self.vocab_file ,						_A       )
				elif not os.path.isfile(self.vocab_file       ):
					with open(_A ,						"""wb"""       ) as fi:
						_UpperCAmelCase      :							str       =   self.sp_model.serialized_model_proto()
						fi.write(_A       )

				return (out_vocab_file,)
			def 							__snake_case	(						self ,						_A ,						_A=None       )      ->      Dict:






				'''simple docstring'''







				_UpperCAmelCase      :							str       =   [self.bos_token_id] if self.add_bos_token else []
				_UpperCAmelCase      :							List[Any]       =   [self.eos_token_id] if self.add_eos_token else []

				_UpperCAmelCase      :							Optional[int]       =   bos_token_id + token_ids_a + eos_token_id

				if token_ids_a is not None:
					_UpperCAmelCase      :							Any       =   output + bos_token_id + token_ids_a + eos_token_id

				return output
			def 							__snake_case	(						self ,						_A ,						_A = None ,						_A = False       )      ->      List[int]:






				'''simple docstring'''







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

				_UpperCAmelCase      :							Any       =   [1] if self.add_bos_token else []
				_UpperCAmelCase      :							Dict       =   [1] if self.add_eos_token else []

				if token_ids_a is None:
					return bos_token_id + ([0] * len(_A       )) + eos_token_id
				return (
				    bos_token_id
				    + ([0] * len(_A       ))
				    + eos_token_id
				    + bos_token_id
				    + ([0] * len(_A       ))
				    + eos_token_id
				)
			def 							__snake_case	(						self ,						_A ,						_A = None       )      ->      List[int]:






				'''simple docstring'''







				_UpperCAmelCase      :							Tuple       =   [self.bos_token_id] if self.add_bos_token else []
				_UpperCAmelCase      :							Any       =   [self.eos_token_id] if self.add_eos_token else []

				_UpperCAmelCase      :							Dict       =   [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 							__snake_case	(						self ,						_A       )      ->      List[int]:






				'''simple docstring'''







				_UpperCAmelCase      :							str       =   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...)"""       )

				_UpperCAmelCase      :							List[int]       =   []
				if len(conversation.past_user_inputs       ) > 0:
					if not conversation.past_user_inputs[0].startswith(_A       ) or E_SYS not in conversation.past_user_inputs[0]:
						_UpperCAmelCase      :							Union[str, Any]       =   (
						    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
						)
				elif not dialogue[0][1].startswith(_A       ) or E_SYS not in dialogue[0][1]:
					_UpperCAmelCase      :							Optional[Any]       =   (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=_A       )
				        + [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=_A       )
				return dialog_tokens








"""simple docstring"""






def  UpperCamelCase   (     _lowerCAmelCase       :  float,					_lowerCAmelCase       :  float,					_lowerCAmelCase       :  float	)			->     float:
	if mass < 0:
		raise ValueError("""The mass of the body cannot be negative"""	)
	if radius <= 0:
		raise ValueError("""The radius is always a positive non zero integer"""	)
	return (mass * (velocity) ** 2) / radius


if __name__ == "__main__":
						import doctest

						doctest.testmod(verbose=True)





