




"""simple docstring"""





import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin

@require_tokenizers
class  __lowercase    (     snake_case_  ,				unittest.TestCase		):


				'''simple docstring'''


				_lowerCAmelCase		     =PreTrainedTokenizerFast
				_lowerCAmelCase		     =False
				_lowerCAmelCase		     =True
				_lowerCAmelCase		     ="tokenizer_file"

				def  _lowerCamelCase   (				self				:       Any ):
										snake_case__    :   int							     =   False  # because we don't have pretrained_vocab_files_map
										super().setUp()
										snake_case__    :   Optional[int]							     =   True

										snake_case__    :   Optional[Any]							     =   ['''robot-test/dummy-tokenizer-fast''', '''robot-test/dummy-tokenizer-wordlevel''']
										snake_case__    :   str							     =   '''SaulLu/dummy-tokenizer-bytelevel-bpe'''

										# Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
										snake_case__    :   Optional[Any]							     =   [(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

										snake_case__    :   Union[str, Any]							     =   PreTrainedTokenizerFast.from_pretrained(model_paths[0] )
										tokenizer.save_pretrained(self.tmpdirname )

				def  _lowerCamelCase   (				self				:       List[Any] ):
										# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
										# model
										pass

				def  _lowerCamelCase   (				self				:       Optional[int] ):
										# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
										# model
										pass

				def  _lowerCamelCase   (				self				:       Optional[int] ):
										# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
										# model
										pass

				def  _lowerCamelCase   (				self				:       Tuple ):
										# PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
										pass

				def  _lowerCamelCase   (				self				:       List[str] ):
										snake_case__    :   Any							     =   self.tmpdirname
										# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
										for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
																with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
																						try:
																												snake_case__    :   Optional[int]							     =   tempfile.mkdtemp()
																												snake_case__    :   Union[str, Any]							     =   self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ )

																												tokenizer.save_pretrained(self.tmpdirname )
																												super().test_training_new_tokenizer()
																						finally:
																												# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
																												# is restored
																												shutil.rmtree(self.tmpdirname )
																												snake_case__    :   List[str]							     =   tmpdirname_orig

				def  _lowerCamelCase   (				self				:       List[Any] ):
										snake_case__    :   List[Any]							     =   self.tmpdirname
										# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
										for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
																with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
																						try:
																												snake_case__    :   Optional[Any]							     =   tempfile.mkdtemp()
																												snake_case__    :   List[Any]							     =   self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ )

																												tokenizer.save_pretrained(self.tmpdirname )
																												super().test_training_new_tokenizer_with_special_tokens_change()
																						finally:
																												# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
																												# is restored
																												shutil.rmtree(self.tmpdirname )
																												snake_case__    :   List[Any]							     =   tmpdirname_orig





				def  _lowerCamelCase   (				self				:       List[str] ):
										snake_case__    :   List[Any]							     =   self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name )

										snake_case__    :   Dict							     =   ('''a''' for _ in range(1_0_0_0 ))
										snake_case__    :   Union[str, Any]							     =   tokenizer.train_new_from_iterator(text_iterator=SCREAMING_SNAKE_CASE_ ,length=1_0_0_0 ,vocab_size=5_0 )

										snake_case__    :   List[Any]							     =   new_tokenizer.encode('''a🤗''' )
										self.assertEqual(SCREAMING_SNAKE_CASE_ ,[6_4, 1_7_2, 2_5_3, 9_7, 2_4_5] )







@require_tokenizers
class  __lowercase    (     unittest.TestCase		):


				'''simple docstring'''


				def  _lowerCamelCase   (				self				:       Dict ):
										snake_case__    :   Optional[Any]							     =   AutoTokenizer.from_pretrained('''bert-base-cased''' )
										snake_case__    :   Tuple							     =   json.loads(tokenizer._tokenizer.to_str() )
										snake_case__    :   List[str]							     =   len(SCREAMING_SNAKE_CASE_ )

										with tempfile.TemporaryDirectory() as tmp_dir:
																# Hack to save this in the tokenizer_config.json
																snake_case__    :   int							     =   ['''tokenizer.4.0.0.json''']
																tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ )
																json.dump(SCREAMING_SNAKE_CASE_ ,open(os.path.join(SCREAMING_SNAKE_CASE_ ,'''tokenizer.4.0.0.json''' ) ,'''w''' ) )

																# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
																snake_case__    :   List[str]							     =   AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ )
																self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) ,len(SCREAMING_SNAKE_CASE_ ) + 1 )
																snake_case__    :   Union[str, Any]							     =   json.loads(new_tokenizer._tokenizer.to_str() )
																self.assertIn('''huggingface''' ,json_tokenizer['''model''']['''vocab'''] )

																# Will need to be adjusted if we reach v42 and this test is still here.
																# Should pick the old tokenizer file as the version of Transformers is < 4.0.0
																shutil.move(os.path.join(SCREAMING_SNAKE_CASE_ ,'''tokenizer.4.0.0.json''' ) ,os.path.join(SCREAMING_SNAKE_CASE_ ,'''tokenizer.42.0.0.json''' ) )
																snake_case__    :   str							     =   ['''tokenizer.42.0.0.json''']
																tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ )
																snake_case__    :   Optional[int]							     =   AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ )
																self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) ,len(SCREAMING_SNAKE_CASE_ ) )
																snake_case__    :   Union[str, Any]							     =   json.loads(new_tokenizer._tokenizer.to_str() )
																self.assertNotIn('''huggingface''' ,json_tokenizer['''model''']['''vocab'''] )





				def  _lowerCamelCase   (				self				:       Optional[Any] ):
										# This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
										snake_case__    :   str							     =   '''hf-internal-testing/test-two-tokenizers'''

										# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
										snake_case__    :   List[str]							     =   AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ )
										self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) ,2_8_9_9_7 )
										snake_case__    :   Tuple							     =   json.loads(tokenizer._tokenizer.to_str() )
										self.assertIn('''huggingface''' ,json_tokenizer['''model''']['''vocab'''] )

										# Testing an older version by monkey-patching the version in the module it's used.
										import transformers as old_transformers

										snake_case__    :   List[Any]							     =   '''3.0.0'''
										snake_case__    :   Any							     =   old_transformers.models.auto.AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ )
										self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) ,2_8_9_9_6 )
										snake_case__    :   Dict							     =   json.loads(old_tokenizer._tokenizer.to_str() )
										self.assertNotIn('''huggingface''' ,json_tokenizer['''model''']['''vocab'''] )







@require_tokenizers
class  __lowercase    (     unittest.TestCase		):


				'''simple docstring'''


				def  _lowerCamelCase   (				self				:       List[str] ):
										# See https://github.com/huggingface/transformers/pull/12550
										# and https://github.com/huggingface/tokenizers/issues/537
										snake_case__    :   int							     =   PreTrainedTokenizerFast.from_pretrained('''robot-test/dummy-tokenizer-wordlevel''' )
										snake_case__    :   Tuple							     =   '''The Matrix is a 1999 science fiction action film.'''

										with concurrent.futures.ThreadPoolExecutor() as executor:
																snake_case__    :   List[Any]							     =   [executor.submit(self.fetch ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) for i in range(1_0 )]
																snake_case__    :   List[str]							     =   [future.result() for future in futures]
																self.assertEqual(SCREAMING_SNAKE_CASE_ ,[[1, 1_0, 0, 8, 0, 1_8, 0, 0, 0, 2] for i in range(1_0 )] )





				def  _lowerCamelCase   (				self				:       Tuple ,SCREAMING_SNAKE_CASE_				:       int ,SCREAMING_SNAKE_CASE_				:       Optional[Any] ):
										return tokenizer.encode(SCREAMING_SNAKE_CASE_ ,truncation='''longest_first''' ,padding='''longest''' )








"""simple docstring"""





class  __lowercase    :


				'''simple docstring'''


				class  __lowercase    :


								'''simple docstring'''


								_lowerCAmelCase		     ="_prev", "_data", "_next"

								def __init__(				self				:       List[Any] ,SCREAMING_SNAKE_CASE_				:       int ,SCREAMING_SNAKE_CASE_				:       Union[str, Any] ,SCREAMING_SNAKE_CASE_				:       Any ):
														snake_case__    :   Any							     =   link_p
														snake_case__    :   List[str]							     =   element
														snake_case__    :   str							     =   link_n





								def  _lowerCamelCase   (				self				:       Optional[Any] ):
														return (
														    F''' Prev -> {self._prev is not None}, Next -> {self._next is not None}'''
														)







				def __init__(				self				:       Any ):
										snake_case__    :   int							     =   self._Node(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
										snake_case__    :   Optional[int]							     =   self._Node(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
										snake_case__    :   Union[str, Any]							     =   self._trailer
										snake_case__    :   Union[str, Any]							     =   self._header
										snake_case__    :   Any							     =   0

				def __len__(				self				:       str ):
										return self._size

				def  _lowerCamelCase   (				self				:       Union[str, Any] ):
										return self.__len__() == 0

				def  _lowerCamelCase   (				self				:       Any ,SCREAMING_SNAKE_CASE_				:       List[Any] ,SCREAMING_SNAKE_CASE_				:       List[str] ,SCREAMING_SNAKE_CASE_				:       Dict ):
										# Create new_node by setting it's prev.link -> header
										# setting it's next.link -> trailer
										snake_case__    :   Dict							     =   self._Node(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
										snake_case__    :   Any							     =   new_node
										snake_case__    :   str							     =   new_node
										self._size += 1
										return self





				def  _lowerCamelCase   (				self				:       Union[str, Any] ,SCREAMING_SNAKE_CASE_				:       Dict ):
										snake_case__    :   Union[str, Any]							     =   node._prev
										snake_case__    :   Union[str, Any]							     =   node._next

										snake_case__    :   List[Any]							     =   successor
										snake_case__    :   Dict							     =   predecessor
										self._size -= 1
										snake_case__    :   Dict							     =   node._data
										snake_case__    :   List[str]							     =   None
										del node
										return temp







class  __lowercase    (     _DoublyLinkedBase		):


				'''simple docstring'''


				def  _lowerCamelCase   (				self				:       Optional[int] ):
										if self.is_empty():
																raise Exception('''List is empty''' )
										return self._header._next._data

				def  _lowerCamelCase   (				self				:       Union[str, Any] ):
										if self.is_empty():
																raise Exception('''List is empty''' )
										return self._trailer._prev._data

				def  _lowerCamelCase   (				self				:       Any ,SCREAMING_SNAKE_CASE_				:       Dict ):
										return self._insert(self._header ,SCREAMING_SNAKE_CASE_ ,self._header._next )

				def  _lowerCamelCase   (				self				:       Dict ,SCREAMING_SNAKE_CASE_				:       Union[str, Any] ):
										return self._insert(self._trailer._prev ,SCREAMING_SNAKE_CASE_ ,self._trailer )

				def  _lowerCamelCase   (				self				:       Optional[int] ):
										if self.is_empty():
																raise IndexError('''remove_first from empty list''' )
										return self._delete(self._header._next )





				def  _lowerCamelCase   (				self				:       Optional[Any] ):
										if self.is_empty():
																raise IndexError('''remove_first from empty list''' )
										return self._delete(self._trailer._prev )


