




import os
from shutil import copyfile
from typing import TYPE_CHECKING, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
from ...utils.versions import require_version


if TYPE_CHECKING:
    from transformers.pipelines.conversational import Conversation

require_version("tokenizers>=0.13.3")

if is_sentencepiece_available():
    from .tokenization_llama import LlamaTokenizer
else:
    snake_case_					:					Dict       						=			None

snake_case_					:					Any       						=			logging.get_logger(__name__)
snake_case_					:					Dict       						=			{"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}

snake_case_						,			snake_case_					:					List[Any]       						=			"[INST]", "[/INST]"
snake_case_						,			snake_case_					:					Optional[Any]       						=			"<<SYS>>\n", "\n<</SYS>>\n\n"

# fmt: off
snake_case_					:					str       						=			"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 __snake_case     (     a						):
   UpperCAmelCase__    :       Tuple		=    VOCAB_FILES_NAMES
   UpperCAmelCase__    :       Dict		=    LlamaTokenizer
   UpperCAmelCase__    :       List[Any]		=    '''left'''
   UpperCAmelCase__    :       int		=    ['''input_ids''', '''attention_mask''']







   def __init__( self						:		List[str]   ,		_snake_case						:		Any=None   ,		_snake_case						:		Tuple=None   ,		_snake_case						:		Any=False   ,		_snake_case						:		Optional[Any]="<unk>"   ,		_snake_case						:		Dict="<s>"   ,		_snake_case						:		List[str]="</s>"   ,		_snake_case						:		Optional[int]=True   ,		_snake_case						:		Union[str, Any]=False   ,		**_snake_case						:		List[str]   ,		):

        """simple docstring"""


        super().__init__(
            vocab_file=_snake_case   ,		tokenizer_file=_snake_case   ,		clean_up_tokenization_spaces=_snake_case   ,		unk_token=_snake_case   ,		bos_token=_snake_case   ,		eos_token=_snake_case   ,		**_snake_case   ,		)
        UpperCAmelCase_		=				add_bos_token
        UpperCAmelCase_		=				add_eos_token
        self.update_post_processor()

        UpperCAmelCase_		=				vocab_file
        UpperCAmelCase_		=				False if not self.vocab_file else True







   def lowerCamelCase		( self						:		List[Any]):

        """simple docstring"""


        UpperCAmelCase_		=				self.bos_token
        UpperCAmelCase_		=				self.bos_token_id

        UpperCAmelCase_		=				self.eos_token
        UpperCAmelCase_		=				self.eos_token_id

        UpperCAmelCase_		=				F"""{(bos+":0 ") * self.add_bos_token}$A:0{(" "+eos+":0") * self.add_eos_token}"""
        UpperCAmelCase_		=				F"""{single}{(" "+bos+":1") * self.add_bos_token} $B:1{(" "+eos+":1") * self.add_eos_token}"""

        UpperCAmelCase_		=				[]
        if self.add_bos_token:
             special_tokens.append((bos, bos_token_id))
        if self.add_eos_token:
             special_tokens.append((eos, eos_token_id))
        UpperCAmelCase_		=				processors.TemplateProcessing(
            single=_snake_case   ,		pair=_snake_case   ,		special_tokens=_snake_case)







   @property
   def lowerCamelCase		( self						:		Any):

        """simple docstring"""


        return self._add_eos_token







   @property
   def lowerCamelCase		( self						:		str):

        """simple docstring"""


        return self._add_bos_token







   @add_eos_token.setter
   def lowerCamelCase		( self						:		Tuple   ,		_snake_case						:		Optional[Any]):

        """simple docstring"""


        UpperCAmelCase_		=				value
        self.update_post_processor()







   @add_bos_token.setter
   def lowerCamelCase		( self						:		Dict   ,		_snake_case						:		List[str]):

        """simple docstring"""


        UpperCAmelCase_		=				value
        self.update_post_processor()







   def lowerCamelCase		( self						:		Union[str, Any]   ,		_snake_case						:		str   ,		_snake_case						:		Optional[str] = None):

        """simple docstring"""


        if not self.can_save_slow_tokenizer:
             raise ValueError(
                 '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '''
                 '''tokenizer.''')

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

        if os.path.abspath(self.vocab_file) != os.path.abspath(_snake_case):
             copyfile(self.vocab_file   ,		_snake_case)

        return (out_vocab_file,)







   def lowerCamelCase		( self						:		str   ,		_snake_case						:		"Conversation"):

        """simple docstring"""


        UpperCAmelCase_		=				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_		=				[]
        if len(conversation.past_user_inputs) > 0:
             if not conversation.past_user_inputs[0].startswith(_snake_case) or E_SYS not in conversation.past_user_inputs[0]:
                  UpperCAmelCase_		=				(
                      B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
                  )
        elif not dialogue[0][1].startswith(_snake_case) or E_SYS not in dialogue[0][1]:
             UpperCAmelCase_		=				(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=_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=_snake_case)
        return dialog_tokens












import os
from typing import List, Union

import tensorflow as tf
from tensorflow_text import BertTokenizer as BertTokenizerLayer
from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utfa, combine_segments, pad_model_inputs

from .tokenization_bert import BertTokenizer







class __snake_case     (     tf.keras.layers.Layer						):







   def __init__( self						:		Optional[int]   ,		_snake_case						:		List   ,		_snake_case						:		bool   ,		_snake_case						:		int = None   ,		_snake_case						:		int = None   ,		_snake_case						:		int = None   ,		_snake_case						:		str = "longest"   ,		_snake_case						:		bool = True   ,		_snake_case						:		int = 512   ,		_snake_case						:		int = None   ,		_snake_case						:		bool = True   ,		_snake_case						:		bool = True   ,		_snake_case						:		bool = True   ,		**_snake_case						:		Any   ,		):

        """simple docstring"""


        super().__init__()
        if use_fast_bert_tokenizer:
             UpperCAmelCase_		=				FastBertTokenizer(
                 _snake_case   ,		token_out_type=tf.intaa   ,		lower_case_nfd_strip_accents=_snake_case   ,		**_snake_case)
        else:
             UpperCAmelCase_		=				tf.lookup.StaticVocabularyTable(
                 tf.lookup.KeyValueTensorInitializer(
                     keys=_snake_case   ,		key_dtype=tf.string   ,		values=tf.range(tf.size(_snake_case   ,		out_type=tf.intaa)   ,		dtype=tf.intaa)   ,		value_dtype=tf.intaa   ,		)   ,		num_oov_buckets=1   ,		)
             UpperCAmelCase_		=				BertTokenizerLayer(
                 _snake_case   ,		token_out_type=tf.intaa   ,		lower_case=_snake_case   ,		**_snake_case)

        UpperCAmelCase_		=				vocab_list
        UpperCAmelCase_		=				do_lower_case
        UpperCAmelCase_		=				cls_token_id or vocab_list.index('''[CLS]''')
        UpperCAmelCase_		=				sep_token_id or vocab_list.index('''[SEP]''')
        UpperCAmelCase_		=				pad_token_id or vocab_list.index('''[PAD]''')
        UpperCAmelCase_		=				ShrinkLongestTrimmer(max_length - 3   ,		axis=1)  # Allow room for special tokens
        UpperCAmelCase_		=				max_length
        UpperCAmelCase_		=				padding
        UpperCAmelCase_		=				truncation
        UpperCAmelCase_		=				pad_to_multiple_of
        UpperCAmelCase_		=				return_token_type_ids
        UpperCAmelCase_		=				return_attention_mask







   @classmethod
   def lowerCamelCase		( cls						:		Optional[Any]   ,		_snake_case						:		"PreTrainedTokenizerBase"   ,		**_snake_case						:		str):  # noqa: F821

        """simple docstring"""


        UpperCAmelCase_		=				kwargs.pop('''do_lower_case'''   ,		_snake_case)
        UpperCAmelCase_		=				tokenizer.do_lower_case if do_lower_case is None else do_lower_case
        UpperCAmelCase_		=				kwargs.pop('''cls_token_id'''   ,		_snake_case)
        UpperCAmelCase_		=				tokenizer.cls_token_id if cls_token_id is None else cls_token_id
        UpperCAmelCase_		=				kwargs.pop('''sep_token_id'''   ,		_snake_case)
        UpperCAmelCase_		=				tokenizer.sep_token_id if sep_token_id is None else sep_token_id
        UpperCAmelCase_		=				kwargs.pop('''pad_token_id'''   ,		_snake_case)
        UpperCAmelCase_		=				tokenizer.pad_token_id if pad_token_id is None else pad_token_id

        UpperCAmelCase_		=				tokenizer.get_vocab()
        UpperCAmelCase_		=				sorted([(wordpiece, idx) for wordpiece, idx in vocab.items()]   ,		key=lambda _snake_case: x[1])
        UpperCAmelCase_		=				[entry[0] for entry in vocab]
        return cls(
            vocab_list=_snake_case   ,		do_lower_case=_snake_case   ,		cls_token_id=_snake_case   ,		sep_token_id=_snake_case   ,		pad_token_id=_snake_case   ,		**_snake_case   ,		)







   @classmethod
   def lowerCamelCase		( cls						:		List[str]   ,		_snake_case						:		Union[str, os.PathLike]   ,		*_snake_case						:		Union[str, Any]   ,		**_snake_case						:		Union[str, Any]):

        """simple docstring"""


        try:
             UpperCAmelCase_		=				BertTokenizer.from_pretrained(_snake_case   ,		*_snake_case   ,		**_snake_case)
        except:  # noqa: E722
             from .tokenization_bert_fast import BertTokenizerFast

             UpperCAmelCase_		=				BertTokenizerFast.from_pretrained(_snake_case   ,		*_snake_case   ,		**_snake_case)
        return cls.from_tokenizer(_snake_case   ,		**_snake_case)







   def lowerCamelCase		( self						:		int   ,		_snake_case						:		str):

        """simple docstring"""


        if self.do_lower_case:
             UpperCAmelCase_		=				case_fold_utfa(_snake_case)
        UpperCAmelCase_		=				self.tf_tokenizer.tokenize(_snake_case)
        return tokens.merge_dims(1   ,		-1)







   def lowerCamelCase		( self						:		int   ,		_snake_case						:		str   ,		_snake_case						:		str=None   ,		_snake_case						:		Union[str, Any]=None   ,		_snake_case						:		str=None   ,		_snake_case						:		int=None   ,		_snake_case						:		Optional[int]=None   ,		_snake_case						:		Optional[Any]=None   ,		_snake_case						:		List[str]=None   ,		):

        """simple docstring"""


        if padding is None:
             UpperCAmelCase_		=				self.padding
        if padding not in ("longest", "max_length"):
             raise ValueError('''Padding must be either \'longest\' or \'max_length\'!''')
        if max_length is not None and text_pair is not None:
             # Because we have to instantiate a Trimmer to do it properly
             raise ValueError('''max_length cannot be overridden at call time when truncating paired texts!''')
        if max_length is None:
             UpperCAmelCase_		=				self.max_length
        if truncation is None:
             UpperCAmelCase_		=				self.truncation
        if pad_to_multiple_of is None:
             UpperCAmelCase_		=				self.pad_to_multiple_of
        if return_token_type_ids is None:
             UpperCAmelCase_		=				self.return_token_type_ids
        if return_attention_mask is None:
             UpperCAmelCase_		=				self.return_attention_mask
        if not isinstance(_snake_case   ,		tf.Tensor):
             UpperCAmelCase_		=				tf.convert_to_tensor(_snake_case)
        if text_pair is not None and not isinstance(_snake_case   ,		tf.Tensor):
             UpperCAmelCase_		=				tf.convert_to_tensor(_snake_case)
        if text_pair is not None:
             if text.shape.rank > 1:
                  raise ValueError('''text argument should not be multidimensional when a text pair is supplied!''')
             if text_pair.shape.rank > 1:
                  raise ValueError('''text_pair should not be multidimensional!''')
        if text.shape.rank == 2:
             UpperCAmelCase_	,			UpperCAmelCase_		=				text[:, 0], text[:, 1]
        UpperCAmelCase_		=				self.unpaired_tokenize(_snake_case)
        if text_pair is None:  # Unpaired text
             if truncation:
                  UpperCAmelCase_		=				text[:, : max_length - 2]  # Allow room for special tokens
             UpperCAmelCase_	,			UpperCAmelCase_		=				combine_segments(
                 (text,)   ,		start_of_sequence_id=self.cls_token_id   ,		end_of_segment_id=self.sep_token_id)
        else:  # Paired text
             UpperCAmelCase_		=				self.unpaired_tokenize(_snake_case)
             if truncation:
                  UpperCAmelCase_	,			UpperCAmelCase_		=				self.paired_trimmer.trim([text, text_pair])
             UpperCAmelCase_	,			UpperCAmelCase_		=				combine_segments(
                 (text, text_pair)   ,		start_of_sequence_id=self.cls_token_id   ,		end_of_segment_id=self.sep_token_id)
        if padding == "longest":
             UpperCAmelCase_		=				input_ids.bounding_shape(axis=1)
             if pad_to_multiple_of is not None:
                  # No ceiling division in tensorflow, so we negate floordiv instead
                  UpperCAmelCase_		=				pad_to_multiple_of * (-tf.math.floordiv(-pad_length   ,		_snake_case))
        else:
             UpperCAmelCase_		=				max_length

        UpperCAmelCase_	,			UpperCAmelCase_		=				pad_model_inputs(_snake_case   ,		max_seq_length=_snake_case   ,		pad_value=self.pad_token_id)
        UpperCAmelCase_		=				{'''input_ids''': input_ids}
        if return_attention_mask:
             UpperCAmelCase_		=				attention_mask
        if return_token_type_ids:
             UpperCAmelCase_	,			UpperCAmelCase_		=				pad_model_inputs(
                 _snake_case   ,		max_seq_length=_snake_case   ,		pad_value=self.pad_token_id)
             UpperCAmelCase_		=				token_type_ids
        return output







   def lowerCamelCase		( self						:		Optional[Any]):

        """simple docstring"""


        return {
            "vocab_list": self.vocab_list,
            "do_lower_case": self.do_lower_case,
            "cls_token_id": self.cls_token_id,
            "sep_token_id": self.sep_token_id,
            "pad_token_id": self.pad_token_id,
        }






