"""simple docstring"""




import copy
import os
from typing import TYPE_CHECKING, List, Union


if TYPE_CHECKING:
			pass

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCAmelCase    :							Optional[Any]													=						logging.get_logger(__name__)

__lowerCAmelCase    :							List[Any]													=						{
    "kakaobrain/align-base": "https://huggingface.co/kakaobrain/align-base/resolve/main/config.json",
}

class       a_      (     __UpperCamelCase			):
					UpperCamelCase_ :	Optional[int]			=    "align_text_model"




					def __init__(	self						:     Optional[Any]  ,						snake_case__						:     Optional[Any]=30522  ,						snake_case__						:     Tuple=768  ,						snake_case__						:     Union[str, Any]=12  ,						snake_case__						:     Tuple=12  ,						snake_case__						:     Dict=3072  ,						snake_case__						:     int="gelu"  ,						snake_case__						:     Tuple=0.1  ,						snake_case__						:     Any=0.1  ,						snake_case__						:     List[Any]=512  ,						snake_case__						:     str=2  ,						snake_case__						:     List[str]=0.02  ,						snake_case__						:     Tuple=1E-12  ,						snake_case__						:     Dict=0  ,						snake_case__						:     str="absolute"  ,						snake_case__						:     str=True  ,						**snake_case__						:     Dict  ,						):
							super().__init__(**snake_case__     )

							lowerCAmelCase__        =   vocab_size
							lowerCAmelCase__        =   hidden_size
							lowerCAmelCase__        =   num_hidden_layers
							lowerCAmelCase__        =   num_attention_heads
							lowerCAmelCase__        =   hidden_act
							lowerCAmelCase__        =   intermediate_size
							lowerCAmelCase__        =   hidden_dropout_prob
							lowerCAmelCase__        =   attention_probs_dropout_prob
							lowerCAmelCase__        =   max_position_embeddings
							lowerCAmelCase__        =   type_vocab_size
							lowerCAmelCase__        =   initializer_range
							lowerCAmelCase__        =   layer_norm_eps
							lowerCAmelCase__        =   position_embedding_type
							lowerCAmelCase__        =   use_cache
							lowerCAmelCase__        =   pad_token_id




					@classmethod
					def 						_SCREAMING_SNAKE_CASE						(	cls						:     Dict  ,						snake_case__						:     Union[str, os.PathLike]  ,						**snake_case__						:     Tuple     ):
							cls._set_token_in_kwargs(snake_case__     )

							lowerCAmelCase__   ,					lowerCAmelCase__        =   cls.get_config_dict(snake_case__  ,						**snake_case__     )

							# get the text config dict if we are loading from AlignConfig
							if config_dict.get("""model_type"""     ) == "align":
									lowerCAmelCase__        =   config_dict["""text_config"""]

							if "model_type" in config_dict and hasattr(cls  ,						"""model_type"""     ) and config_dict["model_type"] != cls.model_type:
									logger.warning(
									    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
									    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""     )

							return cls.from_dict(snake_case__  ,						**snake_case__     )

class       a_      (     __UpperCamelCase			):
					UpperCamelCase_ :	Any			=    "align_vision_model"




					def __init__(	self						:     Tuple  ,						snake_case__						:     int = 3  ,						snake_case__						:     int = 600  ,						snake_case__						:     float = 2.0  ,						snake_case__						:     float = 3.1  ,						snake_case__						:     int = 8  ,						snake_case__						:     List[int] = [3, 3, 5, 3, 5, 5, 3]  ,						snake_case__						:     List[int] = [32, 16, 24, 40, 80, 112, 192]  ,						snake_case__						:     List[int] = [16, 24, 40, 80, 112, 192, 320]  ,						snake_case__						:     List[int] = []  ,						snake_case__						:     List[int] = [1, 2, 2, 2, 1, 2, 1]  ,						snake_case__						:     List[int] = [1, 2, 2, 3, 3, 4, 1]  ,						snake_case__						:     List[int] = [1, 6, 6, 6, 6, 6, 6]  ,						snake_case__						:     float = 0.25  ,						snake_case__						:     str = "swish"  ,						snake_case__						:     int = 2560  ,						snake_case__						:     str = "mean"  ,						snake_case__						:     float = 0.02  ,						snake_case__						:     float = 0.001  ,						snake_case__						:     float = 0.99  ,						snake_case__						:     float = 0.2  ,						**snake_case__						:     Union[str, Any]  ,						):
							super().__init__(**snake_case__     )

							lowerCAmelCase__        =   num_channels
							lowerCAmelCase__        =   image_size
							lowerCAmelCase__        =   width_coefficient
							lowerCAmelCase__        =   depth_coefficient
							lowerCAmelCase__        =   depth_divisor
							lowerCAmelCase__        =   kernel_sizes
							lowerCAmelCase__        =   in_channels
							lowerCAmelCase__        =   out_channels
							lowerCAmelCase__        =   depthwise_padding
							lowerCAmelCase__        =   strides
							lowerCAmelCase__        =   num_block_repeats
							lowerCAmelCase__        =   expand_ratios
							lowerCAmelCase__        =   squeeze_expansion_ratio
							lowerCAmelCase__        =   hidden_act
							lowerCAmelCase__        =   hidden_dim
							lowerCAmelCase__        =   pooling_type
							lowerCAmelCase__        =   initializer_range
							lowerCAmelCase__        =   batch_norm_eps
							lowerCAmelCase__        =   batch_norm_momentum
							lowerCAmelCase__        =   drop_connect_rate
							lowerCAmelCase__        =   sum(snake_case__     ) * 4




					@classmethod
					def 						_SCREAMING_SNAKE_CASE						(	cls						:     int  ,						snake_case__						:     Union[str, os.PathLike]  ,						**snake_case__						:     Optional[Any]     ):
							cls._set_token_in_kwargs(snake_case__     )

							lowerCAmelCase__   ,					lowerCAmelCase__        =   cls.get_config_dict(snake_case__  ,						**snake_case__     )

							# get the vision config dict if we are loading from AlignConfig
							if config_dict.get("""model_type"""     ) == "align":
									lowerCAmelCase__        =   config_dict["""vision_config"""]

							if "model_type" in config_dict and hasattr(cls  ,						"""model_type"""     ) and config_dict["model_type"] != cls.model_type:
									logger.warning(
									    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
									    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""     )

							return cls.from_dict(snake_case__  ,						**snake_case__     )

class       a_      (     __UpperCamelCase			):
					UpperCamelCase_ :	int			=    "align"
					UpperCamelCase_ :	Any			=    True




					def __init__(	self						:     Union[str, Any]  ,						snake_case__						:     Dict=None  ,						snake_case__						:     List[Any]=None  ,						snake_case__						:     Union[str, Any]=640  ,						snake_case__						:     Optional[Any]=1.0  ,						snake_case__						:     Any=0.02  ,						**snake_case__						:     Any  ,						):
							super().__init__(**snake_case__     )

							if text_config is None:
									lowerCAmelCase__        =   {}
									logger.info("""text_config is None. Initializing the AlignTextConfig with default values."""     )

							if vision_config is None:
									lowerCAmelCase__        =   {}
									logger.info("""vision_config is None. Initializing the AlignVisionConfig with default values."""     )

							lowerCAmelCase__        =   AlignTextConfig(**snake_case__     )
							lowerCAmelCase__        =   AlignVisionConfig(**snake_case__     )

							lowerCAmelCase__        =   projection_dim
							lowerCAmelCase__        =   temperature_init_value
							lowerCAmelCase__        =   initializer_range




					@classmethod
					def 						_SCREAMING_SNAKE_CASE						(	cls						:     Union[str, Any]  ,						snake_case__						:     AlignTextConfig  ,						snake_case__						:     AlignVisionConfig  ,						**snake_case__						:     List[str]     ):
							return cls(text_config=text_config.to_dict()  ,						vision_config=vision_config.to_dict()  ,						**snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Tuple     ):
							lowerCAmelCase__        =   copy.deepcopy(self.__dict__     )
							lowerCAmelCase__        =   self.text_config.to_dict()
							lowerCAmelCase__        =   self.vision_config.to_dict()
							lowerCAmelCase__        =   self.__class__.model_type
							return output





"""simple docstring"""




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 						_SCREAMING_SNAKE_CASE						(	self						:     Optional[int]     ):
							lowerCAmelCase__        =   0




					def 						_SCREAMING_SNAKE_CASE						(	self						:     List[Any]     ):
							lowerCAmelCase__        =   AutoImageProcessor.from_pretrained("""openai/clip-vit-base-patch32"""     )
							self.assertIsInstance(snake_case__  ,						snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Tuple     ):
							with tempfile.TemporaryDirectory() as tmpdirname:
									lowerCAmelCase__        =   Path(snake_case__     ) / """preprocessor_config.json"""
									lowerCAmelCase__        =   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"""     )     )

									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__     )
									self.assertIsInstance(snake_case__  ,						snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Union[str, Any]     ):
							# Ensure we can load the image processor from the feature extractor config
							with tempfile.TemporaryDirectory() as tmpdirname:
									lowerCAmelCase__        =   Path(snake_case__     ) / """preprocessor_config.json"""
									lowerCAmelCase__        =   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"""     )     )

									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__     )
									self.assertIsInstance(snake_case__  ,						snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Optional[int]     ):
							with tempfile.TemporaryDirectory() as tmpdirname:
									lowerCAmelCase__        =   CLIPConfig()

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

									config_dict.pop("""image_processor_type"""     )
									lowerCAmelCase__        =   CLIPImageProcessor(**snake_case__     )

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

									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__     )

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

							self.assertIsInstance(snake_case__  ,						snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Dict     ):
							with tempfile.TemporaryDirectory() as tmpdirname:
									lowerCAmelCase__        =   Path(snake_case__     ) / """preprocessor_config.json"""
									json.dump(
									    {"""image_processor_type""": """CLIPImageProcessor""", """processor_class""": """CLIPProcessor"""}  ,						open(snake_case__  ,						"""w"""     )  ,						)

									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__     )
									self.assertIsInstance(snake_case__  ,						snake_case__     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Optional[int]     ):
							with self.assertRaisesRegex(
							    snake_case__  ,						"""clip-base is not a local folder and is not a valid model identifier"""     ):
									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained("""clip-base"""     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Union[str, Any]     ):
							with self.assertRaisesRegex(
							    snake_case__  ,						R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""     ):
									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__  ,						revision="""aaaaaa"""     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Optional[Any]     ):
							with self.assertRaisesRegex(
							    snake_case__  ,						"""hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""  ,						):
									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained("""hf-internal-testing/config-no-model"""     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Any     ):
							# If remote code is not set, we will time out when asking whether to load the model.
							with self.assertRaises(snake_case__     ):
									lowerCAmelCase__        =   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__     ):
									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(
									    """hf-internal-testing/test_dynamic_image_processor"""  ,						trust_remote_code=snake_case__     )

							lowerCAmelCase__        =   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__     )
									lowerCAmelCase__        =   AutoImageProcessor.from_pretrained(snake_case__  ,						trust_remote_code=snake_case__     )
							self.assertEqual(reloaded_image_processor.__class__.__name__  ,						"""NewImageProcessor"""     )




					def 						_SCREAMING_SNAKE_CASE						(	self						:     Dict     ):
							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:
											lowerCAmelCase__        =   Path(snake_case__     ) / """preprocessor_config.json"""
											lowerCAmelCase__        =   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"""     )     )

											lowerCAmelCase__        =   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__     )
											lowerCAmelCase__        =   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 						_SCREAMING_SNAKE_CASE						(	self						:     List[str]     ):

							class       a_      (     __UpperCamelCase			):
												UpperCamelCase_ :	Tuple			=    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
									lowerCAmelCase__        =   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.
									lowerCAmelCase__        =   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
									lowerCAmelCase__        =   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]




