

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   __lowercase				(_UpperCAmelCase			):
 _UpperCamelCase        =  VOCAB_FILES_NAMES
 _UpperCamelCase        =  PRETRAINED_VOCAB_FILES_MAP
 _UpperCamelCase        =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 _UpperCamelCase        =  ["""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[str]:



       '''simple docstring'''





       __lowerCAmelCase :						List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs
       __lowerCAmelCase :						int = AddedToken(A_				,							lstrip=A_				,							rstrip=A_ ) if isinstance(A_				,							A_ ) else bos_token
       __lowerCAmelCase :						Optional[int] = AddedToken(A_				,							lstrip=A_				,							rstrip=A_ ) if isinstance(A_				,							A_ ) else eos_token
       __lowerCAmelCase :						int = 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 :						List[str] = legacy
       __lowerCAmelCase :						Dict = vocab_file
       __lowerCAmelCase :						Tuple = add_bos_token
       __lowerCAmelCase :						Union[str, Any] = add_eos_token
       __lowerCAmelCase :						Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs )
       self.sp_model.Load(A_ )
 def __getstate__(							self ) ->List[str]:



       '''simple docstring'''





       __lowerCAmelCase :						Tuple = self.__dict__.copy()
       __lowerCAmelCase :						Optional[Any] = None
       __lowerCAmelCase :						List[Any] = self.sp_model.serialized_model_proto()
       return state
 def __setstate__(							self				,							A_ ) ->Dict:



       '''simple docstring'''





       __lowerCAmelCase :						Tuple = d
       __lowerCAmelCase :						str = spm.SentencePieceProcessor(**self.sp_model_kwargs )
       self.sp_model.LoadFromSerializedProto(self.sp_model_proto )
 @property
 def      UpperCamelCase__  (							self ) ->Any:



       '''simple docstring'''





       return self.sp_model.get_piece_size()
 def      UpperCamelCase__  (							self ) ->Dict:



       '''simple docstring'''





       __lowerCAmelCase :						List[str] = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )}
       vocab.update(self.added_tokens_encoder )
       return vocab
 def      UpperCamelCase__  (							self				,							A_				,							**A_ ) ->List[str]:



       '''simple docstring'''





       if not self.legacy:
             __lowerCAmelCase :						List[Any] = SPIECE_UNDERLINE + text.replace(A_				,							''' ''' )
       return super().tokenize(A_				,							**A_ )
 def      UpperCamelCase__  (							self				,							A_ ) ->int:



       '''simple docstring'''





       if not self.legacy:
             __lowerCAmelCase :						Optional[Any] = text.startswith(A_ )
             if is_first:
                   __lowerCAmelCase :						Any = text[1:]

       __lowerCAmelCase :						Optional[Any] = 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 :						List[str] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
       return tokens
 def      UpperCamelCase__  (							self				,							A_ ) ->List[Any]:



       '''simple docstring'''





       return self.sp_model.piece_to_id(A_ )
 def      UpperCamelCase__  (							self				,							A_ ) ->Dict:



       '''simple docstring'''





       __lowerCAmelCase :						List[Any] = self.sp_model.IdToPiece(A_ )
       return token
 def      UpperCamelCase__  (							self				,							A_ ) ->str:



       '''simple docstring'''





       __lowerCAmelCase :						List[str] = []
       __lowerCAmelCase :						Dict = ''''''
       __lowerCAmelCase :						Any = 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 :						List[str] = True
                   __lowerCAmelCase :						List[str] = []
             else:
                   current_sub_tokens.append(A_ )
                   __lowerCAmelCase :						Optional[int] = False
       out_string += self.sp_model.decode(A_ )
       return out_string
 def      UpperCamelCase__  (							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
       __lowerCAmelCase :						List[str] = 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 :						Dict = self.sp_model.serialized_model_proto()
                   fi.write(A_ )

       return (out_vocab_file,)
 def      UpperCamelCase__  (							self				,							A_				,							A_=None ) ->Any:



       '''simple docstring'''





       __lowerCAmelCase :						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 :						int = bos_token_id + token_ids_a + eos_token_id

       if token_ids_a is not None:
             __lowerCAmelCase :						List[str] = output + bos_token_id + token_ids_a + eos_token_id

       return output
 def      UpperCamelCase__  (							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_ )

       __lowerCAmelCase :						Union[str, Any] = [1] if self.add_bos_token else []
       __lowerCAmelCase :						Optional[int] = [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      UpperCamelCase__  (							self				,							A_				,							A_ = None ) ->List[int]:



       '''simple docstring'''





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

       __lowerCAmelCase :						List[str] = [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				,							A_ ) ->List[int]:



       '''simple docstring'''





       __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 :						Tuple = (
                       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 :						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





def 		_lowercase			(					lowercase__						):
      return "".join(chr(ord(lowercase__						) + 3_2						) if '''A''' <= char <= '''Z''' else char for char in word						)


if __name__ == "__main__":
 from doctest import testmod

 testmod()


