




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 	SCREAMING_SNAKE_CASE(    lowerCamelCase__       ,				unittest.TestCase					):
       snake_case_			:					str   = PreTrainedTokenizerFast
       snake_case_			:					Union[str, Any]   = False
       snake_case_			:					Tuple   = True
       snake_case_			:					Any   = 'tokenizer_file'

       def    snake_case__      (   self					)   -> List[Any]:

           """simple docstring"""



           __lowercase          =						False  # because we don't have pretrained_vocab_files_map
           super().setUp()
           __lowercase          =						True

           __lowercase          =						["""robot-test/dummy-tokenizer-fast""", """robot-test/dummy-tokenizer-wordlevel"""]
           __lowercase          =						"""SaulLu/dummy-tokenizer-bytelevel-bpe"""

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

           __lowercase          =						PreTrainedTokenizerFast.from_pretrained(model_paths[0]					)
           tokenizer.save_pretrained(self.tmpdirname					)

       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           pass

       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           pass

       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           pass

       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           pass

       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           __lowercase          =						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:
                       __lowercase          =						tempfile.mkdtemp()
                       __lowercase          =						self.rust_tokenizer_class.from_pretrained(lowercase_ ,		**lowercase_					)

                       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					)
                       __lowercase          =						tmpdirname_orig

       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						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:
                       __lowercase          =						tempfile.mkdtemp()
                       __lowercase          =						self.rust_tokenizer_class.from_pretrained(lowercase_ ,		**lowercase_					)

                       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					)
                       __lowercase          =						tmpdirname_orig




       def    snake_case__      (   self					)   -> Optional[Any]:

           """simple docstring"""



           __lowercase          =						self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name					)

           __lowercase          =						("""a""" for _ in range(1000					))
           __lowercase          =						tokenizer.train_new_from_iterator(text_iterator=lowercase_ ,		length=1000 ,		vocab_size=50					)

           __lowercase          =						new_tokenizer.encode("""a🤗"""					)
           self.assertEqual(lowercase_ ,		[64, 172, 253, 97, 245]					)






@require_tokenizers
class 	SCREAMING_SNAKE_CASE(    unittest.TestCase					):

       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						AutoTokenizer.from_pretrained("""bert-base-cased"""					)
           __lowercase          =						json.loads(tokenizer._tokenizer.to_str()					)
           __lowercase          =						len(lowercase_					)

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

               # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
               __lowercase          =						AutoTokenizer.from_pretrained(lowercase_					)
               self.assertEqual(len(lowercase_					) ,		len(lowercase_					) + 1					)
               __lowercase          =						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(lowercase_ ,		"""tokenizer.4.0.0.json"""					) ,		os.path.join(lowercase_ ,		"""tokenizer.42.0.0.json"""					)					)
               __lowercase          =						["""tokenizer.42.0.0.json"""]
               tokenizer.save_pretrained(lowercase_					)
               __lowercase          =						AutoTokenizer.from_pretrained(lowercase_					)
               self.assertEqual(len(lowercase_					) ,		len(lowercase_					)					)
               __lowercase          =						json.loads(new_tokenizer._tokenizer.to_str()					)
               self.assertNotIn("""huggingface""" ,		json_tokenizer["""model"""]["""vocab"""]					)




       def    snake_case__      (   self					)   -> Dict:

           """simple docstring"""



           __lowercase          =						"""hf-internal-testing/test-two-tokenizers"""

           # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
           __lowercase          =						AutoTokenizer.from_pretrained(lowercase_					)
           self.assertEqual(len(lowercase_					) ,		2_8997					)
           __lowercase          =						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

           __lowercase          =						"""3.0.0"""
           __lowercase          =						old_transformers.models.auto.AutoTokenizer.from_pretrained(lowercase_					)
           self.assertEqual(len(lowercase_					) ,		2_8996					)
           __lowercase          =						json.loads(old_tokenizer._tokenizer.to_str()					)
           self.assertNotIn("""huggingface""" ,		json_tokenizer["""model"""]["""vocab"""]					)






@require_tokenizers
class 	SCREAMING_SNAKE_CASE(    unittest.TestCase					):

       def    snake_case__      (   self					)   -> Tuple:

           """simple docstring"""



           __lowercase          =						PreTrainedTokenizerFast.from_pretrained("""robot-test/dummy-tokenizer-wordlevel"""					)
           __lowercase          =						"""The Matrix is a 1999 science fiction action film."""

           with concurrent.futures.ThreadPoolExecutor() as executor:
               __lowercase          =						[executor.submit(self.fetch ,		lowercase_ ,		lowercase_					) for i in range(10					)]
               __lowercase          =						[future.result() for future in futures]
               self.assertEqual(lowercase_ ,		[[1, 10, 0, 8, 0, 18, 0, 0, 0, 2] for i in range(10					)]					)




       def    snake_case__      (   self ,		lowerCamelCase__ ,		lowerCamelCase__					)   -> Union[str, Any]:

           """simple docstring"""



           return tokenizer.encode(lowercase_ ,		truncation="""longest_first""" ,		padding="""longest"""					)










'''simple docstring'''
import unittest
import warnings
from dataclasses import dataclass

from transformers.convert_slow_tokenizer import SpmConverter
from transformers.testing_utils import get_tests_dir






@dataclass
class 	SCREAMING_SNAKE_CASE:
       snake_case_			:					str






class 	SCREAMING_SNAKE_CASE(    unittest.TestCase					):

       def    snake_case__      (   self					)   -> Optional[int]:

           """simple docstring"""



           __lowercase          =						get_tests_dir("""fixtures/test_sentencepiece.model"""					)
           __lowercase          =						get_tests_dir("""fixtures/test_sentencepiece_with_bytefallback.model"""					)

           __lowercase          =						FakeOriginalTokenizer(vocab_file=lowerCamelCase__					)

           with warnings.catch_warnings(record=lowerCamelCase__					) as w:
               __lowercase          =						SpmConverter(lowerCamelCase__					)
           self.assertEqual(len(lowerCamelCase__					) ,		0					)

           __lowercase          =						FakeOriginalTokenizer(vocab_file=lowerCamelCase__					)

           with warnings.catch_warnings(record=lowerCamelCase__					) as w:
               __lowercase          =						SpmConverter(lowerCamelCase__					)
           self.assertEqual(len(lowerCamelCase__					) ,		1					)

           self.assertIn(
               """The sentencepiece tokenizer that you are converting to a fast tokenizer uses the byte fallback option"""
               """ which is not implemented in the fast tokenizers.""" ,		str(w[0].message					) ,		)




