





'''simple docstring'''






from collections import Counter
import datasets
import transformers
from transformers.convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS

from transformers.utils import logging

logging.set_verbosity_info()

__UpperCamelCase										=  {
    name: (getattr(transformers, name), getattr(transformers, name + "Fast")) for name in SLOW_TO_FAST_CONVERTERS
}

__UpperCamelCase										=  datasets.load_dataset("xnli", split="test+validation")

__UpperCamelCase										=  0
__UpperCamelCase										=  0
__UpperCamelCase										=  0
__UpperCamelCase										=  0







def 				_a	(					_lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase   )   ->							Optional[int]:



			"""simple docstring"""


			if spm_diff == list(reversed(_lowerCamelCase   )   ):
						# AAA -> AA+A vs A+AA case.
						return True
			elif len(_lowerCamelCase   ) == len(_lowerCamelCase   ) and fast.decode(_lowerCamelCase   ) == fast.decode(_lowerCamelCase   ):
						# Second order OK
						# Barrich -> Barr + ich vs Bar + rich
						return True
			__snake_case				:			Any       			=    slow.encode(slow.decode(_lowerCamelCase   )   )
			__snake_case				:			Union[str, Any]       			=    fast.encode(fast.decode(_lowerCamelCase   )   )
			if spm_reencoded != spm_diff and spm_reencoded == tok_reencoded:
						# Type 3 error.
						# Snehagatha ->
						#       Sne, h, aga, th, a
						#       Sne, ha, gat, ha
						# Encoding the wrong with sp does not even recover what spm gave us
						# It fits tokenizer however...
						return True
			return False







def 				_a	(					_lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase   )   ->							Optional[Any]:



			"""simple docstring"""


			__snake_case				:			Optional[Any]       			=    fast.encode_plus(_lowerCamelCase   )[0]
			__snake_case				:			int       			=    enc.offsets
			__snake_case			,    __snake_case				:			Tuple       			=    offsets[idx], offsets[idx - 1]
			if curr is not None and line[curr[0] : curr[1]] == "\u200f":
						return True
			if prev is not None and line[prev[0] : prev[1]] == "\u200f":
						return True







def 				_a	(					_lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase   )   ->							Optional[int]:



			"""simple docstring"""


			for i, (spm_id, tok_id) in enumerate(zip(_lowerCamelCase						,  _lowerCamelCase   )   ):
						if spm_id != tok_id:
									break
			__snake_case				:			Tuple       			=    i
			for i, (spm_id, tok_id) in enumerate(zip(reversed(_lowerCamelCase   )						,  reversed(_lowerCamelCase   )   )   ):
						if spm_id != tok_id:
									break
			__snake_case				:			List[Any]       			=    len(_lowerCamelCase   ) - i

			__snake_case				:			Union[str, Any]       			=    spm_ids[first:last]
			__snake_case				:			List[Any]       			=    tok_ids[first:last]

			if check_diff(_lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase   ):
						return True

			if check_LTR_mark(_lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase   ):
						return True

			if last - first > 5:
						# We might have twice a single problem, attempt to subdivide the disjointed tokens into smaller problems
						__snake_case				:			Dict       			=    Counter(spm_ids[first:last]   )
						__snake_case				:			int       			=    Counter(tok_ids[first:last]   )

						__snake_case				:			Optional[Any]       			=    {spm_ for (spm_, si) in spms.items() if toks.get(spm_						,  0   ) == si}
						__snake_case				:			Optional[Any]       			=    3
						for i in range(last - first - min_width   ):
									if all(spm_ids[first + i + j] in removable_tokens for j in range(_lowerCamelCase   )   ):
												__snake_case				:			Union[str, Any]       			=    [
												    k
												    for k in range(last - first - min_width   )
												    if tok_ids[first + k : first + k + min_width] == spm_ids[first + i : first + i + min_width]
												]
												for j in possible_matches:
															if check_diff(spm_ids[first : first + i]						,  tok_ids[first : first + j]						,  _lowerCamelCase						,  _lowerCamelCase   ) and check_details(
															    _lowerCamelCase						,  spm_ids[first + i : last]						,  tok_ids[first + j : last]						,  _lowerCamelCase						,  _lowerCamelCase						,  ):
																		return True

			print(F'''Spm: {[fast.decode([spm_ids[i]]   ) for i in range(_lowerCamelCase						,  _lowerCamelCase   )]}'''   )
			try:
						print(F'''Tok: {[fast.decode([tok_ids[i]]   ) for i in range(_lowerCamelCase						,  _lowerCamelCase   )]}'''   )
			except Exception:
						pass

			__snake_case				:			List[str]       			=    fast.decode(spm_ids[:first]   )
			__snake_case				:			Optional[Any]       			=    fast.decode(spm_ids[last:]   )
			__snake_case				:			Dict       			=    fast.decode(spm_ids[first:last]   )
			print()
			print(_lowerCamelCase   )
			return False







def 				_a	(					_lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase   )   ->							Optional[Any]:



			"""simple docstring"""


			global perfect
			global imperfect
			global wrong
			global total

			__snake_case				:			Any       			=    slow.encode(_lowerCamelCase   )
			__snake_case				:			List[str]       			=    fast.encode(_lowerCamelCase   )

			__snake_case				:			List[Any]       			=    False
			total += 1

			if slow_ids != fast_ids:
						if check_details(_lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase   ):
									__snake_case				:			Tuple       			=    True
									imperfect += 1
						else:
									wrong += 1
			else:
						perfect += 1

			if total % 1_0000 == 0:
						print(F'''({perfect} / {imperfect} / {wrong} ----- {perfect + imperfect + wrong})'''   )

			if skip_assert:
						return

			assert (
			    slow_ids == fast_ids
			), F'''line {text} : \n\n{slow_ids}\n{fast_ids}\n\n{slow.tokenize(_lowerCamelCase   )}\n{fast.tokenize(_lowerCamelCase   )}'''







def 				_a	(					_lowerCamelCase						,  _lowerCamelCase   )   ->							Union[str, Any]:



			"""simple docstring"""


			global batch_total
			for i in range(len(_lowerCamelCase   )   ):
						# premise, all languages
						for text in dataset[i]["premise"].values():
									test_string(_lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase   )

						# hypothesis, all languages
						for text in dataset[i]["hypothesis"]["translation"]:
									test_string(_lowerCamelCase						,  _lowerCamelCase						,  _lowerCamelCase   )


if __name__ == "__main__":
	for name, (slow_class, fast_class) in TOKENIZER_CLASSES.items():
		__UpperCamelCase										=  list(slow_class.max_model_input_sizes.keys())
		for checkpoint in checkpoint_names:
			__UpperCamelCase										=  0
			__UpperCamelCase										=  0
			__UpperCamelCase										=  0
			__UpperCamelCase										=  0

			print(f"""========================== Checking {name}: {checkpoint} ==========================""")
			__UpperCamelCase										=  slow_class.from_pretrained(checkpoint, force_download=True)
			__UpperCamelCase										=  fast_class.from_pretrained(checkpoint, force_download=True)
			test_tokenizer(slow, fast)
			print(f"""Accuracy {perfect * 100 / total:.2f}""")









'''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:
	__UpperCamelCase										=  None

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

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

# fmt: off
__UpperCamelCase										=  "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    _A   (				__lowercase		):
		lowercase__:      Union[str, Any]							    =      VOCAB_FILES_NAMES
		lowercase__:      Tuple							    =      LlamaTokenizer
		lowercase__:      List[Any]							    =      '''left'''
		lowercase__:      int							    =      ['''input_ids''', '''attention_mask''']

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


					"""simple docstring"""

					super().__init__(
					    vocab_file=__magic_name__     ,			tokenizer_file=__magic_name__     ,			clean_up_tokenization_spaces=__magic_name__     ,			unk_token=__magic_name__     ,			bos_token=__magic_name__     ,			eos_token=__magic_name__     ,			**__magic_name__     ,			)
					__snake_case				:			List[Any]       			=    add_bos_token
					__snake_case				:			int       			=    add_eos_token
					self.update_post_processor()

					__snake_case				:			Dict       			=    vocab_file
					__snake_case				:			int       			=    False if not self.vocab_file else True

		def   lowercase__    (      self				:      Any )				->						Dict:


					"""simple docstring"""

					__snake_case				:			Any       			=    self.bos_token
					__snake_case				:			Dict       			=    self.bos_token_id

					__snake_case				:			List[str]       			=    self.eos_token
					__snake_case				:			str       			=    self.eos_token_id

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

					__snake_case				:			List[str]       			=    []
					if self.add_bos_token:
								special_tokens.append((bos, bos_token_id) )
					if self.add_eos_token:
								special_tokens.append((eos, eos_token_id) )
					__snake_case				:			Dict       			=    processors.TemplateProcessing(
					    single=__magic_name__     ,			pair=__magic_name__     ,			special_tokens=__magic_name__ )

		@property
		def   lowercase__    (      self				:      Tuple )				->						List[Any]:


					"""simple docstring"""

					return self._add_eos_token

		@property
		def   lowercase__    (      self				:      Union[str, Any] )				->						str:


					"""simple docstring"""

					return self._add_bos_token

		@add_eos_token.setter
		def   lowercase__    (      self				:      List[str]     ,			__magic_name__				:      Optional[Any] )				->						int:


					"""simple docstring"""

					__snake_case				:			Any       			=    value
					self.update_post_processor()

		@add_bos_token.setter
		def   lowercase__    (      self				:      Union[str, Any]     ,			__magic_name__				:      Optional[Any] )				->						List[str]:


					"""simple docstring"""

					__snake_case				:			Dict       			=    value
					self.update_post_processor()

		def   lowercase__    (      self				:      List[Any]     ,			__magic_name__				:      str     ,			__magic_name__				:      Optional[str] = None )				->						Tuple[str]:


					"""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(__magic_name__ ):
								logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
								return
					__snake_case				:			Dict       			=    os.path.join(
					    __magic_name__     ,			(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )

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

					return (out_vocab_file,)

		def   lowercase__    (      self				:      int     ,			__magic_name__				:      "Conversation" )				->						int:


					"""simple docstring"""

					__snake_case				:			List[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...)""" )

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


