




from importlib import import_module

from .logging import get_logger


__UpperCamelCase   :			Union[str, Any]          = get_logger(__name__)

class 						__lowerCAmelCase      :
							def __init__(		self		:Any						, __magic_name__		:str						, __magic_name__		:Tuple=None							):







								'''simple docstring'''







								a									=				attrs or []
								if module is not None:
									for key in module.__dict__:
										if key in attrs or not key.startswith("""__"""							):
											setattr(self						, __magic_name__						, getattr(__magic_name__						, __magic_name__							)							)
								a									=				module._original_module if isinstance(__magic_name__						, _PatchedModuleObj							) else module







class 						__lowerCAmelCase      :
							UpperCamelCase__   	=    []
							def __init__(		self		:Tuple						, __magic_name__		:int						, __magic_name__		:str						, __magic_name__		:Optional[int]						, __magic_name__		:Optional[int]=None							):







								'''simple docstring'''







								a									=				obj
								a									=				target
								a									=				new
								a									=				target.split("""."""							)[0]
								a									=				{}
								a									=				attrs or []
							def __enter__(		self		:List[Any]							):







								'''simple docstring'''







								*a							,					a									=				self.target.split("""."""							)

								# Patch modules:
								# it's used to patch attributes of submodules like "os.path.join";
								# in this case we need to patch "os" and "os.path"

								for i in range(len(__magic_name__							)							):
									try:
										a									=				import_module(""".""".join(submodules[: i + 1]							)							)
									except ModuleNotFoundError:
										continue
									# We iterate over all the globals in self.obj in case we find "os" or "os.path"
									for attr in self.obj.__dir__():
										a									=				getattr(self.obj						, __magic_name__							)
										# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
										# This allows to patch renamed modules like "from os import path as ospath".
										if obj_attr is submodule or (
										    (isinstance(__magic_name__						, _PatchedModuleObj							) and obj_attr._original_module is submodule)
										):
											a									=				obj_attr
											# patch at top level
											setattr(self.obj						, __magic_name__						, _PatchedModuleObj(__magic_name__						, attrs=self.attrs							)							)
											a									=				getattr(self.obj						, __magic_name__							)
											# construct lower levels patches
											for key in submodules[i + 1 :]:
												setattr(__magic_name__						, __magic_name__						, _PatchedModuleObj(getattr(__magic_name__						, __magic_name__						, __magic_name__							)						, attrs=self.attrs							)							)
												a									=				getattr(__magic_name__						, __magic_name__							)
											# finally set the target attribute
											setattr(__magic_name__						, __magic_name__						, self.new							)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

								if submodules:  # if it's an attribute of a submodule like "os.path.join"
									try:
										a									=				getattr(import_module(""".""".join(__magic_name__							)							)						, __magic_name__							)
									except (AttributeError, ModuleNotFoundError):
										return
									# We iterate over all the globals in self.obj in case we find "os.path.join"
									for attr in self.obj.__dir__():
										# We don't check for the name of the global, but rather if its value *is* "os.path.join".
										# This allows to patch renamed attributes like "from os.path import join as pjoin".
										if getattr(self.obj						, __magic_name__							) is attr_value:
											a									=				getattr(self.obj						, __magic_name__							)
											setattr(self.obj						, __magic_name__						, self.new							)
								elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
									a									=				globals()["""__builtins__"""][target_attr]
									setattr(self.obj						, __magic_name__						, self.new							)
								else:
									raise RuntimeError(F'Tried to patch attribute {target_attr} instead of a submodule.'							)
							def __exit__(		self		:List[Any]						, *__magic_name__		:Optional[int]							):







								'''simple docstring'''







								for attr in list(self.original							):
									setattr(self.obj						, __magic_name__						, self.original.pop(__magic_name__							)							)
							def  lowerCamelCase__				(		self		:Optional[int]							):







								'''simple docstring'''







								self.__enter__()
								self._active_patches.append(self							)





							def  lowerCamelCase__				(		self		:str							):







								'''simple docstring'''







								try:
									self._active_patches.remove(self							)
								except ValueError:
									# If the patch hasn't been started this will fail
									return None

								return self.__exit__()









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 					SCREAMING_SNAKE_CASE_  (       unittest.TestCase ):
       """simple docstring"""


       def 				UpperCamelCase__						(				self	:Any):



          """simple docstring"""

          _lowercase              =0





       def 				UpperCamelCase__						(				self	:Optional[int]):



          """simple docstring"""

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





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



          """simple docstring"""

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

             _lowercase              =AutoImageProcessor.from_pretrained(snake_case)
             self.assertIsInstance(snake_case,      snake_case)





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



          """simple docstring"""

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

             _lowercase              =AutoImageProcessor.from_pretrained(snake_case)
             self.assertIsInstance(snake_case,      snake_case)





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



          """simple docstring"""

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

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

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

             config_dict.pop('image_processor_type')
             _lowercase              =CLIPImageProcessor(**snake_case)

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

             _lowercase              =AutoImageProcessor.from_pretrained(snake_case)

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

          self.assertIsInstance(snake_case,      snake_case)





       def 				UpperCamelCase__						(				self	:Optional[int]):



          """simple docstring"""

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

             _lowercase              =AutoImageProcessor.from_pretrained(snake_case)
             self.assertIsInstance(snake_case,      snake_case)





       def 				UpperCamelCase__						(				self	:int):



          """simple docstring"""

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





       def 				UpperCamelCase__						(				self	:Dict):



          """simple docstring"""

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





       def 				UpperCamelCase__						(				self	:List[Any]):



          """simple docstring"""

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





       def 				UpperCamelCase__						(				self	:Optional[Any]):



          """simple docstring"""

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

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

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





       def 				UpperCamelCase__						(				self	:Optional[Any]):



          """simple docstring"""

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

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

                _lowercase              =CustomImageProcessor.from_pretrained(snake_case)

             # 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(snake_case)
                _lowercase              =AutoImageProcessor.from_pretrained(snake_case)
                self.assertIsInstance(snake_case,      snake_case)

          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	:str):



          """simple docstring"""

          class 					SCREAMING_SNAKE_CASE_  (       _a ):
                 """simple docstring"""


                 __lowerCAmelCase    :		Union[str, Any]					=True

          try:
             AutoConfig.register('custom',      snake_case)
             AutoImageProcessor.register(snake_case,      snake_case)
             # If remote code is not set, the default is to use local
             _lowercase              =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.
             _lowercase              =AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_image_processor',      trust_remote_code=snake_case)
             self.assertEqual(image_processor.__class__.__name__,      'NewImageProcessor')
             self.assertTrue(image_processor.is_local)

             # If remote is enabled, we load from the Hub
             _lowercase              =AutoImageProcessor.from_pretrained(
                 'hf-internal-testing/test_dynamic_image_processor',      trust_remote_code=snake_case)
             self.assertEqual(image_processor.__class__.__name__,      'NewImageProcessor')
             self.assertTrue(not hasattr(snake_case,      '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]


