


"""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 typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available


lowercase  		=			{
    """configuration_flaubert""": ["""FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FlaubertConfig""", """FlaubertOnnxConfig"""],
    """tokenization_flaubert""": ["""FlaubertTokenizer"""],
}

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					lowercase  		=			[
					    """FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
					    """FlaubertForMultipleChoice""",
					    """FlaubertForQuestionAnswering""",
					    """FlaubertForQuestionAnsweringSimple""",
					    """FlaubertForSequenceClassification""",
					    """FlaubertForTokenClassification""",
					    """FlaubertModel""",
					    """FlaubertWithLMHeadModel""",
					    """FlaubertPreTrainedModel""",
					]

try:
					if not is_tf_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					lowercase  		=			[
					    """TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
					    """TFFlaubertForMultipleChoice""",
					    """TFFlaubertForQuestionAnsweringSimple""",
					    """TFFlaubertForSequenceClassification""",
					    """TFFlaubertForTokenClassification""",
					    """TFFlaubertModel""",
					    """TFFlaubertPreTrainedModel""",
					    """TFFlaubertWithLMHeadModel""",
					]


if TYPE_CHECKING:
					from .configuration_flaubert import FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, FlaubertConfig, FlaubertOnnxConfig
					from .tokenization_flaubert import FlaubertTokenizer

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_flaubert import (
										    FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
										    FlaubertForMultipleChoice,
										    FlaubertForQuestionAnswering,
										    FlaubertForQuestionAnsweringSimple,
										    FlaubertForSequenceClassification,
										    FlaubertForTokenClassification,
										    FlaubertModel,
										    FlaubertPreTrainedModel,
										    FlaubertWithLMHeadModel,
										)

					try:
										if not is_tf_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_tf_flaubert import (
										    TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
										    TFFlaubertForMultipleChoice,
										    TFFlaubertForQuestionAnsweringSimple,
										    TFFlaubertForSequenceClassification,
										    TFFlaubertForTokenClassification,
										    TFFlaubertModel,
										    TFFlaubertPreTrainedModel,
										    TFFlaubertWithLMHeadModel,
										)

else:
					import sys

					lowercase  		=			_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)





