


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 		__a				(    unittest.TestCase      ):
		def      UpperCAmelCase__    (      self						)			->	List[str]:




									"""simple docstring"""





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




									"""simple docstring"""





									_UpperCAmelCase					=      AutoImageProcessor.from_pretrained('openai/clip-vit-base-patch32'						)
									self.assertIsInstance(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE						)
		def      UpperCAmelCase__    (      self						)			->	Dict:




									"""simple docstring"""





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

																_UpperCAmelCase					=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE						)
																self.assertIsInstance(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE						)
		def      UpperCAmelCase__    (      self						)			->	Any:




									"""simple docstring"""





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

																_UpperCAmelCase					=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE						)
																self.assertIsInstance(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE						)
		def      UpperCAmelCase__    (      self						)			->	Dict:




									"""simple docstring"""





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

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

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

																config_dict.pop('image_processor_type'						)
																_UpperCAmelCase					=      CLIPImageProcessor(**_SCREAMING_SNAKE_CASE						)

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

																_UpperCAmelCase					=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE						)

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

									self.assertIsInstance(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE						)
		def      UpperCAmelCase__    (      self						)			->	List[Any]:




									"""simple docstring"""





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

																_UpperCAmelCase					=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE						)
																self.assertIsInstance(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE						)
		def      UpperCAmelCase__    (      self						)			->	List[Any]:




									"""simple docstring"""





									with self.assertRaisesRegex(
									    _SCREAMING_SNAKE_CASE      ,   'clip-base is not a local folder and is not a valid model identifier'						):
																_UpperCAmelCase					=      AutoImageProcessor.from_pretrained('clip-base'						)
		def      UpperCAmelCase__    (      self						)			->	Dict:




									"""simple docstring"""





									with self.assertRaisesRegex(
									    _SCREAMING_SNAKE_CASE      ,   R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'						):
																_UpperCAmelCase					=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE      ,   revision='aaaaaa'						)
		def      UpperCAmelCase__    (      self						)			->	str:




									"""simple docstring"""





									with self.assertRaisesRegex(
									    _SCREAMING_SNAKE_CASE      ,   'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.'      ,   ):
																_UpperCAmelCase					=      AutoImageProcessor.from_pretrained('hf-internal-testing/config-no-model'						)
		def      UpperCAmelCase__    (      self						)			->	Union[str, Any]:




									"""simple docstring"""





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

									_UpperCAmelCase					=      AutoImageProcessor.from_pretrained(
									    'hf-internal-testing/test_dynamic_image_processor'      ,   trust_remote_code=_SCREAMING_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(_SCREAMING_SNAKE_CASE						)
																_UpperCAmelCase					=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE      ,   trust_remote_code=_SCREAMING_SNAKE_CASE						)
									self.assertEqual(reloaded_image_processor.__class__.__name__      ,   'NewImageProcessor'						)
		def      UpperCAmelCase__    (      self						)			->	Tuple:




									"""simple docstring"""





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

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

																							_UpperCAmelCase					=      CustomImageProcessor.from_pretrained(_SCREAMING_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(_SCREAMING_SNAKE_CASE						)
																							_UpperCAmelCase					=      AutoImageProcessor.from_pretrained(_SCREAMING_SNAKE_CASE						)
																							self.assertIsInstance(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_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 		__a				(    UpperCAmelCase      ):
											_a     :  int           =     True

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

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




from importlib import import_module

from .logging import get_logger


lowerCAmelCase__  :Optional[Any]             =							get_logger(__name__)

class 		__a				:
		def __init__(      self      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE=None						)			->	List[Any]:




									"""simple docstring"""





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



class 		__a				:
		_a     :  Any           =     []
		def __init__(      self      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE=None						)			->	Union[str, Any]:




									"""simple docstring"""





									_UpperCAmelCase					=      obj
									_UpperCAmelCase					=      target
									_UpperCAmelCase					=      new
									_UpperCAmelCase					=      target.split('.'						)[0]
									_UpperCAmelCase					=      {}
									_UpperCAmelCase					=      attrs or []
		def __enter__(      self						)			->	int:




									"""simple docstring"""





									*_UpperCAmelCase		,	_UpperCAmelCase					=      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(_SCREAMING_SNAKE_CASE						)						):
																try:
																							_UpperCAmelCase					=      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__():
																							_UpperCAmelCase					=      getattr(self.obj      ,   _SCREAMING_SNAKE_CASE						)
																							# 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(_SCREAMING_SNAKE_CASE      ,   _PatchedModuleObj						) and obj_attr._original_module is submodule)
																							):
																														_UpperCAmelCase					=      obj_attr
																														# patch at top level
																														setattr(self.obj      ,   _SCREAMING_SNAKE_CASE      ,   _PatchedModuleObj(_SCREAMING_SNAKE_CASE      ,   attrs=self.attrs						)						)
																														_UpperCAmelCase					=      getattr(self.obj      ,   _SCREAMING_SNAKE_CASE						)
																														# construct lower levels patches
																														for key in submodules[i + 1 :]:
																																					setattr(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   _PatchedModuleObj(getattr(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE						)      ,   attrs=self.attrs						)						)
																																					_UpperCAmelCase					=      getattr(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE						)
																														# finally set the target attribute
																														setattr(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   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:
																							_UpperCAmelCase					=      getattr(import_module('.'.join(_SCREAMING_SNAKE_CASE						)						)      ,   _SCREAMING_SNAKE_CASE						)
																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      ,   _SCREAMING_SNAKE_CASE						) is attr_value:
																														_UpperCAmelCase					=      getattr(self.obj      ,   _SCREAMING_SNAKE_CASE						)
																														setattr(self.obj      ,   _SCREAMING_SNAKE_CASE      ,   self.new						)
									elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
																_UpperCAmelCase					=      globals()['__builtins__'][target_attr]
																setattr(self.obj      ,   _SCREAMING_SNAKE_CASE      ,   self.new						)
									else:
																raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.'''						)
		def __exit__(      self      ,   *_SCREAMING_SNAKE_CASE						)			->	Union[str, Any]:




									"""simple docstring"""





									for attr in list(self.original						):
																setattr(self.obj      ,   _SCREAMING_SNAKE_CASE      ,   self.original.pop(_SCREAMING_SNAKE_CASE						)						)
		def      UpperCAmelCase__    (      self						)			->	Optional[int]:




									"""simple docstring"""





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






		def      UpperCAmelCase__    (      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__()
