

import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


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

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402







class 						__magic_name__			(							unittest.TestCase							):

   '''simple docstring'''




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






     """simple docstring"""






     a__  =0



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






     """simple docstring"""






     a__  =AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32'''       )
     self.assertIsInstance(lowercase_,    lowercase_       )



   def  _UpperCAmelCase (				self       )							->    Optional[Any]:






     """simple docstring"""






     with tempfile.TemporaryDirectory() as tmpdirname:
       a__  =Path(lowercase_       ) / '''preprocessor_config.json'''
       a__  =Path(lowercase_       ) / '''config.json'''
       json.dump(
           {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''},    open(lowercase_,    '''w'''       ),    )
       json.dump({'''model_type''': '''clip'''},    open(lowercase_,    '''w'''       )       )

       a__  =AutoImageProcessor.from_pretrained(lowercase_       )
       self.assertIsInstance(lowercase_,    lowercase_       )



   def  _UpperCAmelCase (				self       )							->    Tuple:






     """simple docstring"""






     with tempfile.TemporaryDirectory() as tmpdirname:
       a__  =Path(lowercase_       ) / '''preprocessor_config.json'''
       a__  =Path(lowercase_       ) / '''config.json'''
       json.dump(
           {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''},    open(lowercase_,    '''w'''       ),    )
       json.dump({'''model_type''': '''clip'''},    open(lowercase_,    '''w'''       )       )

       a__  =AutoImageProcessor.from_pretrained(lowercase_       )
       self.assertIsInstance(lowercase_,    lowercase_       )



   def  _UpperCAmelCase (				self       )							->    Optional[Any]:






     """simple docstring"""






     with tempfile.TemporaryDirectory() as tmpdirname:
       a__  =CLIPConfig()

       # Create a dummy config file with image_proceesor_type
       a__  =Path(lowercase_       ) / '''preprocessor_config.json'''
       a__  =Path(lowercase_       ) / '''config.json'''
       json.dump(
           {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''},    open(lowercase_,    '''w'''       ),    )
       json.dump({'''model_type''': '''clip'''},    open(lowercase_,    '''w'''       )       )

       # remove image_processor_type to make sure config.json alone is enough to load image processor locally
       a__  =AutoImageProcessor.from_pretrained(lowercase_       ).to_dict()

       config_dict.pop('''image_processor_type'''       )
       a__  =CLIPImageProcessor(**lowercase_       )

       # save in new folder
       model_config.save_pretrained(lowercase_       )
       config.save_pretrained(lowercase_       )

       a__  =AutoImageProcessor.from_pretrained(lowercase_       )

       # make sure private variable is not incorrectly saved
       a__  =json.loads(config.to_json_string()       )
       self.assertTrue('''_processor_class''' not in dict_as_saved       )

     self.assertIsInstance(lowercase_,    lowercase_       )



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






     """simple docstring"""






     with tempfile.TemporaryDirectory() as tmpdirname:
       a__  =Path(lowercase_       ) / '''preprocessor_config.json'''
       json.dump(
           {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''},    open(lowercase_,    '''w'''       ),    )

       a__  =AutoImageProcessor.from_pretrained(lowercase_       )
       self.assertIsInstance(lowercase_,    lowercase_       )



   def  _UpperCAmelCase (				self       )							->    Dict:






     """simple docstring"""






     with self.assertRaisesRegex(
         lowercase_,    '''clip-base is not a local folder and is not a valid model identifier'''       ):
       a__  =AutoImageProcessor.from_pretrained('''clip-base'''       )



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






     """simple docstring"""






     with self.assertRaisesRegex(
         lowercase_,    R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''       ):
       a__  =AutoImageProcessor.from_pretrained(lowercase_,    revision='''aaaaaa'''       )



   def  _UpperCAmelCase (				self       )							->    Tuple:






     """simple docstring"""






     with self.assertRaisesRegex(
         lowercase_,    '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''',    ):
       a__  =AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model'''       )



   def  _UpperCAmelCase (				self       )							->    Optional[Any]:






     """simple docstring"""






     with self.assertRaises(lowercase_       ):
       a__  =AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''       )
     # If remote code is disabled, we can't load this config.
     with self.assertRaises(lowercase_       ):
       a__  =AutoImageProcessor.from_pretrained(
           '''hf-internal-testing/test_dynamic_image_processor''',    trust_remote_code=lowercase_       )

     a__  =AutoImageProcessor.from_pretrained(
         '''hf-internal-testing/test_dynamic_image_processor''',    trust_remote_code=lowercase_       )
     self.assertEqual(image_processor.__class__.__name__,    '''NewImageProcessor'''       )

     # Test image processor can be reloaded.
     with tempfile.TemporaryDirectory() as tmp_dir:
       image_processor.save_pretrained(lowercase_       )
       a__  =AutoImageProcessor.from_pretrained(lowercase_,    trust_remote_code=lowercase_       )
     self.assertEqual(reloaded_image_processor.__class__.__name__,    '''NewImageProcessor'''       )



   def  _UpperCAmelCase (				self       )							->    int:






     """simple docstring"""






     try:
       AutoConfig.register('''custom''',    lowercase_       )
       AutoImageProcessor.register(lowercase_,    lowercase_       )
       # Trying to register something existing in the Transformers library will raise an error
       with self.assertRaises(lowercase_       ):
         AutoImageProcessor.register(lowercase_,    lowercase_       )

       with tempfile.TemporaryDirectory() as tmpdirname:
         a__  =Path(lowercase_       ) / '''preprocessor_config.json'''
         a__  =Path(lowercase_       ) / '''config.json'''
         json.dump(
             {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''},    open(lowercase_,    '''w'''       ),    )
         json.dump({'''model_type''': '''clip'''},    open(lowercase_,    '''w'''       )       )

         a__  =CustomImageProcessor.from_pretrained(lowercase_       )

       # Now that the config is registered, it can be used as any other config with the auto-API
       with tempfile.TemporaryDirectory() as tmp_dir:
         image_processor.save_pretrained(lowercase_       )
         a__  =AutoImageProcessor.from_pretrained(lowercase_       )
         self.assertIsInstance(lowercase_,    lowercase_       )

     finally:
       if "custom" in CONFIG_MAPPING._extra_content:
         del CONFIG_MAPPING._extra_content["custom"]
       if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
         del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]



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






     """simple docstring"""






     class 						__magic_name__			(							lowerCamelCase__							):

        '''simple docstring'''




        lowerCamelCase__ :	List[Any]    =   True

     try:
       AutoConfig.register('''custom''',    lowercase_       )
       AutoImageProcessor.register(lowercase_,    lowercase_       )
       # If remote code is not set, the default is to use local
       a__  =AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor'''       )
       self.assertEqual(image_processor.__class__.__name__,    '''NewImageProcessor'''       )
       self.assertTrue(image_processor.is_local       )

       # If remote code is disabled, we load the local one.
       a__  =AutoImageProcessor.from_pretrained(
           '''hf-internal-testing/test_dynamic_image_processor''',    trust_remote_code=lowercase_       )
       self.assertEqual(image_processor.__class__.__name__,    '''NewImageProcessor'''       )
       self.assertTrue(image_processor.is_local       )

       # If remote is enabled, we load from the Hub
       a__  =AutoImageProcessor.from_pretrained(
           '''hf-internal-testing/test_dynamic_image_processor''',    trust_remote_code=lowercase_       )
       self.assertEqual(image_processor.__class__.__name__,    '''NewImageProcessor'''       )
       self.assertTrue(not hasattr(lowercase_,    '''is_local'''       )       )

     finally:
       if "custom" in CONFIG_MAPPING._extra_content:
         del CONFIG_MAPPING._extra_content["custom"]
       if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
         del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]



from typing import TYPE_CHECKING

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


lowerCamelCase           =					{
    '''configuration_deberta''': ['''DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DebertaConfig''', '''DebertaOnnxConfig'''],
    '''tokenization_deberta''': ['''DebertaTokenizer'''],
}

try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCamelCase           =					['''DebertaTokenizerFast''']

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCamelCase           =					[
           '''DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''',
           '''DebertaForMaskedLM''',
           '''DebertaForQuestionAnswering''',
           '''DebertaForSequenceClassification''',
           '''DebertaForTokenClassification''',
           '''DebertaModel''',
           '''DebertaPreTrainedModel''',
       ]

try:
       if not is_tf_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCamelCase           =					[
           '''TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''',
           '''TFDebertaForMaskedLM''',
           '''TFDebertaForQuestionAnswering''',
           '''TFDebertaForSequenceClassification''',
           '''TFDebertaForTokenClassification''',
           '''TFDebertaModel''',
           '''TFDebertaPreTrainedModel''',
       ]


if TYPE_CHECKING:
       from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig
       from .tokenization_deberta import DebertaTokenizer

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_deberta_fast import DebertaTokenizerFast

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_deberta import (
                  DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
                  DebertaForMaskedLM,
                  DebertaForQuestionAnswering,
                  DebertaForSequenceClassification,
                  DebertaForTokenClassification,
                  DebertaModel,
                  DebertaPreTrainedModel,
              )

       try:
              if not is_tf_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_tf_deberta import (
                  TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST,
                  TFDebertaForMaskedLM,
                  TFDebertaForQuestionAnswering,
                  TFDebertaForSequenceClassification,
                  TFDebertaForTokenClassification,
                  TFDebertaModel,
                  TFDebertaPreTrainedModel,
              )


else:
       import sys

       lowerCamelCase           =					_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
