






import os
import warnings
from pathlib import Path
from typing import Optional, Union

from .dynamic_module_utils import custom_object_save
from .tokenization_utils_base import PreTrainedTokenizerBase
from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging


_UpperCAmelCase				:	Optional[int]    						=    logging.get_logger(__name__)

# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
_UpperCAmelCase				:	List[Any]    						=    direct_transformers_import(Path(__file__).parent)


_UpperCAmelCase				:	int    						=    {
    'AutoTokenizer': 'PreTrainedTokenizerBase',
    'AutoFeatureExtractor': 'FeatureExtractionMixin',
    'AutoImageProcessor': 'ImageProcessingMixin',
}


class 		lowerCAmelCase_							(     UpperCamelCase   ):
     __lowerCamelCase					:						Any     =    ['''feature_extractor''', '''tokenizer''']
     # Names need to be attr_class for attr in attributes
     __lowerCamelCase					:						Dict     =    None
     __lowerCamelCase					:						Union[str, Any]     =    None
     __lowerCamelCase					:						Any     =    None





     def __init__(  self       ,   *_UpperCAmelCase       ,   **_UpperCAmelCase     )		->							str:
        # Sanitize args and kwargs
        for key in kwargs:
           if key not in self.attributes:
              raise TypeError(F'''Unexpected keyword argument {key}.'''     )
        for arg, attribute_name in zip(_UpperCAmelCase       ,   self.attributes     ):
           if attribute_name in kwargs:
              raise TypeError(F'''Got multiple values for argument {attribute_name}.'''     )
           else:
              lowerCamelCase											=arg

        if len(_UpperCAmelCase     ) != len(self.attributes     ):
           raise ValueError(
               F'''This processor requires {len(self.attributes     )} arguments: {", ".join(self.attributes     )}. Got '''
               F'''{len(_UpperCAmelCase     )} arguments instead.'''     )

        # Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
        for attribute_name, arg in kwargs.items():
           lowerCamelCase											=getattr(self       ,   F'''{attribute_name}_class'''     )
           # Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
           lowerCamelCase											=AUTO_TO_BASE_CLASS_MAPPING.get(_UpperCAmelCase       ,   _UpperCAmelCase     )
           if isinstance(_UpperCAmelCase       ,   _UpperCAmelCase     ):
              lowerCamelCase											=tuple(getattr(_UpperCAmelCase       ,   _UpperCAmelCase     ) for n in class_name if n is not None     )
           else:
              lowerCamelCase											=getattr(_UpperCAmelCase       ,   _UpperCAmelCase     )

           if not isinstance(_UpperCAmelCase       ,   _UpperCAmelCase     ):
              raise ValueError(
                  F'''Received a {type(_UpperCAmelCase     ).__name__} for argument {attribute_name}, but a {class_name} was expected.'''     )

           setattr(self       ,   _UpperCAmelCase       ,   _UpperCAmelCase     )





     def __repr__(  self     )		->							Optional[int]:
        lowerCamelCase											=[F'''- {name}: {repr(getattr(self       ,   _UpperCAmelCase     )     )}''' for name in self.attributes]
        lowerCamelCase											="""\n""".join(_UpperCAmelCase     )
        return F'''{self.__class__.__name__}:\n{attributes_repr}'''





     def 	lowerCamelCase       (  self       ,   _UpperCAmelCase       ,   _UpperCAmelCase = False       ,   **_UpperCAmelCase     )		->							Tuple:
        os.makedirs(_UpperCAmelCase       ,   exist_ok=_UpperCAmelCase     )

        if push_to_hub:
           lowerCamelCase											=kwargs.pop("""commit_message"""       ,   _UpperCAmelCase     )
           lowerCamelCase											=kwargs.pop("""repo_id"""       ,   save_directory.split(os.path.sep     )[-1]     )
           lowerCamelCase											=self._create_repo(_UpperCAmelCase       ,   **_UpperCAmelCase     )
           lowerCamelCase											=self._get_files_timestamps(_UpperCAmelCase     )
        # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
        # loaded from the Hub.
        if self._auto_class is not None:
           lowerCamelCase											=[getattr(self       ,   _UpperCAmelCase     ) for attribute_name in self.attributes]
           lowerCamelCase											=[(a.init_kwargs if isinstance(_UpperCAmelCase       ,   _UpperCAmelCase     ) else a) for a in attrs]
           custom_object_save(self       ,   _UpperCAmelCase       ,   config=_UpperCAmelCase     )

        for attribute_name in self.attributes:
           lowerCamelCase											=getattr(self       ,   _UpperCAmelCase     )
           # Include the processor class in the attribute config so this processor can then be reloaded with the
           # `AutoProcessor` API.
           if hasattr(_UpperCAmelCase       ,   """_set_processor_class"""     ):
              attribute._set_processor_class(self.__class__.__name__     )
           attribute.save_pretrained(_UpperCAmelCase     )

        if self._auto_class is not None:
           # We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
           for attribute_name in self.attributes:
              lowerCamelCase											=getattr(self       ,   _UpperCAmelCase     )
              if isinstance(_UpperCAmelCase       ,   _UpperCAmelCase     ):
                 del attribute.init_kwargs["auto_map"]

        if push_to_hub:
           self._upload_modified_files(
               _UpperCAmelCase       ,   _UpperCAmelCase       ,   _UpperCAmelCase       ,   commit_message=_UpperCAmelCase       ,   token=kwargs.get("""use_auth_token"""     )       ,   )





     @classmethod
     def 	lowerCamelCase       (  cls       ,   _UpperCAmelCase       ,   _UpperCAmelCase = None       ,   _UpperCAmelCase = False       ,   _UpperCAmelCase = False       ,   _UpperCAmelCase = None       ,   _UpperCAmelCase = "main"       ,   **_UpperCAmelCase       ,   )		->							str:
        lowerCamelCase											=cache_dir
        lowerCamelCase											=force_download
        lowerCamelCase											=local_files_only
        lowerCamelCase											=revision

        lowerCamelCase											=kwargs.pop("""use_auth_token"""       ,   _UpperCAmelCase     )
        if use_auth_token is not None:
           warnings.warn(
               """The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers."""       ,   _UpperCAmelCase     )
           if token is not None:
              raise ValueError(
                  """`token` and `use_auth_token` are both specified. Please set only the argument `token`."""     )
           lowerCamelCase											=use_auth_token

        if token is not None:
           # change to `token` in a follow-up PR
           lowerCamelCase											=token

        lowerCamelCase											=cls._get_arguments_from_pretrained(_UpperCAmelCase       ,   **_UpperCAmelCase     )
        return cls(*_UpperCAmelCase     )





     @classmethod
     def 	lowerCamelCase       (  cls       ,   _UpperCAmelCase="AutoProcessor"     )		->							Dict:
        if not isinstance(_UpperCAmelCase       ,   _UpperCAmelCase     ):
           lowerCamelCase											=auto_class.__name__

        import transformers.models.auto as auto_module

        if not hasattr(_UpperCAmelCase       ,   _UpperCAmelCase     ):
           raise ValueError(F'''{auto_class} is not a valid auto class.'''     )

        lowerCamelCase											=auto_class





     @classmethod
     def 	lowerCamelCase       (  cls       ,   _UpperCAmelCase       ,   **_UpperCAmelCase     )		->							Optional[Any]:
        lowerCamelCase											=[]
        for attribute_name in cls.attributes:
           lowerCamelCase											=getattr(cls       ,   F'''{attribute_name}_class'''     )
           if isinstance(_UpperCAmelCase       ,   _UpperCAmelCase     ):
              lowerCamelCase											=tuple(getattr(_UpperCAmelCase       ,   _UpperCAmelCase     ) if n is not None else None for n in class_name     )
              lowerCamelCase											=kwargs.get("""use_fast"""       ,   _UpperCAmelCase     )
              if use_fast and classes[1] is not None:
                 lowerCamelCase											=classes[1]
              else:
                 lowerCamelCase											=classes[0]
           else:
              lowerCamelCase											=getattr(_UpperCAmelCase       ,   _UpperCAmelCase     )

           args.append(attribute_class.from_pretrained(_UpperCAmelCase       ,   **_UpperCAmelCase     )     )
        return args





     @property
     def 	lowerCamelCase       (  self     )		->							Any:
        lowerCamelCase											=getattr(self       ,   self.attributes[0]     )
        return getattr(_UpperCAmelCase       ,   """model_input_names"""       ,   _UpperCAmelCase     )




_UpperCAmelCase				:	str    						=    copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
   _UpperCAmelCase				:	Optional[int]    						=    ProcessorMixin.push_to_hub.__doc__.format(
       object='processor', object_class='AutoProcessor', object_files='processor files'
   )







import unittest

from transformers import ErnieMTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


_UpperCAmelCase				:	Any    						=    get_tests_dir('fixtures/spiece.model')


@require_sentencepiece
@require_tokenizers
class 		lowerCAmelCase_							(     UpperCamelCase							,    unittest.TestCase   ):
     __lowerCamelCase					:						List[Any]     =    ErnieMTokenizer
     __lowerCamelCase					:						Optional[Any]     =    False
     __lowerCamelCase					:						Optional[int]     =    True
     __lowerCamelCase					:						str     =    False
     __lowerCamelCase					:						Any     =    False





     def 	lowerCamelCase       (  self     )		->							Any:
        super().setUp()

        # We have a SentencePiece fixture for testing
        lowerCamelCase											=ErnieMTokenizer(_UpperCAmelCase       ,   unk_token="""<unk>"""       ,   pad_token="""<pad>"""     )
        tokenizer.save_pretrained(self.tmpdirname     )





     def 	lowerCamelCase       (  self       ,   _UpperCAmelCase     )		->							Union[str, Any]:
        lowerCamelCase											="""this is a test"""
        lowerCamelCase											="""this is a test"""
        return input_text, output_text





     def 	lowerCamelCase       (  self     )		->							List[Any]:
        lowerCamelCase											="""<pad>"""
        lowerCamelCase											=0

        self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase     )       ,   _UpperCAmelCase     )
        self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase     )       ,   _UpperCAmelCase     )





     def 	lowerCamelCase       (  self     )		->							List[str]:
        lowerCamelCase											=list(self.get_tokenizer().get_vocab().keys()     )

        self.assertEqual(vocab_keys[0]       ,   """<pad>"""     )
        self.assertEqual(vocab_keys[1]       ,   """<unk>"""     )
        self.assertEqual(vocab_keys[-1]       ,   """▁eloquent"""     )
        self.assertEqual(len(_UpperCAmelCase     )       ,   30000     )





     def 	lowerCamelCase       (  self     )		->							Any:
        self.assertEqual(self.get_tokenizer().vocab_size       ,   30000     )





     def 	lowerCamelCase       (  self     )		->							Any:
        if not self.test_rust_tokenizer:
           return

        lowerCamelCase											=self.get_tokenizer()
        lowerCamelCase											=self.get_rust_tokenizer()

        lowerCamelCase											="""I was born in 92000, and this is falsé."""

        lowerCamelCase											=tokenizer.tokenize(_UpperCAmelCase     )
        lowerCamelCase											=rust_tokenizer.tokenize(_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   _UpperCAmelCase     )

        lowerCamelCase											=tokenizer.encode(_UpperCAmelCase       ,   add_special_tokens=_UpperCAmelCase     )
        lowerCamelCase											=rust_tokenizer.encode(_UpperCAmelCase       ,   add_special_tokens=_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   _UpperCAmelCase     )

        lowerCamelCase											=self.get_rust_tokenizer()
        lowerCamelCase											=tokenizer.encode(_UpperCAmelCase     )
        lowerCamelCase											=rust_tokenizer.encode(_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   _UpperCAmelCase     )





     def 	lowerCamelCase       (  self     )		->							Union[str, Any]:
        lowerCamelCase											=ErnieMTokenizer(_UpperCAmelCase       ,   do_lower_case=_UpperCAmelCase       ,   unk_token="""<unk>"""       ,   pad_token="""<pad>"""     )

        lowerCamelCase											=tokenizer.tokenize("""This is a test"""     )
        self.assertListEqual(_UpperCAmelCase       ,   ["""▁this""", """▁is""", """▁a""", """▁test"""]     )

        self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase     )       ,   [48, 25, 21, 1289]     )

        lowerCamelCase											=tokenizer.tokenize("""I was born in 92000, and this is falsé."""     )
        # ErnieMTokenizer(paddlenlp implementation) outputs '9' instead of '_9' so to mimic that '_9' is changed to '9'
        self.assertListEqual(
            _UpperCAmelCase       ,   ["""▁i""", """▁was""", """▁born""", """▁in""", """9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """é""", """."""]     )
        lowerCamelCase											=tokenizer.convert_tokens_to_ids(_UpperCAmelCase     )
        self.assertListEqual(_UpperCAmelCase       ,   [31, 23, 386, 19, 518, 3050, 15, 17, 48, 25, 8256, 18, 1, 9]     )

        lowerCamelCase											=tokenizer.convert_ids_to_tokens(_UpperCAmelCase     )
        self.assertListEqual(
            _UpperCAmelCase       ,   ["""▁i""", """▁was""", """▁born""", """▁in""", """9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """<unk>""", """."""]       ,   )





     def 	lowerCamelCase       (  self     )		->							List[str]:
        lowerCamelCase											=ErnieMTokenizer(_UpperCAmelCase       ,   unk_token="""<unk>"""       ,   pad_token="""<pad>"""     )

        lowerCamelCase											=tokenizer.encode("""sequence builders"""     )
        lowerCamelCase											=tokenizer.encode("""multi-sequence build"""     )

        lowerCamelCase											=tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase     )
        lowerCamelCase											=tokenizer.build_inputs_with_special_tokens(_UpperCAmelCase       ,   _UpperCAmelCase     )

        assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
        assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + [
            tokenizer.sep_token_id
        ] + text_a + [tokenizer.sep_token_id]





     @slow
     def 	lowerCamelCase       (  self     )		->							Dict:
        # fmt: off
        lowerCamelCase											={"""input_ids""": [[0, 11062, 82772, 7, 15, 82772, 538, 51529, 237, 17198, 1290, 206, 9, 215175, 1314, 136, 17198, 1290, 206, 9, 56359, 42, 122009, 9, 16466, 16, 87344, 4537, 9, 4717, 78381, 6, 159958, 7, 15, 24480, 618, 4, 527, 22693, 9, 304, 4, 2777, 24480, 9874, 4, 43523, 594, 4, 803, 18392, 33189, 18, 4, 43523, 24447, 5, 5, 5, 16, 100, 24955, 83658, 9626, 144057, 15, 839, 22335, 16, 136, 24955, 83658, 83479, 15, 39102, 724, 16, 678, 645, 6460, 1328, 4589, 42, 122009, 115774, 23, 3559, 1328, 46876, 7, 136, 53894, 1940, 42227, 41159, 17721, 823, 425, 4, 27512, 98722, 206, 136, 5531, 4970, 919, 17336, 5, 2], [0, 20080, 618, 83, 82775, 47, 479, 9, 1517, 73, 53894, 333, 80581, 110117, 18811, 5256, 1295, 51, 152526, 297, 7986, 390, 124416, 538, 35431, 214, 98, 15044, 25737, 136, 7108, 43701, 23, 756, 135355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 581, 63773, 119455, 6, 147797, 88203, 7, 645, 70, 21, 3285, 10269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}
        # fmt: on

        self.tokenizer_integration_test_util(
            expected_encoding=_UpperCAmelCase       ,   model_name="""susnato/ernie-m-base_pytorch"""       ,   sequences=[
                """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """
                """general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet...) for Natural """
                """Language Understanding (NLU) and Natural Language Generation (NLG) with over32+ pretrained """
                """models in100+ languages and deep interoperability between Jax, PyTorch and TensorFlow.""",
                """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """
                """conditioning on both left and right context in all layers.""",
                """The quick brown fox jumps over the lazy dog.""",
            ]       ,   )