





'''simple docstring'''

import copy
import os
from typing import Union

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


__lowerCAmelCase				:      Union[str, Any]						      =logging.get_logger(__name__)

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






class   UpperCAmelCase      (			UpperCamelCase__							):
 __lowercase  						=							"""altclip_text_model"""
 def __init__(							self :Dict		,			lowercase_ :Dict=25_00_02		,			lowercase_ :int=10_24		,			lowercase_ :Tuple=24		,			lowercase_ :Tuple=16		,			lowercase_ :str=40_96		,			lowercase_ :List[Any]="gelu"		,			lowercase_ :str=0.1		,			lowercase_ :Optional[Any]=0.1		,			lowercase_ :int=5_14		,			lowercase_ :List[Any]=1		,			lowercase_ :Union[str, Any]=0.0_2		,			lowercase_ :int=0.0_2		,			lowercase_ :Union[str, Any]=1E-05		,			lowercase_ :Optional[Any]=1		,			lowercase_ :Union[str, Any]=0		,			lowercase_ :int=2		,			lowercase_ :Any="absolute"		,			lowercase_ :Any=True		,			lowercase_ :Optional[int]=7_68		,			**lowercase_ :int		,			)->				int:
     super().__init__(pad_token_id=lowercase_		,			bos_token_id=lowercase_		,			eos_token_id=lowercase_		,			**lowercase_				)

     A__							=     vocab_size
     A__							=     hidden_size
     A__							=     num_hidden_layers
     A__							=     num_attention_heads
     A__							=     hidden_act
     A__							=     intermediate_size
     A__							=     hidden_dropout_prob
     A__							=     attention_probs_dropout_prob
     A__							=     max_position_embeddings
     A__							=     type_vocab_size
     A__							=     initializer_range
     A__							=     initializer_factor
     A__							=     layer_norm_eps
     A__							=     position_embedding_type
     A__							=     use_cache
     A__							=     project_dim






class   UpperCAmelCase      (			UpperCamelCase__							):
 __lowercase  						=							"""altclip_vision_model"""
 def __init__(							self :Any		,			lowercase_ :Tuple=7_68		,			lowercase_ :List[str]=30_72		,			lowercase_ :str=5_12		,			lowercase_ :Dict=12		,			lowercase_ :List[Any]=12		,			lowercase_ :Tuple=3		,			lowercase_ :str=2_24		,			lowercase_ :Any=32		,			lowercase_ :Tuple="quick_gelu"		,			lowercase_ :Dict=1E-5		,			lowercase_ :int=0.0		,			lowercase_ :str=0.0_2		,			lowercase_ :List[Any]=1.0		,			**lowercase_ :str		,			)->				Union[str, Any]:
     super().__init__(**lowercase_				)

     A__							=     hidden_size
     A__							=     intermediate_size
     A__							=     projection_dim
     A__							=     num_hidden_layers
     A__							=     num_attention_heads
     A__							=     num_channels
     A__							=     patch_size
     A__							=     image_size
     A__							=     initializer_range
     A__							=     initializer_factor
     A__							=     attention_dropout
     A__							=     layer_norm_eps
     A__							=     hidden_act



 @classmethod
 def 	UpperCAmelCase_				(							cls :Tuple		,			lowercase_ :Union[str, os.PathLike]		,			**lowercase_ :Any				)->				"PretrainedConfig":
     cls._set_token_in_kwargs(lowercase_				)

     A__,      A__							=     cls.get_config_dict(lowercase_		,			**lowercase_				)

     # get the vision config dict if we are loading from AltCLIPConfig
     if config_dict.get("model_type"				) == "altclip":
         A__							=     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(lowercase_		,			**lowercase_				)






class   UpperCAmelCase      (			UpperCamelCase__							):
 __lowercase  						=							"""altclip"""
 __lowercase  						=							True
 def __init__(							self :Union[str, Any]		,			lowercase_ :Any=None		,			lowercase_ :List[Any]=None		,			lowercase_ :Optional[int]=7_68		,			lowercase_ :Union[str, Any]=2.6_5_9_2		,			**lowercase_ :Optional[Any]				)->				int:
     # If `_config_dict` exist, we use them for the backward compatibility.
     # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
     # of confusion!).
     A__							=     kwargs.pop("text_config_dict"		,			lowercase_				)
     A__							=     kwargs.pop("vision_config_dict"		,			lowercase_				)

     super().__init__(**lowercase_				)

     # 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:
             A__							=     {}

         # This is the complete result when using `text_config_dict`.
         A__							=     AltCLIPTextConfig(**lowercase_				).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:
                     A__							=     (
                         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:
                     A__							=     (
                         F"`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The "
                         F"value `text_config[\"{key}\"]` will be overriden."
                     )
                 logger.warning(lowercase_				)

            # 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:
             A__							=     {}

         # This is the complete result when using `vision_config_dict`.
         A__							=     AltCLIPVisionConfig(**lowercase_				).to_dict()
         # convert keys to string instead of integer
         if "id2label" in _vision_config_dict:
             A__							=     {
                 str(lowercase_				): 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:
                     A__							=     (
                         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:
                     A__							=     (
                         F"`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. "
                         F"The value `vision_config[\"{key}\"]` will be overriden."
                     )
                 logger.warning(lowercase_				)

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

     if text_config is None:
         A__							=     {}
         logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values."				)

     if vision_config is None:
         A__							=     {}
         logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."				)

     A__							=     AltCLIPTextConfig(**lowercase_				)
     A__							=     AltCLIPVisionConfig(**lowercase_				)

     A__							=     projection_dim
     A__							=     logit_scale_init_value
     A__							=     1.0
 @classmethod
 def 	UpperCAmelCase_				(							cls :Tuple		,			lowercase_ :AltCLIPTextConfig		,			lowercase_ :AltCLIPVisionConfig		,			**lowercase_ :Union[str, Any]				)->				Union[str, Any]:
     return cls(text_config=text_config.to_dict()		,			vision_config=vision_config.to_dict()		,			**lowercase_				)



 def 	UpperCAmelCase_				(							self :List[Any]				)->				str:
     A__							=     copy.deepcopy(self.__dict__				)
     A__							=     self.text_config.to_dict()
     A__							=     self.vision_config.to_dict()
     A__							=     self.__class__.model_type
     return output










'''simple docstring'''

import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding






class   UpperCAmelCase      (			UpperCamelCase__							):
 __lowercase  						=							["""image_processor""", """tokenizer"""]
 __lowercase  						=							"""CLIPImageProcessor"""
 __lowercase  						=							("""CLIPTokenizer""", """CLIPTokenizerFast""")
 def __init__(							self :List[Any]		,			lowercase_ :List[str]=None		,			lowercase_ :Any=None		,			**lowercase_ :Union[str, Any]				)->				Optional[Any]:
     A__							=     None
     if "feature_extractor" in kwargs:
         warnings.warn(
             "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
             " instead."		,			lowercase_		,			)
         A__							=     kwargs.pop("feature_extractor"				)

     A__							=     image_processor if image_processor is not None else feature_extractor
     if image_processor is None:
         raise ValueError("You need to specify an `image_processor`."				)
     if tokenizer is None:
         raise ValueError("You need to specify a `tokenizer`."				)

     super().__init__(lowercase_		,			lowercase_				)
 def __call__(							self :Optional[Any]		,			lowercase_ :Optional[int]=None		,			lowercase_ :Dict=None		,			lowercase_ :List[Any]=None		,			**lowercase_ :Optional[Any]				)->				Union[str, Any]:

     if text is None and images is None:
         raise ValueError("You have to specify either text or images. Both cannot be none."				)

     if text is not None:
         A__							=     self.tokenizer(lowercase_		,			return_tensors=lowercase_		,			**lowercase_				)

     if images is not None:
         A__							=     self.image_processor(lowercase_		,			return_tensors=lowercase_		,			**lowercase_				)

     if text is not None and images is not None:
         A__							=     image_features.pixel_values
         return encoding
     elif text is not None:
         return encoding
     else:
         return BatchEncoding(data=dict(**lowercase_				)		,			tensor_type=lowercase_				)
 def 	UpperCAmelCase_				(							self :int		,			*lowercase_ :Tuple		,			**lowercase_ :Any				)->				Dict:
     return self.tokenizer.batch_decode(*lowercase_		,			**lowercase_				)
 def 	UpperCAmelCase_				(							self :Any		,			*lowercase_ :Any		,			**lowercase_ :Any				)->				List[str]:
     return self.tokenizer.decode(*lowercase_		,			**lowercase_				)
 @property
 def 	UpperCAmelCase_				(							self :Union[str, Any]				)->				Optional[int]:
     A__							=     self.tokenizer.model_input_names
     A__							=     self.image_processor.model_input_names
     return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names				)				)
 @property
 def 	UpperCAmelCase_				(							self :List[Any]				)->				str:
     warnings.warn(
         "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."		,			lowercase_		,			)
     return self.image_processor_class



 @property
 def 	UpperCAmelCase_				(							self :List[str]				)->				List[Any]:
     warnings.warn(
         "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."		,			lowercase_		,			)
     return self.image_processor



