
'''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:
					__SCREAMING_SNAKE_CASE		:  List[str]        =      None

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

__SCREAMING_SNAKE_CASE   ,       __SCREAMING_SNAKE_CASE		:  List[str]        =      '[INST]', '[/INST]'
__SCREAMING_SNAKE_CASE   ,       __SCREAMING_SNAKE_CASE		:  Optional[int]        =      '<<SYS>>\n', '\n<</SYS>>\n\n'

# fmt: off
__SCREAMING_SNAKE_CASE		:  Dict        =      '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  SCREAMING_SNAKE_CASE__       (  __UpperCamelCase   ):
	lowercase__	    =							VOCAB_FILES_NAMES
	lowercase__	    =							LlamaTokenizer
	lowercase__	    =							"left"
	lowercase__	    =							["input_ids", "attention_mask"]
	def __init__(				self  ,    __UpperCamelCase=None  ,    __UpperCamelCase=None  ,    __UpperCamelCase=False  ,    __UpperCamelCase="<unk>"  ,    __UpperCamelCase="<s>"  ,    __UpperCamelCase="</s>"  ,    __UpperCamelCase=True  ,    __UpperCamelCase=False  ,    **__UpperCamelCase  ,    ):



					'''simple docstring'''






					super().__init__(
					    vocab_file=__UpperCamelCase  ,    tokenizer_file=__UpperCamelCase  ,    clean_up_tokenization_spaces=__UpperCamelCase  ,    unk_token=__UpperCamelCase  ,    bos_token=__UpperCamelCase  ,    eos_token=__UpperCamelCase  ,    **__UpperCamelCase  ,    )
					__a       :     Tuple								=	add_bos_token
					__a       :     List[str]								=	add_eos_token
					self.update_post_processor()

					__a       :     Union[str, Any]								=	vocab_file
					__a       :     int								=	False if not self.vocab_file else True
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     Dict								=	self.bos_token
					__a       :     List[Any]								=	self.bos_token_id

					__a       :     Any								=	self.eos_token
					__a       :     Any								=	self.eos_token_id

					__a       :     List[Any]								=	f"""{(bos+":0 ") * self.add_bos_token}$A:0{(" "+eos+":0") * self.add_eos_token}"""
					__a       :     Union[str, Any]								=	f"""{single}{(" "+bos+":1") * self.add_bos_token} $B:1{(" "+eos+":1") * self.add_eos_token}"""

					__a       :     Optional[int]								=	[]
					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       :     Any								=	processors.TemplateProcessing(
					    single=__UpperCamelCase  ,    pair=__UpperCamelCase  ,    special_tokens=__UpperCamelCase			)
	@property
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					return self._add_eos_token
	@property
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					return self._add_bos_token
	@add_eos_token.setter
	def __lowerCamelCase    (				self  ,    __UpperCamelCase			):



					'''simple docstring'''






					__a       :     Any								=	value
					self.update_post_processor()
	@add_bos_token.setter
	def __lowerCamelCase    (				self  ,    __UpperCamelCase			):



					'''simple docstring'''






					__a       :     Optional[int]								=	value
					self.update_post_processor()
	def __lowerCamelCase    (				self  ,    __UpperCamelCase  ,    __UpperCamelCase = 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(__UpperCamelCase			):
									logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""			)
									return
					__a       :     Optional[int]								=	os.path.join(
					    __UpperCamelCase  ,    (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]			)

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

					return (out_vocab_file,)

	def __lowerCamelCase    (				self  ,    __UpperCamelCase			):



					'''simple docstring'''






					__a       :     Optional[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...)"""			)

					__a       :     Optional[int]								=	[]
					if len(conversation.past_user_inputs			) > 0:
									if not conversation.past_user_inputs[0].startswith(__UpperCamelCase			) or E_SYS not in conversation.past_user_inputs[0]:
													__a       :     List[Any]								=	(
													    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
													)
					elif not dialogue[0][1].startswith(__UpperCamelCase			) or E_SYS not in dialogue[0][1]:
									__a       :     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=__UpperCamelCase			)
					        + [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=__UpperCamelCase			)
					return dialog_tokens

'''simple docstring'''







import unittest

from cer import CER


__SCREAMING_SNAKE_CASE		:  List[str]        =      CER()
class  SCREAMING_SNAKE_CASE__       (  unittest.TestCase   ):
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     Optional[Any]								=	["""White House"""]
					__a       :     Tuple								=	["""white house"""]
					# S = 2, D = 0, I = 0, N = 11, CER = 2 / 11
					__a       :     Any								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.1_8_1_8_1_8_1_8_1_8			) < 1E-6			)
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     Optional[int]								=	["""were wolf"""]
					__a       :     Tuple								=	["""werewolf"""]
					# S = 0, D = 0, I = 1, N = 9, CER = 1 / 9
					__a       :     Any								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.1_1_1_1_1_1_1			) < 1E-6			)

					__a       :     str								=	["""werewolf"""]
					__a       :     List[Any]								=	["""weae     wolf"""]
					# S = 1, D = 1, I = 0, N = 8, CER = 0.25
					__a       :     Tuple								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.2_5			) < 1E-6			)

					# consecutive whitespaces case 1
					__a       :     int								=	["""were wolf"""]
					__a       :     Dict								=	["""were               wolf"""]
					# S = 0, D = 0, I = 0, N = 9, CER = 0
					__a       :     str								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.0			) < 1E-6			)

					# consecutive whitespaces case 2
					__a       :     List[str]								=	["""were   wolf"""]
					__a       :     Optional[int]								=	["""were               wolf"""]
					# S = 0, D = 0, I = 0, N = 9, CER = 0
					__a       :     Optional[Any]								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.0			) < 1E-6			)
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     Dict								=	["""werewolf"""]
					__a       :     str								=	["""weaewolf"""]
					# S = 1, D = 0, I = 0, N = 8, CER = 0.125
					__a       :     Optional[int]								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.1_2_5			) < 1E-6			)
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     List[str]								=	["""werewolf"""]
					__a       :     Tuple								=	["""wereawolf"""]
					# S = 0, D = 1, I = 0, N = 8, CER = 0.125
					__a       :     Optional[Any]								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.1_2_5			) < 1E-6			)
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     List[str]								=	["""werewolf"""]
					__a       :     Optional[Any]								=	["""wereolf"""]
					# S = 0, D = 0, I = 1, N = 8, CER = 0.125
					__a       :     int								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.1_2_5			) < 1E-6			)
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     Dict								=	["""werewolf"""]
					__a       :     Tuple								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertEqual(__UpperCamelCase  ,    0.0			)
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     List[str]								=	["""werewolf""", """I am your father"""]
					__a       :     int								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertEqual(__UpperCamelCase  ,    0.0			)

					__a       :     Dict								=	["""werewolf""", """I am your father""", """doge"""]
					__a       :     Optional[Any]								=	["""werxwolf""", """I       am your father""", """doge"""]
					# S = 1, D = 0, I = 0, N = 28, CER = 1 / 28
					__a       :     Union[str, Any]								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.0_3_5_7_1_4_2_8			) < 1E-6			)
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     List[str]								=	["""My hovercraft""", """is full of eels"""]
					__a       :     Union[str, Any]								=	["""My hovercraft is full""", """ of eels"""]
					# S = 0, D = 0, I = 2, N = 28, CER = 2 / 28
					# whitespace at the front of " of eels" will be strip during preporcessing
					# so need to insert 2 whitespaces
					__a       :     str								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase  ,    concatenate_texts=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.0_7_1_4_2_8			) < 1E-6			)
	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     int								=	["""我能吞下玻璃而不伤身体"""]
					__a       :     Optional[Any]								=	[""" 能吞虾玻璃而 不霜身体啦"""]
					# S = 3, D = 2, I = 0, N = 11, CER = 5 / 11
					__a       :     List[Any]								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.4_5_4_5_4_5_4_5_4_5			) < 1E-6			)

					__a       :     Union[str, Any]								=	["""我能吞下玻璃""", """而不伤身体"""]
					__a       :     Optional[Any]								=	["""我    能 吞 下 玻 璃""", """而不伤身体"""]
					# S = 0, D = 5, I = 0, N = 11, CER = 5 / 11
					__a       :     List[str]								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertTrue(abs(char_error_rate - 0.4_5_4_5_4_5_4_5_4_5_4_5			) < 1E-6			)

					__a       :     Union[str, Any]								=	["""我能吞下玻璃而不伤身体"""]
					__a       :     Dict								=	cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)
					self.assertFalse(__UpperCamelCase  ,    0.0			)

	def __lowerCamelCase    (				self			):



					'''simple docstring'''






					__a       :     List[Any]								=	[""""""]
					__a       :     Dict								=	["""Hypothesis"""]
					with self.assertRaises(__UpperCamelCase			):
									cer.compute(predictions=__UpperCamelCase  ,    references=__UpperCamelCase			)


if __name__ == "__main__":
					unittest.main()