


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 				lowerCamelCase_			(							self:     Dict							)      ->       int:





									"""simple docstring"""







									lowercase__						=				0

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





									"""simple docstring"""







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

							def 				lowerCamelCase_			(							self:     List[str]							)      ->       Optional[int]:





									"""simple docstring"""







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

											lowercase__						=				AutoImageProcessor.from_pretrained(__lowercase							)
											self.assertIsInstance(__lowercase   ,						__lowercase							)

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





									"""simple docstring"""







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

											lowercase__						=				AutoImageProcessor.from_pretrained(__lowercase							)
											self.assertIsInstance(__lowercase   ,						__lowercase							)

							def 				lowerCamelCase_			(							self:     List[str]							)      ->       Optional[int]:





									"""simple docstring"""







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

											# Create a dummy config file with image_proceesor_type
											lowercase__						=				Path(__lowercase							) / '''preprocessor_config.json'''
											lowercase__						=				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
											lowercase__						=				AutoImageProcessor.from_pretrained(__lowercase							).to_dict()

											config_dict.pop('''image_processor_type'''							)
											lowercase__						=				CLIPImageProcessor(**__lowercase							)

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

											lowercase__						=				AutoImageProcessor.from_pretrained(__lowercase							)

											# 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(__lowercase   ,						__lowercase							)

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





									"""simple docstring"""







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

											lowercase__						=				AutoImageProcessor.from_pretrained(__lowercase							)
											self.assertIsInstance(__lowercase   ,						__lowercase							)

							def 				lowerCamelCase_			(							self:     Tuple							)      ->       Optional[int]:





									"""simple docstring"""







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

							def 				lowerCamelCase_			(							self:     str							)      ->       List[Any]:





									"""simple docstring"""







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

							def 				lowerCamelCase_			(							self:     int							)      ->       List[str]:





									"""simple docstring"""







									with self.assertRaisesRegex(
									    __lowercase   ,						'''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 				lowerCamelCase_			(							self:     Optional[Any]							)      ->       str:





									"""simple docstring"""







									with self.assertRaises(__lowercase							):
											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(__lowercase							):
											lowercase__						=				AutoImageProcessor.from_pretrained(
											    '''hf-internal-testing/test_dynamic_image_processor'''   ,						trust_remote_code=__lowercase							)

									lowercase__						=				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							)
											lowercase__						=				AutoImageProcessor.from_pretrained(__lowercase   ,						trust_remote_code=__lowercase							)
									self.assertEqual(reloaded_image_processor.__class__.__name__   ,						'''NewImageProcessor'''							)

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





									"""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:
													lowercase__						=				Path(__lowercase							) / '''preprocessor_config.json'''
													lowercase__						=				Path(__lowercase							) / '''config.json'''
													json.dump(
													    {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''}   ,						open(__lowercase   ,						'''w'''							)   ,						)
													json.dump({'''model_type''': '''clip'''}   ,						open(__lowercase   ,						'''w'''							)							)

													lowercase__						=				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							)
													lowercase__						=				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 				lowerCamelCase_			(							self:     Any							)      ->       List[Any]:





									"""simple docstring"""







									class 	_a							(      UpperCAmelCase_      ):
																_lowercase     :      List[str]  				=			True

									try:
											AutoConfig.register('''custom'''   ,						__lowercase							)
											AutoImageProcessor.register(__lowercase   ,						__lowercase							)
											# 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=__lowercase							)
											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=__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 ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase	=							logging.get_logger(__name__)

lowerCAmelCase	=							{
    'unc-nlp/lxmert-base-uncased': 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json',
}


class 	_a							(      UpperCamelCase__      ):
							_lowercase     :      List[Any]  				=			'''lxmert'''
							_lowercase     :      Any  				=			{}

							def __init__(							self:     Any   ,						UpperCamelCase_:     List[Any]=30_522   ,						UpperCamelCase_:     int=768   ,						UpperCamelCase_:     Optional[Any]=12   ,						UpperCamelCase_:     Dict=9_500   ,						UpperCamelCase_:     List[Any]=1_600   ,						UpperCamelCase_:     List[Any]=400   ,						UpperCamelCase_:     List[str]=3_072   ,						UpperCamelCase_:     int="gelu"   ,						UpperCamelCase_:     Any=0.1   ,						UpperCamelCase_:     int=0.1   ,						UpperCamelCase_:     List[str]=512   ,						UpperCamelCase_:     Optional[int]=2   ,						UpperCamelCase_:     Union[str, Any]=0.02   ,						UpperCamelCase_:     Dict=1E-1_2   ,						UpperCamelCase_:     List[Any]=9   ,						UpperCamelCase_:     List[Any]=5   ,						UpperCamelCase_:     Optional[Any]=5   ,						UpperCamelCase_:     str=2_048   ,						UpperCamelCase_:     Dict=4   ,						UpperCamelCase_:     Any=6.67   ,						UpperCamelCase_:     Dict=True   ,						UpperCamelCase_:     List[str]=True   ,						UpperCamelCase_:     Dict=True   ,						UpperCamelCase_:     Any=True   ,						UpperCamelCase_:     Tuple=True   ,						UpperCamelCase_:     Optional[Any]=True   ,						UpperCamelCase_:     Any=True   ,						**UpperCamelCase_:     Union[str, Any]   ,						)      ->       Union[str, Any]:





									"""simple docstring"""







									lowercase__						=				vocab_size
									lowercase__						=				hidden_size
									lowercase__						=				num_attention_heads
									lowercase__						=				hidden_act
									lowercase__						=				intermediate_size
									lowercase__						=				hidden_dropout_prob
									lowercase__						=				attention_probs_dropout_prob
									lowercase__						=				max_position_embeddings
									lowercase__						=				type_vocab_size
									lowercase__						=				initializer_range
									lowercase__						=				layer_norm_eps
									lowercase__						=				num_qa_labels
									lowercase__						=				num_object_labels
									lowercase__						=				num_attr_labels
									lowercase__						=				l_layers
									lowercase__						=				x_layers
									lowercase__						=				r_layers
									lowercase__						=				visual_feat_dim
									lowercase__						=				visual_pos_dim
									lowercase__						=				visual_loss_normalizer
									lowercase__						=				task_matched
									lowercase__						=				task_mask_lm
									lowercase__						=				task_obj_predict
									lowercase__						=				task_qa
									lowercase__						=				visual_obj_loss
									lowercase__						=				visual_attr_loss
									lowercase__						=				visual_feat_loss
									lowercase__						=				{'''vision''': r_layers, '''cross_encoder''': x_layers, '''language''': l_layers}
									super().__init__(**UpperCamelCase_							)


