




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

lowercase			:      Optional[Any]			=					logging.get_logger(__name__)

lowercase			:      List[Any]			=					{"""vocab_file""": """tokenizer.model"""}

lowercase			:      Optional[Any]			=					{
    """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""",
    },
}
lowercase			:      Union[str, Any]			=					{
    """hf-internal-testing/llama-tokenizer""": 2048,
}
lowercase			:      Tuple			=					"""▁"""

lowercase,  lowercase			:      List[Any]			=					"""[INST]""", """[/INST]"""
lowercase,  lowercase			:      Tuple			=					"""<<SYS>>\n""", """\n<</SYS>>\n\n"""

# fmt: off
lowercase			:      List[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 				_a   (a__  ):





     '''simple docstring'''



     lowerCAmelCase_     :    Optional[int]									=				VOCAB_FILES_NAMES
     lowerCAmelCase_     :    Union[str, Any]									=				PRETRAINED_VOCAB_FILES_MAP
     lowerCAmelCase_     :    Union[str, Any]									=				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     lowerCAmelCase_     :    str									=				["""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]:
          snake_case :			Optional[int]					   = {} if sp_model_kwargs is None else sp_model_kwargs
          snake_case :			Union[str, Any]					   = AddedToken(__a       ,lstrip=__a       ,rstrip=__a       ) if isinstance(__a       ,__a       ) else bos_token
          snake_case :			Optional[Any]					   = AddedToken(__a       ,lstrip=__a       ,rstrip=__a       ) if isinstance(__a       ,__a       ) else eos_token
          snake_case :			List[str]					   = AddedToken(__a       ,lstrip=__a       ,rstrip=__a       ) if isinstance(__a       ,__a       ) else unk_token
          snake_case :			List[Any]					   = 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"""       )
          snake_case :			Union[str, Any]					   = legacy
          snake_case :			int					   = vocab_file
          snake_case :			Dict					   = add_bos_token
          snake_case :			Union[str, Any]					   = add_eos_token
          snake_case :			Tuple					   = spm.SentencePieceProcessor(**self.sp_model_kwargs       )
          self.sp_model.Load(__a       )







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







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







     @property
     def  snake_case_			(							self       )			->							Tuple:
          return self.sp_model.get_piece_size()







     def  snake_case_			(							self       )			->							Optional[Any]:
          snake_case :			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  snake_case_			(							self       ,__a       ,**__a       )			->							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:
               snake_case :			List[str]					   = SPIECE_UNDERLINE + text.replace(__a       ,""" """       )
          return super().tokenize(__a       ,**__a       )







     def  snake_case_			(							self       ,__a       )			->							Dict:
          if not self.legacy:
               snake_case :			Dict					   = text.startswith(__a       )
               if is_first:
                    snake_case :			str					   = text[1:]

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







     def  snake_case_			(							self       ,__a       )			->							Dict:
          return self.sp_model.piece_to_id(__a       )







     def  snake_case_			(							self       ,__a       )			->							str:
          snake_case :			List[str]					   = self.sp_model.IdToPiece(__a       )
          return token







     def  snake_case_			(							self       ,__a       )			->							Optional[Any]:
          snake_case :			Optional[int]					   = []
          snake_case :			Optional[int]					   = """"""
          snake_case :			str					   = 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
                    snake_case :			Tuple					   = True
                    snake_case :			List[Any]					   = []
               else:
                    current_sub_tokens.append(__a       )
                    snake_case :			int					   = False
          out_string += self.sp_model.decode(__a       )
          return out_string







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

          return (out_vocab_file,)







     def  snake_case_			(							self       ,__a       ,__a=None       )			->							List[Any]:
          snake_case :			Union[str, Any]					   = [self.bos_token_id] if self.add_bos_token else []
          snake_case :			str					   = [self.eos_token_id] if self.add_eos_token else []

          snake_case :			Optional[Any]					   = bos_token_id + token_ids_a + eos_token_id

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

          return output







     def  snake_case_			(							self       ,__a       ,__a = None       ,__a = 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       )

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

          snake_case :			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]:
          snake_case :			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...)"""       )

          snake_case :			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]:
                    snake_case :			List[str]					   = (
                        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]:
               snake_case :			Optional[int]					   = (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'''







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available


lowercase			:      Tuple			=					{"""configuration_bert_generation""": ["""BertGenerationConfig"""]}

try:
      if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase			:      Tuple			=					["""BertGenerationTokenizer"""]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase			:      List[Any]			=					[
          """BertGenerationDecoder""",
          """BertGenerationEncoder""",
          """BertGenerationPreTrainedModel""",
          """load_tf_weights_in_bert_generation""",
      ]


if TYPE_CHECKING:
      from .configuration_bert_generation import BertGenerationConfig

      try:
            if not is_sentencepiece_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_bert_generation import BertGenerationTokenizer

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_bert_generation import (
                BertGenerationDecoder,
                BertGenerationEncoder,
                BertGenerationPreTrainedModel,
                load_tf_weights_in_bert_generation,
            )

else:
      import sys

      lowercase			:      Optional[Any]			=					_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



