



'''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

_UpperCamelCase							    =						logging.get_logger(__name__)

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

_UpperCamelCase							    =						{
    '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',
    },
}
_UpperCamelCase							    =						{
    'hf-internal-testing/llama-tokenizer': 2048,
}
_UpperCamelCase							    =						'▁'

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

# fmt: off
_UpperCamelCase							    =						'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  lowerCamelCase_   (    SCREAMING_SNAKE_CASE_					):
  """simple docstring"""




  a_							 =VOCAB_FILES_NAMES
  a_							 =PRETRAINED_VOCAB_FILES_MAP
  a_							 =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a_							 =["""input_ids""", """attention_mask"""]




  def __init__(			self				:     Union[str, Any]      ,     _a				:     List[Any]      ,     _a				:     str="<unk>"      ,     _a				:     Tuple="<s>"      ,     _a				:     Optional[Any]="</s>"      ,     _a				:     Any=None      ,     _a				:     Optional[Dict[str, Any]] = None      ,     _a				:     Optional[Any]=True      ,     _a				:     Optional[int]=False      ,     _a				:     str=False      ,     _a				:     Optional[Any]=True      ,     **_a				:     Union[str, Any]      ,     ) -> int:
    __lowerCamelCase	:	List[str]   	=			{} if sp_model_kwargs is None else sp_model_kwargs
    __lowerCamelCase	:	Optional[int]   	=			AddedToken(_a      ,     lstrip=_a      ,     rstrip=_a       ) if isinstance(_a      ,     _a       ) else bos_token
    __lowerCamelCase	:	Optional[Any]   	=			AddedToken(_a      ,     lstrip=_a      ,     rstrip=_a       ) if isinstance(_a      ,     _a       ) else eos_token
    __lowerCamelCase	:	str   	=			AddedToken(_a      ,     lstrip=_a      ,     rstrip=_a       ) if isinstance(_a      ,     _a       ) else unk_token
    __lowerCamelCase	:	Dict   	=			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'       )
    __lowerCamelCase	:	Any   	=			legacy
    __lowerCamelCase	:	Tuple   	=			vocab_file
    __lowerCamelCase	:	List[str]   	=			add_bos_token
    __lowerCamelCase	:	Tuple   	=			add_eos_token
    __lowerCamelCase	:	int   	=			spm.SentencePieceProcessor(**self.sp_model_kwargs       )
    self.sp_model.Load(_a       )




  def __getstate__(			self				:     List[str]       ) -> Optional[int]:
    __lowerCamelCase	:	Any   	=			self.__dict__.copy()
    __lowerCamelCase	:	List[str]   	=			None
    __lowerCamelCase	:	int   	=			self.sp_model.serialized_model_proto()
    return state




  def __setstate__(			self				:     List[Any]      ,     _a				:     str       ) -> Tuple:
    __lowerCamelCase	:	List[Any]   	=			d
    __lowerCamelCase	:	Dict   	=			spm.SentencePieceProcessor(**self.sp_model_kwargs       )
    self.sp_model.LoadFromSerializedProto(self.sp_model_proto       )




  @property
  def 						_lowercase					(			self				:     int       ) -> Any:
    return self.sp_model.get_piece_size()




  def 						_lowercase					(			self				:     Tuple       ) -> Optional[Any]:
    __lowerCamelCase	:	List[Any]   	=			{self.convert_ids_to_tokens(_a       ): i for i in range(self.vocab_size       )}
    vocab.update(self.added_tokens_encoder       )
    return vocab




  def 						_lowercase					(			self				:     Optional[Any]      ,     _a				:     str      ,     **_a				:     str       ) -> List[str]:
    # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
    # the beginning of the text
    if not self.legacy:
      __lowerCamelCase	:	str   	=			SPIECE_UNDERLINE + text.replace(_a      ,     ' '       )
    return super().tokenize(_a      ,     **_a       )




  def 						_lowercase					(			self				:     Any      ,     _a				:     Union[str, Any]       ) -> Union[str, Any]:
    if not self.legacy:
      __lowerCamelCase	:	List[Any]   	=			text.startswith(_a       )
      if is_first:
        __lowerCamelCase	:	Optional[int]   	=			text[1:]

    __lowerCamelCase	:	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       ):
      __lowerCamelCase	:	Optional[int]   	=			([tokens[0][1:]] if len(tokens[0]       ) > 1 else []) + tokens[1:]
    return tokens




  def 						_lowercase					(			self				:     Optional[int]      ,     _a				:     Optional[Any]       ) -> int:
    return self.sp_model.piece_to_id(_a       )




  def 						_lowercase					(			self				:     int      ,     _a				:     Optional[int]       ) -> List[str]:
    __lowerCamelCase	:	Dict   	=			self.sp_model.IdToPiece(_a       )
    return token




  def 						_lowercase					(			self				:     int      ,     _a				:     List[str]       ) -> int:
    __lowerCamelCase	:	List[Any]   	=			[]
    __lowerCamelCase	:	Optional[int]   	=			''
    __lowerCamelCase	:	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
        __lowerCamelCase	:	Optional[Any]   	=			True
        __lowerCamelCase	:	Optional[int]   	=			[]
      else:
        current_sub_tokens.append(_a       )
        __lowerCamelCase	:	Union[str, Any]   	=			False
    out_string += self.sp_model.decode(_a       )
    return out_string




  def 						_lowercase					(			self				:     Tuple      ,     _a				:     Dict      ,     _a				:     Optional[str] = None       ) -> Tuple[str]:
    if not os.path.isdir(_a       ):
      logger.error(f'Vocabulary path ({save_directory}) should be a directory'       )
      return
    __lowerCamelCase	:	Optional[int]   	=			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:
        __lowerCamelCase	:	Any   	=			self.sp_model.serialized_model_proto()
        fi.write(_a       )

    return (out_vocab_file,)




  def 						_lowercase					(			self				:     List[Any]      ,     _a				:     Tuple      ,     _a				:     Optional[int]=None       ) -> Optional[Any]:
    __lowerCamelCase	:	List[str]   	=			[self.bos_token_id] if self.add_bos_token else []
    __lowerCamelCase	:	Optional[int]   	=			[self.eos_token_id] if self.add_eos_token else []

    __lowerCamelCase	:	Tuple   	=			bos_token_id + token_ids_a + eos_token_id

    if token_ids_a is not None:
      __lowerCamelCase	:	Dict   	=			output + bos_token_id + token_ids_a + eos_token_id

    return output




  def 						_lowercase					(			self				:     Tuple      ,     _a				:     List[int]      ,     _a				:     Optional[List[int]] = None      ,     _a				:     bool = False       ) -> List[int]:
    if already_has_special_tokens:
      return super().get_special_tokens_mask(
          token_ids_a=_a      ,     token_ids_a=_a      ,     already_has_special_tokens=_a       )

    __lowerCamelCase	:	List[Any]   	=			[1] if self.add_bos_token else []
    __lowerCamelCase	:	Optional[Any]   	=			[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 						_lowercase					(			self				:     List[str]      ,     _a				:     List[int]      ,     _a				:     Optional[List[int]] = None       ) -> List[int]:
    __lowerCamelCase	:	Dict   	=			[self.bos_token_id] if self.add_bos_token else []
    __lowerCamelCase	:	str   	=			[self.eos_token_id] if self.add_eos_token else []

    __lowerCamelCase	:	Optional[Any]   	=			[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 						_lowercase					(			self				:     str      ,     _a				:     "Conversation"       ) -> List[int]:
    __lowerCamelCase	:	Any   	=			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...)'       )

    __lowerCamelCase	:	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]:
        __lowerCamelCase	:	Dict   	=			(
            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]:
      __lowerCamelCase	:	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'''





import math
from timeit import timeit

def 	a_					(							_lowerCAmelCase	)				->				int:
  __lowerCamelCase	:	int   	=			0
  __lowerCamelCase	:	Optional[int]   	=			abs(_lowerCAmelCase	)
  while True:
    __lowerCamelCase	:	List[str]   	=			n // 10
    digits += 1
    if n == 0:
      break
  return digits

def 	a_					(							_lowerCAmelCase	)				->				int:
  return 1 if n == 0 else math.floor(math.log(abs(_lowerCAmelCase	)	,10	) + 1	)

def 	a_					(							_lowerCAmelCase	)				->				int:
  return len(str(abs(_lowerCAmelCase	)	)	)

def 	a_					(							)				->				None:
  from collections.abc import Callable

  def benchmark_a_function(_lowerCAmelCase	,_lowerCAmelCase	) -> None:
    __lowerCamelCase	:	Any   	=			F'{func.__name__}({value})'
    __lowerCamelCase	:	int   	=			timeit(F'__main__.{call}'	,setup='import __main__'	)
    print(F'{call}: {func(_lowerCAmelCase	)} -- {timing} seconds'	)

  for value in (262144, 1125899906842624, 1267650600228229401496703205376):
    for func in (num_digits, num_digits_fast, num_digits_faster):
      benchmark_a_function(_lowerCAmelCase	,_lowerCAmelCase	)
    print()


if __name__ == "__main__":
   import doctest

   doctest.testmod()
   benchmark()






