






'''simple docstring'''





import copy
import os
from typing import Union

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


lowerCamelCase__							=     logging.get_logger(__name__)

lowerCamelCase__							=     {
    'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json',
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}




class 			snake_case__   (							_A):

       '''simple docstring'''
       lowerCamelCase							:				Dict 				= "altclip_text_model"



       def __init__(							self			,						a__=25_00_02			,						a__=10_24			,						a__=24			,						a__=16			,						a__=40_96			,						a__="gelu"			,						a__=0.1			,						a__=0.1			,						a__=5_14			,						a__=1			,						a__=0.02			,						a__=0.02			,						a__=1e-05			,						a__=1			,						a__=0			,						a__=2			,						a__="absolute"			,						a__=True			,						a__=7_68			,						**a__			,						) ->      List[Any]:






            '''simple docstring'''





            super().__init__(pad_token_id=UpperCamelCase__			,						bos_token_id=UpperCamelCase__			,						eos_token_id=UpperCamelCase__			,						**UpperCamelCase__    )

            __snake_case			:Dict          =						vocab_size
            __snake_case			:str          =						hidden_size
            __snake_case			:int          =						num_hidden_layers
            __snake_case			:List[str]          =						num_attention_heads
            __snake_case			:List[Any]          =						hidden_act
            __snake_case			:Any          =						intermediate_size
            __snake_case			:Tuple          =						hidden_dropout_prob
            __snake_case			:Dict          =						attention_probs_dropout_prob
            __snake_case			:Any          =						max_position_embeddings
            __snake_case			:Union[str, Any]          =						type_vocab_size
            __snake_case			:str          =						initializer_range
            __snake_case			:List[Any]          =						initializer_factor
            __snake_case			:List[str]          =						layer_norm_eps
            __snake_case			:Optional[int]          =						position_embedding_type
            __snake_case			:List[Any]          =						use_cache
            __snake_case			:str          =						project_dim




class 			snake_case__   (							_A):

       '''simple docstring'''
       lowerCamelCase							:				Optional[Any] 				= "altclip_vision_model"



       def __init__(							self			,						a__=7_68			,						a__=30_72			,						a__=5_12			,						a__=12			,						a__=12			,						a__=3			,						a__=2_24			,						a__=32			,						a__="quick_gelu"			,						a__=1e-5			,						a__=0.0			,						a__=0.02			,						a__=1.0			,						**a__			,						) ->      Tuple:






            '''simple docstring'''





            super().__init__(**UpperCamelCase__    )

            __snake_case			:int          =						hidden_size
            __snake_case			:Tuple          =						intermediate_size
            __snake_case			:Optional[int]          =						projection_dim
            __snake_case			:int          =						num_hidden_layers
            __snake_case			:Any          =						num_attention_heads
            __snake_case			:Optional[Any]          =						num_channels
            __snake_case			:Optional[Any]          =						patch_size
            __snake_case			:int          =						image_size
            __snake_case			:Any          =						initializer_range
            __snake_case			:int          =						initializer_factor
            __snake_case			:Dict          =						attention_dropout
            __snake_case			:Optional[int]          =						layer_norm_eps
            __snake_case			:List[Any]          =						hidden_act



       @classmethod
       def 					__lowercase						(							cls			,						a__			,						**a__    ) ->      "PretrainedConfig":






            '''simple docstring'''





            cls._set_token_in_kwargs(UpperCamelCase__    )

            __snake_case       , __snake_case			:Dict          =						cls.get_config_dict(UpperCamelCase__			,						**UpperCamelCase__    )

            # get the vision config dict if we are loading from AltCLIPConfig
            if config_dict.get("""model_type"""    ) == "altclip":
                 __snake_case			:List[str]          =						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(UpperCamelCase__			,						**UpperCamelCase__    )




class 			snake_case__   (							_A):

       '''simple docstring'''
       lowerCamelCase							:				List[str] 				= "altclip"
       lowerCamelCase							:				List[Any] 				= True



       def __init__(							self			,						a__=None			,						a__=None			,						a__=7_68			,						a__=2.65_92			,						**a__    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:List[Any]          =						kwargs.pop("""text_config_dict"""			,						UpperCamelCase__    )
            __snake_case			:Optional[int]          =						kwargs.pop("""vision_config_dict"""			,						UpperCamelCase__    )

            super().__init__(**UpperCamelCase__    )

            # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
            # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
            # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
            if text_config_dict is not None:
                 if text_config is None:
                      __snake_case			:Any          =						{}

                 # This is the complete result when using `text_config_dict`.
                 __snake_case			:List[str]          =						AltCLIPTextConfig(**UpperCamelCase__    ).to_dict()

                 # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
                 for key, value in _text_config_dict.items():
                      if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
                           # If specified in `text_config_dict`
                           if key in text_config_dict:
                                __snake_case			:List[Any]          =						(
                                    F'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. '''
                                    F'''The value `text_config_dict["{key}"]` will be used instead.'''
                                )
                           # If inferred from default argument values (just to be super careful)
                           else:
                                __snake_case			:List[str]          =						(
                                    F'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '''
                                    F'''value `text_config["{key}"]` will be overriden.'''
                                )
                           logger.warning(UpperCamelCase__    )

                             # Update all values in `text_config` with the ones in `_text_config_dict`.
                 text_config.update(_text_config_dict    )

            if vision_config_dict is not None:
                 if vision_config is None:
                      __snake_case			:Optional[int]          =						{}

                 # This is the complete result when using `vision_config_dict`.
                 __snake_case			:Any          =						AltCLIPVisionConfig(**UpperCamelCase__    ).to_dict()
                 # convert keys to string instead of integer
                 if "id2label" in _vision_config_dict:
                      __snake_case			:Optional[Any]          =						{
                          str(UpperCamelCase__    ): value for key, value in _vision_config_dict["""id2label"""].items()
                      }

                 # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
                 for key, value in _vision_config_dict.items():
                      if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
                           # If specified in `vision_config_dict`
                           if key in vision_config_dict:
                                __snake_case			:Optional[int]          =						(
                                    F'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different '''
                                    F'''values. The value `vision_config_dict["{key}"]` will be used instead.'''
                                )
                           # If inferred from default argument values (just to be super careful)
                           else:
                                __snake_case			:Any          =						(
                                    F'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '''
                                    F'''The value `vision_config["{key}"]` will be overriden.'''
                                )
                           logger.warning(UpperCamelCase__    )

                             # Update all values in `vision_config` with the ones in `_vision_config_dict`.
                 vision_config.update(_vision_config_dict    )

            if text_config is None:
                 __snake_case			:Union[str, Any]          =						{}
                 logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values."""    )

            if vision_config is None:
                 __snake_case			:List[str]          =						{}
                 logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."""    )

            __snake_case			:Dict          =						AltCLIPTextConfig(**UpperCamelCase__    )
            __snake_case			:List[str]          =						AltCLIPVisionConfig(**UpperCamelCase__    )

            __snake_case			:int          =						projection_dim
            __snake_case			:List[Any]          =						logit_scale_init_value
            __snake_case			:Any          =						1.0



       @classmethod
       def 					__lowercase						(							cls			,						a__			,						a__			,						**a__    ) ->      Tuple:






            '''simple docstring'''





            return cls(text_config=text_config.to_dict()			,						vision_config=vision_config.to_dict()			,						**UpperCamelCase__    )



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            __snake_case			:int          =						copy.deepcopy(self.__dict__    )
            __snake_case			:List[Any]          =						self.text_config.to_dict()
            __snake_case			:int          =						self.vision_config.to_dict()
            __snake_case			:List[Any]          =						self.__class__.model_type
            return output










import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
     import torch

if is_vision_available():
     from PIL import Image

     from transformers import GLPNImageProcessor




class 			snake_case__   (							unittest.TestCase):

       '''simple docstring'''



       def __init__(							self			,						a__			,						a__=7			,						a__=3			,						a__=18			,						a__=30			,						a__=4_00			,						a__=True			,						a__=32			,						a__=True			,						) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:List[Any]          =						parent
            __snake_case			:Dict          =						batch_size
            __snake_case			:Optional[Any]          =						num_channels
            __snake_case			:Dict          =						image_size
            __snake_case			:Dict          =						min_resolution
            __snake_case			:Dict          =						max_resolution
            __snake_case			:List[Any]          =						do_resize
            __snake_case			:Dict          =						size_divisor
            __snake_case			:Union[str, Any]          =						do_rescale



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            return {
                "do_resize": self.do_resize,
                "size_divisor": self.size_divisor,
                "do_rescale": self.do_rescale,
            }




@require_torch
@require_vision
class 			snake_case__   (							lowercase_	,    unittest.TestCase):

       '''simple docstring'''
       lowerCamelCase							:				Tuple 				= GLPNImageProcessor if is_vision_available() else None



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:Dict          =						GLPNImageProcessingTester(self    )



       @property
       def 					__lowercase						(							self    ) ->      Optional[int]:






            '''simple docstring'''





            return self.image_processor_tester.prepare_image_processor_dict()



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






            '''simple docstring'''





            __snake_case			:Optional[Any]          =						self.image_processing_class(**self.image_processor_dict    )
            self.assertTrue(hasattr(a__			,						"""do_resize"""    )    )
            self.assertTrue(hasattr(a__			,						"""size_divisor"""    )    )
            self.assertTrue(hasattr(a__			,						"""resample"""    )    )
            self.assertTrue(hasattr(a__			,						"""do_rescale"""    )    )



       def 					__lowercase						(							self    ) ->      str:






            '''simple docstring'''





            pass



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            __snake_case			:int          =						self.image_processing_class(**self.image_processor_dict    )
            # create random PIL images
            __snake_case			:Optional[Any]          =						prepare_image_inputs(self.image_processor_tester			,						equal_resolution=a__    )
            for image in image_inputs:
                 self.assertIsInstance(a__			,						Image.Image    )

            # Test not batched input (GLPNImageProcessor doesn't support batching)
            __snake_case			:Union[str, Any]          =						image_processing(image_inputs[0]			,						return_tensors="""pt"""    ).pixel_values
            self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0    )
            self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0    )



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            __snake_case			:int          =						self.image_processing_class(**self.image_processor_dict    )
            # create random numpy tensors
            __snake_case			:List[Any]          =						prepare_image_inputs(self.image_processor_tester			,						equal_resolution=a__			,						numpify=a__    )
            for image in image_inputs:
                 self.assertIsInstance(a__			,						np.ndarray    )

            # Test not batched input (GLPNImageProcessor doesn't support batching)
            __snake_case			:int          =						image_processing(image_inputs[0]			,						return_tensors="""pt"""    ).pixel_values
            self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0    )
            self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0    )



       def 					__lowercase						(							self    ) ->      Any:






            '''simple docstring'''





            __snake_case			:Tuple          =						self.image_processing_class(**self.image_processor_dict    )
            # create random PyTorch tensors
            __snake_case			:Optional[int]          =						prepare_image_inputs(self.image_processor_tester			,						equal_resolution=a__			,						torchify=a__    )
            for image in image_inputs:
                 self.assertIsInstance(a__			,						torch.Tensor    )

            # Test not batched input (GLPNImageProcessor doesn't support batching)
            __snake_case			:List[Any]          =						image_processing(image_inputs[0]			,						return_tensors="""pt"""    ).pixel_values
            self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0    )
            self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0    )


