






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

__snake_case							 =  logging.get_logger(__name__)

__snake_case							 =  {"""vocab_file""": """tokenizer.model"""}

__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""",
    },
}
__snake_case							 =  {
    """hf-internal-testing/llama-tokenizer""": 20_48,
}
__snake_case							 =  """▁"""

__snake_case ,				__snake_case							 =  """[INST]""", """[/INST]"""
__snake_case ,				__snake_case							 =  """<<SYS>>\n""", """\n<</SYS>>\n\n"""

# fmt: off
__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       UpperCAmelCase_						( lowercase			):



      """simple docstring"""
      UpperCamelCase_    : Any									=VOCAB_FILES_NAMES
      UpperCamelCase_    : int									=PRETRAINED_VOCAB_FILES_MAP
      UpperCamelCase_    : str									=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      UpperCamelCase_    : Any									=['input_ids', 'attention_mask']
      def __init__(    self   ,    SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_="<unk>"   ,    SCREAMING_SNAKE_CASE_="<s>"   ,    SCREAMING_SNAKE_CASE_="</s>"   ,    SCREAMING_SNAKE_CASE_=None   ,    SCREAMING_SNAKE_CASE_ = None   ,    SCREAMING_SNAKE_CASE_=True   ,    SCREAMING_SNAKE_CASE_=False   ,    SCREAMING_SNAKE_CASE_=False   ,    SCREAMING_SNAKE_CASE_=True   ,    **SCREAMING_SNAKE_CASE_   ,    )    ->				int:
          UpperCamelCase	:int     							=       {} if sp_model_kwargs is None else sp_model_kwargs
          UpperCamelCase	:Union[str, Any]     							=       AddedToken(SCREAMING_SNAKE_CASE_   ,    lstrip=SCREAMING_SNAKE_CASE_   ,    rstrip=SCREAMING_SNAKE_CASE_			) if isinstance(SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_			) else bos_token
          UpperCamelCase	:Dict     							=       AddedToken(SCREAMING_SNAKE_CASE_   ,    lstrip=SCREAMING_SNAKE_CASE_   ,    rstrip=SCREAMING_SNAKE_CASE_			) if isinstance(SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_			) else eos_token
          UpperCamelCase	:Any     							=       AddedToken(SCREAMING_SNAKE_CASE_   ,    lstrip=SCREAMING_SNAKE_CASE_   ,    rstrip=SCREAMING_SNAKE_CASE_			) if isinstance(SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_			) else unk_token
          UpperCamelCase	:Optional[int]     							=       AddedToken(SCREAMING_SNAKE_CASE_   ,    lstrip=SCREAMING_SNAKE_CASE_   ,    rstrip=SCREAMING_SNAKE_CASE_			) if isinstance(SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_			) else pad_token
          super().__init__(
              bos_token=SCREAMING_SNAKE_CASE_   ,    eos_token=SCREAMING_SNAKE_CASE_   ,    unk_token=SCREAMING_SNAKE_CASE_   ,    pad_token=SCREAMING_SNAKE_CASE_   ,    add_bos_token=SCREAMING_SNAKE_CASE_   ,    add_eos_token=SCREAMING_SNAKE_CASE_   ,    sp_model_kwargs=self.sp_model_kwargs   ,    clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE_   ,    legacy=SCREAMING_SNAKE_CASE_   ,    **SCREAMING_SNAKE_CASE_   ,    )
          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	:List[str]     							=       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(SCREAMING_SNAKE_CASE_			)
      def __getstate__(    self			)    ->				List[Any]:
          UpperCamelCase	:Optional[int]     							=       self.__dict__.copy()
          UpperCamelCase	:Tuple     							=       None
          UpperCamelCase	:Optional[int]     							=       self.sp_model.serialized_model_proto()
          return state
      def __setstate__(    self   ,    SCREAMING_SNAKE_CASE_			)    ->				Optional[Any]:
          UpperCamelCase	:Optional[int]     							=       d
          UpperCamelCase	:Any     							=       spm.SentencePieceProcessor(**self.sp_model_kwargs			)
          self.sp_model.LoadFromSerializedProto(self.sp_model_proto			)
      @property
      def    UpperCAmelCase						(    self			)    ->				int:
          return self.sp_model.get_piece_size()
      def    UpperCAmelCase						(    self			)    ->				Union[str, Any]:
          UpperCamelCase	:str     							=       {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_			): i for i in range(self.vocab_size			)}
          vocab.update(self.added_tokens_encoder			)
          return vocab
      def    UpperCAmelCase						(    self   ,    SCREAMING_SNAKE_CASE_   ,    **SCREAMING_SNAKE_CASE_			)    ->				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:
              UpperCamelCase	:Union[str, Any]     							=       SPIECE_UNDERLINE + text.replace(SCREAMING_SNAKE_CASE_   ,    ''' '''			)
          return super().tokenize(SCREAMING_SNAKE_CASE_   ,    **SCREAMING_SNAKE_CASE_			)
      def    UpperCAmelCase						(    self   ,    SCREAMING_SNAKE_CASE_			)    ->				Union[str, Any]:
          if not self.legacy:
              UpperCamelCase	:int     							=       text.startswith(SCREAMING_SNAKE_CASE_			)
              if is_first:
                  UpperCamelCase	:str     							=       text[1:]

          UpperCamelCase	:Dict     							=       self.sp_model.encode(SCREAMING_SNAKE_CASE_   ,    out_type=SCREAMING_SNAKE_CASE_			)

          if not self.legacy and not is_first and not text.startswith(''' '''			) and tokens[0].startswith(SCREAMING_SNAKE_CASE_			):
              UpperCamelCase	:Union[str, Any]     							=       ([tokens[0][1:]] if len(tokens[0]			) > 1 else []) + tokens[1:]
          return tokens
      def    UpperCAmelCase						(    self   ,    SCREAMING_SNAKE_CASE_			)    ->				List[Any]:
          return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE_			)
      def    UpperCAmelCase						(    self   ,    SCREAMING_SNAKE_CASE_			)    ->				Optional[int]:
          UpperCamelCase	:Optional[Any]     							=       self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE_			)
          return token
      def    UpperCAmelCase						(    self   ,    SCREAMING_SNAKE_CASE_			)    ->				Any:
          UpperCamelCase	:Any     							=       []
          UpperCamelCase	:Optional[Any]     							=       ''''''
          UpperCamelCase	:Optional[Any]     							=       False
          for i, token in enumerate(SCREAMING_SNAKE_CASE_			):
              # 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(SCREAMING_SNAKE_CASE_			) + token
                  UpperCamelCase	:int     							=       True
                  UpperCamelCase	:str     							=       []
              else:
                  current_sub_tokens.append(SCREAMING_SNAKE_CASE_			)
                  UpperCamelCase	:List[str]     							=       False
          out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE_			)
          return out_string
      def    UpperCAmelCase						(    self   ,    SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_ = None			)    ->				Tuple[str]:
          if not os.path.isdir(SCREAMING_SNAKE_CASE_			):
              logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''			)
              return
          UpperCamelCase	:Dict     							=       os.path.join(
              SCREAMING_SNAKE_CASE_   ,    (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']			)

          if os.path.abspath(self.vocab_file			) != os.path.abspath(SCREAMING_SNAKE_CASE_			) and os.path.isfile(self.vocab_file			):
              copyfile(self.vocab_file   ,    SCREAMING_SNAKE_CASE_			)
          elif not os.path.isfile(self.vocab_file			):
              with open(SCREAMING_SNAKE_CASE_   ,    '''wb'''			) as fi:
                  UpperCamelCase	:List[Any]     							=       self.sp_model.serialized_model_proto()
                  fi.write(SCREAMING_SNAKE_CASE_			)

          return (out_vocab_file,)
      def    UpperCAmelCase						(    self   ,    SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_=None			)    ->				Tuple:
          UpperCamelCase	:List[str]     							=       [self.bos_token_id] if self.add_bos_token else []
          UpperCamelCase	:Tuple     							=       [self.eos_token_id] if self.add_eos_token else []

          UpperCamelCase	:Union[str, Any]     							=       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    UpperCAmelCase						(    self   ,    SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_ = None   ,    SCREAMING_SNAKE_CASE_ = False			)    ->				List[int]:
          if already_has_special_tokens:
              return super().get_special_tokens_mask(
                  token_ids_a=SCREAMING_SNAKE_CASE_   ,    token_ids_a=SCREAMING_SNAKE_CASE_   ,    already_has_special_tokens=SCREAMING_SNAKE_CASE_			)

          UpperCamelCase	:int     							=       [1] if self.add_bos_token else []
          UpperCamelCase	:Union[str, Any]     							=       [1] if self.add_eos_token else []

          if token_ids_a is None:
              return bos_token_id + ([0] * len(SCREAMING_SNAKE_CASE_			)) + eos_token_id
          return (
              bos_token_id
              + ([0] * len(SCREAMING_SNAKE_CASE_			))
              + eos_token_id
              + bos_token_id
              + ([0] * len(SCREAMING_SNAKE_CASE_			))
              + eos_token_id
          )
      def    UpperCAmelCase						(    self   ,    SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_ = None			)    ->				List[int]:
          UpperCamelCase	:str     							=       [self.bos_token_id] if self.add_bos_token else []
          UpperCamelCase	:Optional[int]     							=       [self.eos_token_id] if self.add_eos_token else []

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













from transformers import (
    DPRContextEncoderTokenizer,
    DPRContextEncoderTokenizerFast,
    DPRQuestionEncoderTokenizer,
    DPRQuestionEncoderTokenizerFast,
    DPRReaderOutput,
    DPRReaderTokenizer,
    DPRReaderTokenizerFast,
)
from transformers.testing_utils import require_tokenizers, slow
from transformers.tokenization_utils_base import BatchEncoding

from ..bert.test_tokenization_bert import BertTokenizationTest







@require_tokenizers
class       UpperCAmelCase_						( lowercase			):



      """simple docstring"""
      UpperCamelCase_    : Optional[int]									=DPRContextEncoderTokenizer
      UpperCamelCase_    : Any									=DPRContextEncoderTokenizerFast
      UpperCamelCase_    : Optional[int]									=True







@require_tokenizers
class       UpperCAmelCase_						( lowercase			):



      """simple docstring"""
      UpperCamelCase_    : Tuple									=DPRQuestionEncoderTokenizer
      UpperCamelCase_    : Union[str, Any]									=DPRQuestionEncoderTokenizerFast
      UpperCamelCase_    : Any									=True







@require_tokenizers
class       UpperCAmelCase_						( lowercase			):



      """simple docstring"""
      UpperCamelCase_    : Tuple									=DPRReaderTokenizer
      UpperCamelCase_    : List[Any]									=DPRReaderTokenizerFast
      UpperCamelCase_    : Union[str, Any]									=True
      @slow
      def    UpperCAmelCase						(    self			)    ->				Dict:
          UpperCamelCase	:Optional[int]     							=       self.tokenizer_class.from_pretrained('''bert-base-uncased'''			)

          UpperCamelCase	:Optional[Any]     							=       tokenizer.encode('''question sequence'''   ,    add_special_tokens=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase	:Optional[Any]     							=       tokenizer.encode('''title sequence'''   ,    add_special_tokens=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase	:List[str]     							=       tokenizer.encode('''text sequence ''' * 4   ,    add_special_tokens=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase	:Optional[int]     							=       [[101] + text_a + [102] + text_a + [102] + text_a]
          UpperCamelCase	:Tuple     							=       BatchEncoding({'''input_ids''': input_ids}			)

          UpperCamelCase	:Dict     							=       [[0] * len(input_ids[0]			)]
          UpperCamelCase	:List[Any]     							=       [[0] * len(input_ids[0]			)]
          UpperCamelCase	:Tuple     							=       [0]
          UpperCamelCase	:Union[str, Any]     							=       DPRReaderOutput(SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_			)

          UpperCamelCase							,       UpperCamelCase	:Union[str, Any]     							=       8, 9
          UpperCamelCase	:Any     							=       10
          UpperCamelCase	:Optional[Any]     							=       10
          UpperCamelCase	:Optional[int]     							=       tokenizer.decode_best_spans(SCREAMING_SNAKE_CASE_   ,    SCREAMING_SNAKE_CASE_			)
          self.assertEqual(predicted_spans[0].start_index   ,    SCREAMING_SNAKE_CASE_			)
          self.assertEqual(predicted_spans[0].end_index   ,    SCREAMING_SNAKE_CASE_			)
          self.assertEqual(predicted_spans[0].doc_id   ,    0			)




      @slow
      def    UpperCAmelCase						(    self			)    ->				Any:
          UpperCamelCase	:List[str]     							=       self.tokenizer_class.from_pretrained('''bert-base-uncased'''			)

          UpperCamelCase	:Any     							=       tokenizer.encode('''question sequence'''   ,    add_special_tokens=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase	:str     							=       tokenizer.encode('''title sequence'''   ,    add_special_tokens=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase	:Union[str, Any]     							=       tokenizer.encode('''text sequence'''   ,    add_special_tokens=SCREAMING_SNAKE_CASE_			)
          UpperCamelCase	:List[Any]     							=       [101] + text_a + [102] + text_a + [102] + text_a
          UpperCamelCase	:Any     							=       tokenizer(questions=['''question sequence''']   ,    titles=['''title sequence''']   ,    texts=['''text sequence''']			)
          self.assertIn('''input_ids'''   ,    SCREAMING_SNAKE_CASE_			)
          self.assertIn('''attention_mask'''   ,    SCREAMING_SNAKE_CASE_			)
          self.assertListEqual(encoded_input['''input_ids'''][0]   ,    SCREAMING_SNAKE_CASE_			)





