

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

_SCREAMING_SNAKE_CASE							 =			logging.get_logger(__name__)

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

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

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

# fmt: off
_SCREAMING_SNAKE_CASE							 =			'''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      lowerCamelCase_ (			_lowerCAmelCase):
 _lowerCAmelCase									=	VOCAB_FILES_NAMES
 _lowerCAmelCase									=	PRETRAINED_VOCAB_FILES_MAP
 _lowerCAmelCase									=	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 _lowerCAmelCase									=	['''input_ids''', '''attention_mask''']




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




 def __getstate__(			self							):
   __UpperCAmelCase	:  int		=     self.__dict__.copy()
   __UpperCAmelCase	:  List[str]		=     None
   __UpperCAmelCase	:  Dict		=     self.sp_model.serialized_model_proto()
   return state




 def __setstate__(			self  ,  _UpperCAmelCase							):
   __UpperCAmelCase	:  Optional[Any]		=     d
   __UpperCAmelCase	:  List[str]		=     spm.SentencePieceProcessor(**self.sp_model_kwargs							)
   self.sp_model.LoadFromSerializedProto(self.sp_model_proto							)




 @property
 def     a       (			self							):
   return self.sp_model.get_piece_size()




 def     a       (			self							):
   __UpperCAmelCase	:  List[Any]		=     {self.convert_ids_to_tokens(_UpperCAmelCase							): i for i in range(self.vocab_size							)}
   vocab.update(self.added_tokens_encoder							)
   return vocab




 def     a       (			self  ,  _UpperCAmelCase  ,  **_UpperCAmelCase							):
   # 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:
     __UpperCAmelCase	:  str		=     SPIECE_UNDERLINE + text.replace(_UpperCAmelCase  ,  ' '							)
   return super().tokenize(_UpperCAmelCase  ,  **_UpperCAmelCase							)




 def     a       (			self  ,  _UpperCAmelCase							):
   if not self.legacy:
     __UpperCAmelCase	:  List[str]		=     text.startswith(_UpperCAmelCase							)
     if is_first:
       __UpperCAmelCase	:  str		=     text[1:]

   __UpperCAmelCase	:  Optional[int]		=     self.sp_model.encode(_UpperCAmelCase  ,  out_type=_UpperCAmelCase							)

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




 def     a       (			self  ,  _UpperCAmelCase							):
   return self.sp_model.piece_to_id(_UpperCAmelCase							)




 def     a       (			self  ,  _UpperCAmelCase							):
   __UpperCAmelCase	:  Union[str, Any]		=     self.sp_model.IdToPiece(_UpperCAmelCase							)
   return token




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




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

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

   return (out_vocab_file,)




 def     a       (			self  ,  _UpperCAmelCase  ,  _UpperCAmelCase=None							):
   __UpperCAmelCase	:  Union[str, Any]		=     [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	:  Union[str, Any]		=     output + bos_token_id + token_ids_a + eos_token_id

   return output




 def     a       (			self  ,  _UpperCAmelCase  ,  _UpperCAmelCase = None  ,  _UpperCAmelCase = False							):
   if already_has_special_tokens:
     return super().get_special_tokens_mask(
         token_ids_a=_UpperCAmelCase  ,  token_ids_a=_UpperCAmelCase  ,  already_has_special_tokens=_UpperCAmelCase							)

   __UpperCAmelCase	:  str		=     [1] if self.add_bos_token else []
   __UpperCAmelCase	:  Optional[int]		=     [1] if self.add_eos_token else []

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




 def     a       (			self  ,  _UpperCAmelCase  ,  _UpperCAmelCase = None							):
   __UpperCAmelCase	:  Union[str, Any]		=     [self.bos_token_id] if self.add_bos_token else []
   __UpperCAmelCase	:  int		=     [self.eos_token_id] if self.add_eos_token else []

   __UpperCAmelCase	:  Tuple		=     [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     a       (			self  ,  _UpperCAmelCase							):
   __UpperCAmelCase	:  Tuple		=     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(_UpperCAmelCase							) or E_SYS not in conversation.past_user_inputs[0]:
       __UpperCAmelCase	:  Any		=     (
           B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
       )
   elif not dialogue[0][1].startswith(_UpperCAmelCase							) or E_SYS not in dialogue[0][1]:
     __UpperCAmelCase	:  str		=     (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=_UpperCAmelCase							)
           + [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=_UpperCAmelCase							)
   return dialog_tokens








def  _snake_case		(snake_case_					:     int = 100    ,       snake_case_					:     int = 100  )							->		int:
  return max(
      sum(int(snake_case_  ) for x in str(base**power  )  )
      for base in range(snake_case_  )
      for power in range(snake_case_  )  )


# Tests
if __name__ == "__main__":
      import doctest

      doctest.testmod()





