



from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


UpperCAmelCase_          =				{"configuration_pegasus": ["PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP", "PegasusConfig"]}

try:
    if not is_sentencepiece_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCAmelCase_          =				["PegasusTokenizer"]

try:
    if not is_tokenizers_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCAmelCase_          =				["PegasusTokenizerFast"]

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCAmelCase_          =				[
        "PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST",
        "PegasusForCausalLM",
        "PegasusForConditionalGeneration",
        "PegasusModel",
        "PegasusPreTrainedModel",
    ]

try:
    if not is_tf_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCAmelCase_          =				[
        "TFPegasusForConditionalGeneration",
        "TFPegasusModel",
        "TFPegasusPreTrainedModel",
    ]

try:
    if not is_flax_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCAmelCase_          =				[
        "FlaxPegasusForConditionalGeneration",
        "FlaxPegasusModel",
        "FlaxPegasusPreTrainedModel",
    ]


if TYPE_CHECKING:
    from .configuration_pegasus import PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusConfig

    try:
        if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_pegasus import PegasusTokenizer

    try:
        if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_pegasus_fast import PegasusTokenizerFast

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_pegasus import (
            PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST,
            PegasusForCausalLM,
            PegasusForConditionalGeneration,
            PegasusModel,
            PegasusPreTrainedModel,
        )

    try:
        if not is_tf_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_tf_pegasus import TFPegasusForConditionalGeneration, TFPegasusModel, TFPegasusPreTrainedModel

    try:
        if not is_flax_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_flax_pegasus import (
            FlaxPegasusForConditionalGeneration,
            FlaxPegasusModel,
            FlaxPegasusPreTrainedModel,
        )

else:
    import sys

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




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 		UpperCAmelCase    (    snake_case_							,unittest.TestCase					):
   SCREAMING_SNAKE_CASE__					      =  PreTrainedTokenizerFast
   SCREAMING_SNAKE_CASE__					      =  False
   SCREAMING_SNAKE_CASE__					      =  True
   SCREAMING_SNAKE_CASE__					      =  '''tokenizer_file'''





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	False  # because we don't have pretrained_vocab_files_map
         super().setUp()
         _lowerCAmelCase			      =	True

         _lowerCAmelCase			      =	['''robot-test/dummy-tokenizer-fast''', '''robot-test/dummy-tokenizer-wordlevel''']
         _lowerCAmelCase			      =	'''SaulLu/dummy-tokenizer-bytelevel-bpe'''

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

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





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





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





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





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





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	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:
                           _lowerCAmelCase			      =	tempfile.mkdtemp()
                           _lowerCAmelCase			      =	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      )
                           _lowerCAmelCase			      =	tmpdirname_orig





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	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:
                           _lowerCAmelCase			      =	tempfile.mkdtemp()
                           _lowerCAmelCase			      =	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      )
                           _lowerCAmelCase			      =	tmpdirname_orig





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name      )

         _lowerCAmelCase			      =	('''a''' for _ in range(1_000      ))
         _lowerCAmelCase			      =	tokenizer.train_new_from_iterator(text_iterator=_lowerCAmelCase							,  length=1_000							,  vocab_size=50      )

         _lowerCAmelCase			      =	new_tokenizer.encode('''a🤗'''      )
         self.assertEqual(_lowerCAmelCase							,  [64, 172, 253, 97, 245]      )






@require_tokenizers
class 		UpperCAmelCase    (    unittest.TestCase					):





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	AutoTokenizer.from_pretrained('''bert-base-cased'''      )
         _lowerCAmelCase			      =	json.loads(tokenizer._tokenizer.to_str()      )
         _lowerCAmelCase			      =	len(_lowerCAmelCase      )

         with tempfile.TemporaryDirectory() as tmp_dir:
               # Hack to save this in the tokenizer_config.json
               _lowerCAmelCase			      =	['''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
               _lowerCAmelCase			      =	AutoTokenizer.from_pretrained(_lowerCAmelCase      )
               self.assertEqual(len(_lowerCAmelCase      )							,  len(_lowerCAmelCase      ) + 1      )
               _lowerCAmelCase			      =	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'''      )      )
               _lowerCAmelCase			      =	['''tokenizer.42.0.0.json''']
               tokenizer.save_pretrained(_lowerCAmelCase      )
               _lowerCAmelCase			      =	AutoTokenizer.from_pretrained(_lowerCAmelCase      )
               self.assertEqual(len(_lowerCAmelCase      )							,  len(_lowerCAmelCase      )      )
               _lowerCAmelCase			      =	json.loads(new_tokenizer._tokenizer.to_str()      )
               self.assertNotIn('''huggingface'''							,  json_tokenizer['''model''']['''vocab''']      )





   def 						__lowerCAmelCase				(						self      ):
         # This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
         _lowerCAmelCase			      =	'''hf-internal-testing/test-two-tokenizers'''

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

         _lowerCAmelCase			      =	'''3.0.0'''
         _lowerCAmelCase			      =	old_transformers.models.auto.AutoTokenizer.from_pretrained(_lowerCAmelCase      )
         self.assertEqual(len(_lowerCAmelCase      )							,  28_996      )
         _lowerCAmelCase			      =	json.loads(old_tokenizer._tokenizer.to_str()      )
         self.assertNotIn('''huggingface'''							,  json_tokenizer['''model''']['''vocab''']      )






@require_tokenizers
class 		UpperCAmelCase    (    unittest.TestCase					):





   def 						__lowerCAmelCase				(						self      ):
         # See https://github.com/huggingface/transformers/pull/12550
         # and https://github.com/huggingface/tokenizers/issues/537
         _lowerCAmelCase			      =	PreTrainedTokenizerFast.from_pretrained('''robot-test/dummy-tokenizer-wordlevel'''      )
         _lowerCAmelCase			      =	'''The Matrix is a 1999 science fiction action film.'''

         with concurrent.futures.ThreadPoolExecutor() as executor:
               _lowerCAmelCase			      =	[executor.submit(self.fetch							,  _lowerCAmelCase							,  _lowerCAmelCase      ) for i in range(10      )]
               _lowerCAmelCase			      =	[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 						__lowerCAmelCase				(						self							,  _lowerCAmelCase							,  _lowerCAmelCase      ):
         return tokenizer.encode(_lowerCAmelCase							,  truncation='''longest_first'''							,  padding='''longest'''      )