




"""simple docstring"""

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:
		_lowerCamelCase	:      Optional[Any]   =							None

_lowerCamelCase	:      Optional[int]   =							logging.get_logger(__name__)
_lowerCamelCase	:      str   =							{'vocab_file': 'tokenizer.model', 'tokenizer_file': 'tokenizer.json'}

_lowerCamelCase  ,    _lowerCamelCase	:      int   =							'[INST]', '[/INST]'
_lowerCamelCase  ,    _lowerCamelCase	:      Tuple   =							'<<SYS>>\n', '\n<</SYS>>\n\n'

# fmt: off
_lowerCamelCase	:      Optional[Any]   =							'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):
				__lowerCAmelCase     :     int								= VOCAB_FILES_NAMES
				__lowerCAmelCase     :     Tuple								= LlamaTokenizer
				__lowerCAmelCase     :     Dict								= """left"""
				__lowerCAmelCase     :     int								= ["""input_ids""", """attention_mask"""]







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



					"""simple docstring"""

					super().__init__(
					    vocab_file=_lowerCamelCase   ,  tokenizer_file=_lowerCamelCase   ,  clean_up_tokenization_spaces=_lowerCamelCase   ,  unk_token=_lowerCamelCase   ,  bos_token=_lowerCamelCase   ,  eos_token=_lowerCamelCase   ,  **_lowerCamelCase   ,  )
					A_	:					List[Any]						 =		add_bos_token
					A_	:					List[str]						 =		add_eos_token
					self.update_post_processor()

					A_	:					Union[str, Any]						 =		vocab_file
					A_	:					str						 =		False if not self.vocab_file else True







				def        a_	(				self :       List[str]							):



					"""simple docstring"""

					A_	:					str						 =		self.bos_token
					A_	:					List[Any]						 =		self.bos_token_id

					A_	:					Optional[int]						 =		self.eos_token
					A_	:					Tuple						 =		self.eos_token_id

					A_	:					Optional[int]						 =		F"""{(bos+':0 ') * self.add_bos_token}$A:0{(' '+eos+':0') * self.add_eos_token}"""
					A_	:					Optional[Any]						 =		F"""{single}{(' '+bos+':1') * self.add_bos_token} $B:1{(' '+eos+':1') * self.add_eos_token}"""

					A_	:					Optional[Any]						 =		[]
					if self.add_bos_token:
						special_tokens.append((bos, bos_token_id)							)
					if self.add_eos_token:
						special_tokens.append((eos, eos_token_id)							)
					A_	:					int						 =		processors.TemplateProcessing(
					    single=_lowerCamelCase   ,  pair=_lowerCamelCase   ,  special_tokens=_lowerCamelCase							)







				@property
				def        a_	(				self :       str							):



					"""simple docstring"""

					return self._add_eos_token







				@property
				def        a_	(				self :       Union[str, Any]							):



					"""simple docstring"""

					return self._add_bos_token







				@add_eos_token.setter
				def        a_	(				self :       Optional[int]   ,  _lowerCamelCase :       Optional[int]							):



					"""simple docstring"""

					A_	:					Tuple						 =		value
					self.update_post_processor()







				@add_bos_token.setter
				def        a_	(				self :       Optional[int]   ,  _lowerCamelCase :       List[str]							):



					"""simple docstring"""

					A_	:					List[Any]						 =		value
					self.update_post_processor()







				def        a_	(				self :       Any   ,  _lowerCamelCase :       str   ,  _lowerCamelCase :       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(_lowerCamelCase							):
						logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""							)
						return
					A_	:					Any						 =		os.path.join(
					    _lowerCamelCase   ,  (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']							)

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

					return (out_vocab_file,)







				def        a_	(				self :       Optional[Any]   ,  _lowerCamelCase :       "Conversation"							):



					"""simple docstring"""

					A_	:					Optional[int]						 =		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...)'''							)

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











"""simple docstring"""

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

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


if is_sentencepiece_available():
		from .tokenization_xglm import XGLMTokenizer
else:
		_lowerCamelCase	:      Union[str, Any]   =							None


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

_lowerCamelCase	:      Tuple   =							{'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'}

_lowerCamelCase	:      Union[str, Any]   =							{
    'vocab_file': {
        'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/sentencepiece.bpe.model',
    },
    'tokenizer_file': {
        'facebook/xglm-564M': 'https://huggingface.co/facebook/xglm-564M/resolve/main/tokenizer.json',
    },
}

_lowerCamelCase	:      Dict   =							{
    'facebook/xglm-564M': 2048,
}

class 							lowercase   (     __UpperCAmelCase):
				__lowerCAmelCase     :     Optional[int]								= VOCAB_FILES_NAMES
				__lowerCAmelCase     :     Tuple								= PRETRAINED_VOCAB_FILES_MAP
				__lowerCAmelCase     :     List[Any]								= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				__lowerCAmelCase     :     Union[str, Any]								= ["""input_ids""", """attention_mask"""]
				__lowerCAmelCase     :     List[str]								= XGLMTokenizer







				def __init__(				self :       str   ,  _lowerCamelCase :       int=None   ,  _lowerCamelCase :       Any=None   ,  _lowerCamelCase :       List[str]="<s>"   ,  _lowerCamelCase :       int="</s>"   ,  _lowerCamelCase :       Any="</s>"   ,  _lowerCamelCase :       Optional[int]="<s>"   ,  _lowerCamelCase :       List[Any]="<unk>"   ,  _lowerCamelCase :       Optional[int]="<pad>"   ,  **_lowerCamelCase :       List[Any]   ,  ):



					"""simple docstring"""

					A_	:					Tuple						 =		7
					A_	:					Dict						 =		[F"""<madeupword{i}>""" for i in range(self.num_madeup_words							)]

					A_	:					str						 =		kwargs.get('''additional_special_tokens'''   ,  []							)
					kwargs["additional_special_tokens"] += [
					    word for word in madeup_words if word not in kwargs["additional_special_tokens"]
					]

					super().__init__(
					    _lowerCamelCase   ,  tokenizer_file=_lowerCamelCase   ,  bos_token=_lowerCamelCase   ,  eos_token=_lowerCamelCase   ,  sep_token=_lowerCamelCase   ,  cls_token=_lowerCamelCase   ,  unk_token=_lowerCamelCase   ,  pad_token=_lowerCamelCase   ,  **_lowerCamelCase   ,  )

					A_	:					Tuple						 =		vocab_file
					A_	:					str						 =		False if not self.vocab_file else True







				def        a_	(				self :       List[Any]   ,  _lowerCamelCase :       List[int]   ,  _lowerCamelCase :       Optional[List[int]] = None							):



					"""simple docstring"""

					if token_ids_a is None:
						return [self.sep_token_id] + token_ids_a
					A_	:					List[Any]						 =		[self.sep_token_id]
					return sep + token_ids_a + sep + sep + token_ids_a







				def        a_	(				self :       List[str]   ,  _lowerCamelCase :       List[int]   ,  _lowerCamelCase :       Optional[List[int]] = None							):



					"""simple docstring"""

					A_	:					Dict						 =		[self.sep_token_id]

					if token_ids_a is None:
						return len(sep + token_ids_a							) * [0]
					return len(sep + token_ids_a + sep + sep + token_ids_a							) * [0]







				def        a_	(				self :       List[str]   ,  _lowerCamelCase :       str   ,  _lowerCamelCase :       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(_lowerCamelCase							):
						logger.error(F"""Vocabulary path ({save_directory}) should be a directory."""							)
						return
					A_	:					Tuple						 =		os.path.join(
					    _lowerCamelCase   ,  (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']							)

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

					return (out_vocab_file,)





