


"""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 			SCREAMING_SNAKE_CASE_  (   _lowercase	,      unittest.TestCase):




							'''simple docstring'''





							__magic_name__					:     int				  =  PreTrainedTokenizerFast
							__magic_name__					:     Tuple				  =  False
							__magic_name__					:     str				  =  True
							__magic_name__					:     Tuple				  =  '''tokenizer_file'''




							def        UpperCAmelCase (						self)   ->	Dict:







								'''simple docstring'''




								snake_case__  :						Union[str, Any]		=      False  # because we don't have pretrained_vocab_files_map
								super().setUp()
								snake_case__  :						Any		=      True

								snake_case__  :						List[str]		=      ["robot-test/dummy-tokenizer-fast", "robot-test/dummy-tokenizer-wordlevel"]
								snake_case__  :						List[str]		=      "SaulLu/dummy-tokenizer-bytelevel-bpe"

								# Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
								snake_case__  :						Tuple		=      [(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        UpperCAmelCase (						self)   ->	Optional[int]:







								'''simple docstring'''




								pass




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







								'''simple docstring'''




								pass




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







								'''simple docstring'''




								pass




							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								pass




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







								'''simple docstring'''




								snake_case__  :						Optional[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__  :						List[str]		=      tempfile.mkdtemp()
											snake_case__  :						Optional[Any]		=      self.rust_tokenizer_class.from_pretrained(lowerCamelCase__	,					**lowerCamelCase__)

											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[Any]		=      tmpdirname_orig




							def        UpperCAmelCase (						self)   ->	Dict:







								'''simple docstring'''




								snake_case__  :						Tuple		=      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__  :						str		=      self.rust_tokenizer_class.from_pretrained(lowerCamelCase__	,					**lowerCamelCase__)

											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__  :						int		=      tmpdirname_orig







							def        UpperCAmelCase (						self)   ->	int:







								'''simple docstring'''




								snake_case__  :						str		=      self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name)

								snake_case__  :						Dict		=      ("a" for _ in range(1_000))
								snake_case__  :						Any		=      tokenizer.train_new_from_iterator(text_iterator=lowerCamelCase__	,					length=1_000	,					vocab_size=50)

								snake_case__  :						Optional[Any]		=      new_tokenizer.encode("a🤗")
								self.assertEqual(lowerCamelCase__	,					[64, 172, 253, 97, 245])


@require_tokenizers
class 			SCREAMING_SNAKE_CASE_  (   unittest.TestCase):




							'''simple docstring'''





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







								'''simple docstring'''




								snake_case__  :						List[Any]		=      AutoTokenizer.from_pretrained("bert-base-cased")
								snake_case__  :						Dict		=      json.loads(tokenizer._tokenizer.to_str())
								snake_case__  :						Any		=      len(lowerCamelCase__)

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

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







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







								'''simple docstring'''




								snake_case__  :						List[Any]		=      "hf-internal-testing/test-two-tokenizers"

								# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
								snake_case__  :						Union[str, Any]		=      AutoTokenizer.from_pretrained(lowerCamelCase__)
								self.assertEqual(len(lowerCamelCase__)	,					28_997)
								snake_case__  :						Optional[Any]		=      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__  :						Any		=      "3.0.0"
								snake_case__  :						Optional[Any]		=      old_transformers.models.auto.AutoTokenizer.from_pretrained(lowerCamelCase__)
								self.assertEqual(len(lowerCamelCase__)	,					28_996)
								snake_case__  :						Any		=      json.loads(old_tokenizer._tokenizer.to_str())
								self.assertNotIn("huggingface"	,					json_tokenizer["model"]["vocab"])


@require_tokenizers
class 			SCREAMING_SNAKE_CASE_  (   unittest.TestCase):




							'''simple docstring'''





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







								'''simple docstring'''




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

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







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







								'''simple docstring'''




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











'''simple docstring'''






from __future__ import annotations

from enum import Enum, unique
from typing import TypeVar

# Create a generic variable that can be 'Enum', or any subclass.
lowercase						:   Any      						=							TypeVar('''T''', bound='''Enum''')

@unique
class 	SCREAMING_SNAKE_CASE_		(							lowerCamelCase_					):
 __snake_case						:  Union[str, Any]       =   8_0
 __snake_case						:  Optional[Any]       =   7_0
 __snake_case						:  List[str]       =   6_0
 __snake_case						:  str       =   5_0
 __snake_case						:  Tuple       =   4_0
 __snake_case						:  Union[str, Any]       =   3_0
 __snake_case						:  Dict       =   2_0
 __snake_case						:  str       =   1_0






@unique
class 	SCREAMING_SNAKE_CASE_		(							lowerCamelCase_					):
 __snake_case						:  Optional[Any]       =   2_4
 __snake_case						:  List[str]       =   2_1
 __snake_case						:  Any       =   1_8
 __snake_case						:  Union[str, Any]       =   1_5
 __snake_case						:  Dict       =   1_2
 __snake_case						:  Union[str, Any]       =   9
 __snake_case						:  List[str]       =   6
 __snake_case						:  Optional[int]       =   3
 __snake_case						:  Tuple       =   2
 __snake_case						:  Any       =   1
 __snake_case						:  Optional[int]       =   -1
 __snake_case						:  Optional[int]       =   -2
 __snake_case						:  str       =   -3
 __snake_case						:  Optional[Any]       =   -6
 __snake_case						:  Optional[int]       =   -9
 __snake_case						:  List[Any]       =   -1_2
 __snake_case						:  str       =   -1_5
 __snake_case						:  str       =   -1_8
 __snake_case						:  Dict       =   -2_1
 __snake_case						:  int       =   -2_4



 @classmethod
 def  SCREAMING_SNAKE_CASE(	cls			):






        '''simple docstring'''




        return {unit.name: unit.value for unit in cls if unit.value > 0}





 @classmethod
 def  SCREAMING_SNAKE_CASE(	cls			):






        '''simple docstring'''




        return {unit.name: unit.value for unit in cls if unit.value < 0}






def 		a_(			lowerCamelCase   )					->str:






       '''simple docstring'''




       lowercase	:		Tuple    =   SIUnit.get_positive() if value > 0 else SIUnit.get_negative()
       for name_prefix, value_prefix in prefixes.items():
              lowercase	:		Dict    =   value / (10**value_prefix)
              if numerical_part > 1:
                     return f"""{numerical_part!s} {name_prefix}"""
       return str(lowerCamelCase   )




def 		a_(			lowerCamelCase   )					->str:






       '''simple docstring'''




       for prefix in BinaryUnit:
              lowercase	:		Dict    =   value / (2**prefix.value)
              if numerical_part > 1:
                     return f"""{numerical_part!s} {prefix.name}"""
       return str(lowerCamelCase   )


if __name__ == "__main__":
      import doctest

      doctest.testmod()




