






import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from huggingface_hub import HfFolder, Repository, create_repo, delete_repo
from requests.exceptions import HTTPError

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoProcessor,
    AutoTokenizer,
    BertTokenizer,
    ProcessorMixin,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available


sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402
from test_module.custom_processing import CustomProcessor  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


__a   :							int						= get_tests_dir("fixtures/dummy_feature_extractor_config.json")
__a   :							List[str]						= get_tests_dir("fixtures/vocab.json")
__a   :							str						= get_tests_dir("fixtures")


class    __lowercase   (						unittest.TestCase	):







     '''simple docstring'''
     SCREAMING_SNAKE_CASE     =					["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]




     def 		lowerCAmelCase_  (					self							:      Any					):


         """simple docstring"""



         __A       =						0




     def 		lowerCAmelCase_  (					self							:      Optional[Any]					):


         """simple docstring"""



         __A       =						AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h"""					)
         self.assertIsInstance(UpperCamelCase_			,						UpperCamelCase_					)




     def 		lowerCAmelCase_  (					self							:      Optional[int]					):


         """simple docstring"""



         with tempfile.TemporaryDirectory() as tmpdirname:
             __A       =						WavaVecaConfig()
             __A       =						AutoProcessor.from_pretrained("""facebook/wav2vec2-base-960h"""					)

             # save in new folder
             model_config.save_pretrained(UpperCamelCase_					)
             processor.save_pretrained(UpperCamelCase_					)

             __A       =						AutoProcessor.from_pretrained(UpperCamelCase_					)

         self.assertIsInstance(UpperCamelCase_			,						UpperCamelCase_					)




     def 		lowerCAmelCase_  (					self							:      Union[str, Any]					):


         """simple docstring"""



         with tempfile.TemporaryDirectory() as tmpdirname:
             # copy relevant files
             copyfile(UpperCamelCase_			,						os.path.join(UpperCamelCase_			,						UpperCamelCase_					)					)
             copyfile(UpperCamelCase_			,						os.path.join(UpperCamelCase_			,						"""vocab.json"""					)					)

             __A       =						AutoProcessor.from_pretrained(UpperCamelCase_					)

         self.assertIsInstance(UpperCamelCase_			,						UpperCamelCase_					)




     def 		lowerCAmelCase_  (					self							:      Dict					):


         """simple docstring"""



         with tempfile.TemporaryDirectory() as tmpdirname:
             __A       =						WavaVecaFeatureExtractor()
             __A       =						AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h"""					)

             __A       =						WavaVecaProcessor(UpperCamelCase_			,						UpperCamelCase_					)

             # save in new folder
             processor.save_pretrained(UpperCamelCase_					)

             # drop `processor_class` in tokenizer
             with open(os.path.join(UpperCamelCase_			,						UpperCamelCase_					)			,						"""r"""					) as f:
                 __A       =						json.load(UpperCamelCase_					)
                 config_dict.pop("""processor_class"""					)

             with open(os.path.join(UpperCamelCase_			,						UpperCamelCase_					)			,						"""w"""					) as f:
                 f.write(json.dumps(UpperCamelCase_					)					)

             __A       =						AutoProcessor.from_pretrained(UpperCamelCase_					)

         self.assertIsInstance(UpperCamelCase_			,						UpperCamelCase_					)




     def 		lowerCAmelCase_  (					self							:      int					):


         """simple docstring"""



         with tempfile.TemporaryDirectory() as tmpdirname:
             __A       =						WavaVecaFeatureExtractor()
             __A       =						AutoTokenizer.from_pretrained("""facebook/wav2vec2-base-960h"""					)

             __A       =						WavaVecaProcessor(UpperCamelCase_			,						UpperCamelCase_					)

             # save in new folder
             processor.save_pretrained(UpperCamelCase_					)

             # drop `processor_class` in feature extractor
             with open(os.path.join(UpperCamelCase_			,						UpperCamelCase_					)			,						"""r"""					) as f:
                 __A       =						json.load(UpperCamelCase_					)
                 config_dict.pop("""processor_class"""					)

             with open(os.path.join(UpperCamelCase_			,						UpperCamelCase_					)			,						"""w"""					) as f:
                 f.write(json.dumps(UpperCamelCase_					)					)

             __A       =						AutoProcessor.from_pretrained(UpperCamelCase_					)

         self.assertIsInstance(UpperCamelCase_			,						UpperCamelCase_					)




     def 		lowerCAmelCase_  (					self							:      Optional[Any]					):


         """simple docstring"""



         with tempfile.TemporaryDirectory() as tmpdirname:
             __A       =						WavaVecaConfig(processor_class="""Wav2Vec2Processor"""					)
             model_config.save_pretrained(UpperCamelCase_					)
             # copy relevant files
             copyfile(UpperCamelCase_			,						os.path.join(UpperCamelCase_			,						"""vocab.json"""					)					)
             # create emtpy sample processor
             with open(os.path.join(UpperCamelCase_			,						UpperCamelCase_					)			,						"""w"""					) as f:
                 f.write("""{}"""					)

             __A       =						AutoProcessor.from_pretrained(UpperCamelCase_					)

         self.assertIsInstance(UpperCamelCase_			,						UpperCamelCase_					)




     def 		lowerCAmelCase_  (					self							:      Any					):


         """simple docstring"""



         with self.assertRaises(UpperCamelCase_					):
             __A       =						AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor"""					)
         # If remote code is disabled, we can't load this config.
         with self.assertRaises(UpperCamelCase_					):
             __A       =						AutoProcessor.from_pretrained(
                 """hf-internal-testing/test_dynamic_processor"""			,						trust_remote_code=UpperCamelCase_					)

         __A       =						AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor"""			,						trust_remote_code=UpperCamelCase_					)
         self.assertTrue(processor.special_attribute_present					)
         self.assertEqual(processor.__class__.__name__			,						"""NewProcessor"""					)

         __A       =						processor.feature_extractor
         self.assertTrue(feature_extractor.special_attribute_present					)
         self.assertEqual(feature_extractor.__class__.__name__			,						"""NewFeatureExtractor"""					)

         __A       =						processor.tokenizer
         self.assertTrue(tokenizer.special_attribute_present					)
         if is_tokenizers_available():
             self.assertEqual(tokenizer.__class__.__name__			,						"""NewTokenizerFast"""					)

             # Test we can also load the slow version
             __A       =						AutoProcessor.from_pretrained(
                 """hf-internal-testing/test_dynamic_processor"""			,						trust_remote_code=UpperCamelCase_			,						use_fast=UpperCamelCase_					)
             __A       =						new_processor.tokenizer
             self.assertTrue(new_tokenizer.special_attribute_present					)
             self.assertEqual(new_tokenizer.__class__.__name__			,						"""NewTokenizer"""					)
         else:
             self.assertEqual(tokenizer.__class__.__name__			,						"""NewTokenizer"""					)




     def 		lowerCAmelCase_  (					self							:      List[Any]					):


         """simple docstring"""



         try:
             AutoConfig.register("""custom"""			,						UpperCamelCase_					)
             AutoFeatureExtractor.register(UpperCamelCase_			,						UpperCamelCase_					)
             AutoTokenizer.register(UpperCamelCase_			,						slow_tokenizer_class=UpperCamelCase_					)
             AutoProcessor.register(UpperCamelCase_			,						UpperCamelCase_					)
             # Trying to register something existing in the Transformers library will raise an error
             with self.assertRaises(UpperCamelCase_					):
                 AutoProcessor.register(UpperCamelCase_			,						UpperCamelCase_					)

             # Now that the config is registered, it can be used as any other config with the auto-API
             __A       =						CustomFeatureExtractor.from_pretrained(UpperCamelCase_					)

             with tempfile.TemporaryDirectory() as tmp_dir:
                 __A       =						os.path.join(UpperCamelCase_			,						"""vocab.txt"""					)
                 with open(UpperCamelCase_			,						"""w"""			,						encoding="""utf-8"""					) as vocab_writer:
                     vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens]					)					)
                 __A       =						CustomTokenizer(UpperCamelCase_					)

             __A       =						CustomProcessor(UpperCamelCase_			,						UpperCamelCase_					)

             with tempfile.TemporaryDirectory() as tmp_dir:
                 processor.save_pretrained(UpperCamelCase_					)
                 __A       =						AutoProcessor.from_pretrained(UpperCamelCase_					)
                 self.assertIsInstance(UpperCamelCase_			,						UpperCamelCase_					)

         finally:
             if "custom" in CONFIG_MAPPING._extra_content:
                 del CONFIG_MAPPING._extra_content["custom"]
             if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
                 del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
             if CustomConfig in TOKENIZER_MAPPING._extra_content:
                 del TOKENIZER_MAPPING._extra_content[CustomConfig]
             if CustomConfig in PROCESSOR_MAPPING._extra_content:
                 del PROCESSOR_MAPPING._extra_content[CustomConfig]




     def 		lowerCAmelCase_  (					self							:      int					):


         """simple docstring"""



         class    __lowercase   (						lowercase_	):







              '''simple docstring'''
              SCREAMING_SNAKE_CASE     =					False


         class    __lowercase   (						lowercase_	):







              '''simple docstring'''
              SCREAMING_SNAKE_CASE     =					False


         class    __lowercase   (						lowercase_	):







              '''simple docstring'''
              SCREAMING_SNAKE_CASE     =					"AutoFeatureExtractor"
              SCREAMING_SNAKE_CASE     =					"AutoTokenizer"
              SCREAMING_SNAKE_CASE     =					False

         try:
             AutoConfig.register("""custom"""			,						UpperCamelCase_					)
             AutoFeatureExtractor.register(UpperCamelCase_			,						UpperCamelCase_					)
             AutoTokenizer.register(UpperCamelCase_			,						slow_tokenizer_class=UpperCamelCase_					)
             AutoProcessor.register(UpperCamelCase_			,						UpperCamelCase_					)
             # If remote code is not set, the default is to use local classes.
             __A       =						AutoProcessor.from_pretrained("""hf-internal-testing/test_dynamic_processor"""					)
             self.assertEqual(processor.__class__.__name__			,						"""NewProcessor"""					)
             self.assertFalse(processor.special_attribute_present					)
             self.assertFalse(processor.feature_extractor.special_attribute_present					)
             self.assertFalse(processor.tokenizer.special_attribute_present					)

             # If remote code is disabled, we load the local ones.
             __A       =						AutoProcessor.from_pretrained(
                 """hf-internal-testing/test_dynamic_processor"""			,						trust_remote_code=UpperCamelCase_					)
             self.assertEqual(processor.__class__.__name__			,						"""NewProcessor"""					)
             self.assertFalse(processor.special_attribute_present					)
             self.assertFalse(processor.feature_extractor.special_attribute_present					)
             self.assertFalse(processor.tokenizer.special_attribute_present					)

             # If remote is enabled, we load from the Hub.
             __A       =						AutoProcessor.from_pretrained(
                 """hf-internal-testing/test_dynamic_processor"""			,						trust_remote_code=UpperCamelCase_					)
             self.assertEqual(processor.__class__.__name__			,						"""NewProcessor"""					)
             self.assertTrue(processor.special_attribute_present					)
             self.assertTrue(processor.feature_extractor.special_attribute_present					)
             self.assertTrue(processor.tokenizer.special_attribute_present					)

         finally:
             if "custom" in CONFIG_MAPPING._extra_content:
                 del CONFIG_MAPPING._extra_content["custom"]
             if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
                 del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
             if CustomConfig in TOKENIZER_MAPPING._extra_content:
                 del TOKENIZER_MAPPING._extra_content[CustomConfig]
             if CustomConfig in PROCESSOR_MAPPING._extra_content:
                 del PROCESSOR_MAPPING._extra_content[CustomConfig]




     def 		lowerCAmelCase_  (					self							:      Optional[Any]					):


         """simple docstring"""



         __A       =						AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-bert"""					)
         self.assertEqual(processor.__class__.__name__			,						"""BertTokenizerFast"""					)





     def 		lowerCAmelCase_  (					self							:      Any					):


         """simple docstring"""



         __A       =						AutoProcessor.from_pretrained("""hf-internal-testing/tiny-random-convnext"""					)
         self.assertEqual(processor.__class__.__name__			,						"""ConvNextImageProcessor"""					)


@is_staging_test
class    __lowercase   (						unittest.TestCase	):







     '''simple docstring'''
     SCREAMING_SNAKE_CASE     =					["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]




     @classmethod
     def 		lowerCAmelCase_  (					cls							:      Dict					):


         """simple docstring"""



         __A       =						TOKEN
         HfFolder.save_token(UpperCamelCase_					)




     @classmethod
     def 		lowerCAmelCase_  (					cls							:      Tuple					):


         """simple docstring"""



         try:
             delete_repo(token=cls._token			,						repo_id="""test-processor"""					)
         except HTTPError:
             pass

         try:
             delete_repo(token=cls._token			,						repo_id="""valid_org/test-processor-org"""					)
         except HTTPError:
             pass

         try:
             delete_repo(token=cls._token			,						repo_id="""test-dynamic-processor"""					)
         except HTTPError:
             pass




     def 		lowerCAmelCase_  (					self							:      int					):


         """simple docstring"""



         __A       =						WavaVecaProcessor.from_pretrained(UpperCamelCase_					)
         with tempfile.TemporaryDirectory() as tmp_dir:
             processor.save_pretrained(
                 os.path.join(UpperCamelCase_			,						"""test-processor"""					)			,						push_to_hub=UpperCamelCase_			,						use_auth_token=self._token					)

             __A       =						WavaVecaProcessor.from_pretrained(F"{USER}/test-processor"					)
             for k, v in processor.feature_extractor.__dict__.items():
                 self.assertEqual(UpperCamelCase_			,						getattr(new_processor.feature_extractor			,						UpperCamelCase_					)					)
             self.assertDictEqual(new_processor.tokenizer.get_vocab()			,						processor.tokenizer.get_vocab()					)




     def 		lowerCAmelCase_  (					self							:      int					):


         """simple docstring"""



         __A       =						WavaVecaProcessor.from_pretrained(UpperCamelCase_					)

         with tempfile.TemporaryDirectory() as tmp_dir:
             processor.save_pretrained(
                 os.path.join(UpperCamelCase_			,						"""test-processor-org"""					)			,						push_to_hub=UpperCamelCase_			,						use_auth_token=self._token			,						organization="""valid_org"""			,						)

             __A       =						WavaVecaProcessor.from_pretrained("""valid_org/test-processor-org"""					)
             for k, v in processor.feature_extractor.__dict__.items():
                 self.assertEqual(UpperCamelCase_			,						getattr(new_processor.feature_extractor			,						UpperCamelCase_					)					)
             self.assertDictEqual(new_processor.tokenizer.get_vocab()			,						processor.tokenizer.get_vocab()					)





     def 		lowerCAmelCase_  (					self							:      str					):


         """simple docstring"""



         CustomFeatureExtractor.register_for_auto_class()
         CustomTokenizer.register_for_auto_class()
         CustomProcessor.register_for_auto_class()

         __A       =						CustomFeatureExtractor.from_pretrained(UpperCamelCase_					)

         with tempfile.TemporaryDirectory() as tmp_dir:
             __A       =						os.path.join(UpperCamelCase_			,						"""vocab.txt"""					)
             with open(UpperCamelCase_			,						"""w"""			,						encoding="""utf-8"""					) as vocab_writer:
                 vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens]					)					)
             __A       =						CustomTokenizer(UpperCamelCase_					)

         __A       =						CustomProcessor(UpperCamelCase_			,						UpperCamelCase_					)

         with tempfile.TemporaryDirectory() as tmp_dir:
             create_repo(F"{USER}/test-dynamic-processor"			,						token=self._token					)
             __A       =						Repository(UpperCamelCase_			,						clone_from=F"{USER}/test-dynamic-processor"			,						token=self._token					)
             processor.save_pretrained(UpperCamelCase_					)

             # This has added the proper auto_map field to the feature extractor config
             self.assertDictEqual(
                 processor.feature_extractor.auto_map			,						{
                     """AutoFeatureExtractor""": """custom_feature_extraction.CustomFeatureExtractor""",
                     """AutoProcessor""": """custom_processing.CustomProcessor""",
                 }			,						)

             # This has added the proper auto_map field to the tokenizer config
             with open(os.path.join(UpperCamelCase_			,						"""tokenizer_config.json"""					)					) as f:
                 __A       =						json.load(UpperCamelCase_					)
             self.assertDictEqual(
                 tokenizer_config["""auto_map"""]			,						{
                     """AutoTokenizer""": ["""custom_tokenization.CustomTokenizer""", None],
                     """AutoProcessor""": """custom_processing.CustomProcessor""",
                 }			,						)

             # The code has been copied from fixtures
             self.assertTrue(os.path.isfile(os.path.join(UpperCamelCase_			,						"""custom_feature_extraction.py"""					)					)					)
             self.assertTrue(os.path.isfile(os.path.join(UpperCamelCase_			,						"""custom_tokenization.py"""					)					)					)
             self.assertTrue(os.path.isfile(os.path.join(UpperCamelCase_			,						"""custom_processing.py"""					)					)					)

             repo.push_to_hub()

         __A       =						AutoProcessor.from_pretrained(F"{USER}/test-dynamic-processor"			,						trust_remote_code=UpperCamelCase_					)
         # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
         self.assertEqual(new_processor.__class__.__name__			,						"""CustomProcessor"""					)












from typing import TYPE_CHECKING

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


__a   :							Optional[int]						= {"configuration_xlnet": ["XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLNetConfig"]}

try:
  if not is_sentencepiece_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __a   :							Tuple						= ["XLNetTokenizer"]

try:
  if not is_tokenizers_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __a   :							List[str]						= ["XLNetTokenizerFast"]

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __a   :							Any						= [
      "XLNET_PRETRAINED_MODEL_ARCHIVE_LIST",
      "XLNetForMultipleChoice",
      "XLNetForQuestionAnswering",
      "XLNetForQuestionAnsweringSimple",
      "XLNetForSequenceClassification",
      "XLNetForTokenClassification",
      "XLNetLMHeadModel",
      "XLNetModel",
      "XLNetPreTrainedModel",
      "load_tf_weights_in_xlnet",
  ]

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __a   :							Dict						= [
      "TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST",
      "TFXLNetForMultipleChoice",
      "TFXLNetForQuestionAnsweringSimple",
      "TFXLNetForSequenceClassification",
      "TFXLNetForTokenClassification",
      "TFXLNetLMHeadModel",
      "TFXLNetMainLayer",
      "TFXLNetModel",
      "TFXLNetPreTrainedModel",
  ]


if TYPE_CHECKING:
  from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig

  try:
    if not is_sentencepiece_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_xlnet import XLNetTokenizer

  try:
    if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_xlnet_fast import XLNetTokenizerFast

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_xlnet import (
        XLNET_PRETRAINED_MODEL_ARCHIVE_LIST,
        XLNetForMultipleChoice,
        XLNetForQuestionAnswering,
        XLNetForQuestionAnsweringSimple,
        XLNetForSequenceClassification,
        XLNetForTokenClassification,
        XLNetLMHeadModel,
        XLNetModel,
        XLNetPreTrainedModel,
        load_tf_weights_in_xlnet,
    )

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_xlnet import (
        TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFXLNetForMultipleChoice,
        TFXLNetForQuestionAnsweringSimple,
        TFXLNetForSequenceClassification,
        TFXLNetForTokenClassification,
        TFXLNetLMHeadModel,
        TFXLNetMainLayer,
        TFXLNetModel,
        TFXLNetPreTrainedModel,
    )

else:
  import sys

  __a   :							str						= _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)




