






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 						lowerCAmelCase   (       unittest.TestCase	):

					'''simple docstring'''

					def 					lowerCAmelCase (     self :		List[Any]							)	->     Optional[Any]:


												"""simple docstring"""

												__lowercase					:							Dict			=   0



					def 					lowerCAmelCase (     self :		Dict							)	->     Optional[int]:


												"""simple docstring"""

												__lowercase					:							str			=   AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32"""							)
												self.assertIsInstance(UpperCamelCase__						,   UpperCamelCase__							)



					def 					lowerCAmelCase (     self :		Dict							)	->     Optional[int]:


												"""simple docstring"""

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

																			__lowercase					:							Any			=   AutoImageProcessor.from_pretrained(UpperCamelCase__							)
																			self.assertIsInstance(UpperCamelCase__						,   UpperCamelCase__							)



					def 					lowerCAmelCase (     self :		int							)	->     Optional[Any]:


												"""simple docstring"""

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

																			__lowercase					:							Optional[Any]			=   AutoImageProcessor.from_pretrained(UpperCamelCase__							)
																			self.assertIsInstance(UpperCamelCase__						,   UpperCamelCase__							)



					def 					lowerCAmelCase (     self :		List[str]							)	->     Dict:


												"""simple docstring"""

												with tempfile.TemporaryDirectory() as tmpdirname:
																			__lowercase					:							Dict			=   CLIPConfig()

																			# Create a dummy config file with image_proceesor_type
																			__lowercase					:							Dict			=   Path(UpperCamelCase__							) / '''preprocessor_config.json'''
																			__lowercase					:							List[str]			=   Path(UpperCamelCase__							) / '''config.json'''
																			json.dump(
																			    {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""}						,   open(UpperCamelCase__						,   """w"""							)						,   )
																			json.dump({"""model_type""": """clip"""}						,   open(UpperCamelCase__						,   """w"""							)							)

																			# remove image_processor_type to make sure config.json alone is enough to load image processor locally
																			__lowercase					:							List[Any]			=   AutoImageProcessor.from_pretrained(UpperCamelCase__							).to_dict()

																			config_dict.pop("""image_processor_type"""							)
																			__lowercase					:							str			=   CLIPImageProcessor(**UpperCamelCase__							)

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

																			__lowercase					:							Union[str, Any]			=   AutoImageProcessor.from_pretrained(UpperCamelCase__							)

																			# make sure private variable is not incorrectly saved
																			__lowercase					:							List[Any]			=   json.loads(config.to_json_string()							)
																			self.assertTrue("""_processor_class""" not in dict_as_saved							)

												self.assertIsInstance(UpperCamelCase__						,   UpperCamelCase__							)



					def 					lowerCAmelCase (     self :		Tuple							)	->     Union[str, Any]:


												"""simple docstring"""

												with tempfile.TemporaryDirectory() as tmpdirname:
																			__lowercase					:							Optional[int]			=   Path(UpperCamelCase__							) / '''preprocessor_config.json'''
																			json.dump(
																			    {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""}						,   open(UpperCamelCase__						,   """w"""							)						,   )

																			__lowercase					:							Dict			=   AutoImageProcessor.from_pretrained(UpperCamelCase__							)
																			self.assertIsInstance(UpperCamelCase__						,   UpperCamelCase__							)



					def 					lowerCAmelCase (     self :		int							)	->     Tuple:


												"""simple docstring"""

												with self.assertRaisesRegex(
												    UpperCamelCase__						,   """clip-base is not a local folder and is not a valid model identifier"""							):
																			__lowercase					:							List[str]			=   AutoImageProcessor.from_pretrained("""clip-base"""							)



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


												"""simple docstring"""

												with self.assertRaisesRegex(
												    UpperCamelCase__						,   r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""							):
																			__lowercase					:							Tuple			=   AutoImageProcessor.from_pretrained(UpperCamelCase__						,   revision="""aaaaaa"""							)



					def 					lowerCAmelCase (     self :		Dict							)	->     List[Any]:


												"""simple docstring"""

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



					def 					lowerCAmelCase (     self :		List[Any]							)	->     Optional[Any]:


												"""simple docstring"""

												with self.assertRaises(UpperCamelCase__							):
																			__lowercase					:							str			=   AutoImageProcessor.from_pretrained("""hf-internal-testing/test_dynamic_image_processor"""							)
												# If remote code is disabled, we can't load this config.
												with self.assertRaises(UpperCamelCase__							):
																			__lowercase					:							List[Any]			=   AutoImageProcessor.from_pretrained(
																			    """hf-internal-testing/test_dynamic_image_processor"""						,   trust_remote_code=UpperCamelCase__							)

												__lowercase					:							List[Any]			=   AutoImageProcessor.from_pretrained(
												    """hf-internal-testing/test_dynamic_image_processor"""						,   trust_remote_code=UpperCamelCase__							)
												self.assertEqual(image_processor.__class__.__name__						,   """NewImageProcessor"""							)

												# Test image processor can be reloaded.
												with tempfile.TemporaryDirectory() as tmp_dir:
																			image_processor.save_pretrained(UpperCamelCase__							)
																			__lowercase					:							Optional[int]			=   AutoImageProcessor.from_pretrained(UpperCamelCase__						,   trust_remote_code=UpperCamelCase__							)
												self.assertEqual(reloaded_image_processor.__class__.__name__						,   """NewImageProcessor"""							)



					def 					lowerCAmelCase (     self :		Optional[Any]							)	->     Union[str, Any]:


												"""simple docstring"""

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

																			with tempfile.TemporaryDirectory() as tmpdirname:
																										__lowercase					:							Union[str, Any]			=   Path(UpperCamelCase__							) / '''preprocessor_config.json'''
																										__lowercase					:							Any			=   Path(UpperCamelCase__							) / '''config.json'''
																										json.dump(
																										    {"""feature_extractor_type""": """CLIPFeatureExtractor""", """processor_class""": """CLIPProcessor"""}						,   open(UpperCamelCase__						,   """w"""							)						,   )
																										json.dump({"""model_type""": """clip"""}						,   open(UpperCamelCase__						,   """w"""							)							)

																										__lowercase					:							Tuple			=   CustomImageProcessor.from_pretrained(UpperCamelCase__							)

																			# 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(UpperCamelCase__							)
																										__lowercase					:							Any			=   AutoImageProcessor.from_pretrained(UpperCamelCase__							)
																										self.assertIsInstance(UpperCamelCase__						,   UpperCamelCase__							)

												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 					lowerCAmelCase (     self :		Any							)	->     str:


												"""simple docstring"""

												class 						lowerCAmelCase   (       UpperCamelCase_	):

																	'''simple docstring'''

																	_A  :	Any     =					True

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

																			# If remote is enabled, we load from the Hub
																			__lowercase					:							Optional[Any]			=   AutoImageProcessor.from_pretrained(
																			    """hf-internal-testing/test_dynamic_image_processor"""						,   trust_remote_code=UpperCamelCase__							)
																			self.assertEqual(image_processor.__class__.__name__						,   """NewImageProcessor"""							)
																			self.assertTrue(not hasattr(UpperCamelCase__						,   """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 packaging import version

from .import_utils import is_accelerate_available


if is_accelerate_available():
					import accelerate
def       A	(    _lowercase						):
						if not is_accelerate_available():
												return method
						SCREAMING_SNAKE_CASE							:    int							=							version.parse(accelerate.__version__						).base_version
						if version.parse(_lowercase						) < version.parse('''0.17.0'''						):
												return method

						def wrapper(self		,  *_lowercase		,  **_lowercase						):
												if hasattr(self		,  '''_hf_hook'''						) and hasattr(self._hf_hook		,  '''pre_forward'''						):
																		self._hf_hook.pre_forward(self						)
												return method(self		,  *_lowercase		,  **_lowercase						)

						return wrapper





