
import copy
import os
from typing import Union

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


_lowercase     							=						logging.get_logger(__name__)

_lowercase     							=						{
    "BAAI/AltCLIP": "https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json",
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}
class 				__A					( UpperCAmelCase_      ):
			UpperCamelCase					:Any     =			'altclip_text_model'





			def __init__(self							,    __magic_name__=250002							,    __magic_name__=1024							,    __magic_name__=24							,    __magic_name__=16							,    __magic_name__=4096							,    __magic_name__="gelu"							,    __magic_name__=0.1							,    __magic_name__=0.1							,    __magic_name__=514							,    __magic_name__=1							,    __magic_name__=0.02							,    __magic_name__=0.02							,    __magic_name__=1E-05							,    __magic_name__=1							,    __magic_name__=0							,    __magic_name__=2							,    __magic_name__="absolute"							,    __magic_name__=True							,    __magic_name__=768							,    **__magic_name__							,    ):
						super().__init__(pad_token_id=_lowercase							,    bos_token_id=_lowercase							,    eos_token_id=_lowercase							,    **_lowercase				)

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







class 				__A					( UpperCAmelCase_      ):
			UpperCamelCase					:str     =			'altclip_vision_model'





			def __init__(self							,    __magic_name__=768							,    __magic_name__=3072							,    __magic_name__=512							,    __magic_name__=12							,    __magic_name__=12							,    __magic_name__=3							,    __magic_name__=224							,    __magic_name__=32							,    __magic_name__="quick_gelu"							,    __magic_name__=1E-5							,    __magic_name__=0.0							,    __magic_name__=0.02							,    __magic_name__=1.0							,    **__magic_name__							,    ):
						super().__init__(**_lowercase				)

						lowerCamelCase__ :      List[str]								=		hidden_size
						lowerCamelCase__ :      Any								=		intermediate_size
						lowerCamelCase__ :      int								=		projection_dim
						lowerCamelCase__ :      Union[str, Any]								=		num_hidden_layers
						lowerCamelCase__ :      List[Any]								=		num_attention_heads
						lowerCamelCase__ :      Any								=		num_channels
						lowerCamelCase__ :      Optional[Any]								=		patch_size
						lowerCamelCase__ :      Optional[Any]								=		image_size
						lowerCamelCase__ :      Tuple								=		initializer_range
						lowerCamelCase__ :      List[str]								=		initializer_factor
						lowerCamelCase__ :      Any								=		attention_dropout
						lowerCamelCase__ :      str								=		layer_norm_eps
						lowerCamelCase__ :      Tuple								=		hidden_act





			@classmethod
			def        _snake_case    (cls							,    __magic_name__							,    **__magic_name__				):
						cls._set_token_in_kwargs(_lowercase				)

						lowerCamelCase__ :      int								=		cls.get_config_dict(_lowercase							,    **_lowercase				)

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







class 				__A					( UpperCAmelCase_      ):
			UpperCamelCase					:Dict     =			'altclip'
			UpperCamelCase					:Any     =			True





			def __init__(self							,    __magic_name__=None							,    __magic_name__=None							,    __magic_name__=768							,    __magic_name__=2.65_92							,    **__magic_name__				):
						# 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!).
						lowerCamelCase__ :      List[str]								=		kwargs.pop("""text_config_dict"""							,    _lowercase				)
						lowerCamelCase__ :      Optional[Any]								=		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:
												lowerCamelCase__ :      List[str]								=		{}

									# This is the complete result when using `text_config_dict`.
									lowerCamelCase__ :      str								=		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:
																		lowerCamelCase__ :      int								=		(
																		    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:
																		lowerCamelCase__ :      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(_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:
												lowerCamelCase__ :      Dict								=		{}

									# This is the complete result when using `vision_config_dict`.
									lowerCamelCase__ :      Optional[Any]								=		AltCLIPVisionConfig(**_lowercase				).to_dict()
									# convert keys to string instead of integer
									if "id2label" in _vision_config_dict:
												lowerCamelCase__ :      List[str]								=		{
												    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:
																		lowerCamelCase__ :      Union[str, Any]								=		(
																		    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:
																		lowerCamelCase__ :      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(_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:
									lowerCamelCase__ :      List[Any]								=		{}
									logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values."""				)

						if vision_config is None:
									lowerCamelCase__ :      Optional[Any]								=		{}
									logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."""				)

						lowerCamelCase__ :      int								=		AltCLIPTextConfig(**_lowercase				)
						lowerCamelCase__ :      Any								=		AltCLIPVisionConfig(**_lowercase				)

						lowerCamelCase__ :      Union[str, Any]								=		projection_dim
						lowerCamelCase__ :      List[Any]								=		logit_scale_init_value
						lowerCamelCase__ :      str								=		1.0





			@classmethod
			def        _snake_case    (cls							,    __magic_name__							,    __magic_name__							,    **__magic_name__				):
						return cls(text_config=text_config.to_dict()							,    vision_config=vision_config.to_dict()							,    **_lowercase				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      List[Any]								=		copy.deepcopy(self.__dict__				)
						lowerCamelCase__ :      Union[str, Any]								=		self.text_config.to_dict()
						lowerCamelCase__ :      int								=		self.vision_config.to_dict()
						lowerCamelCase__ :      Optional[int]								=		self.__class__.model_type
						return output








from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
				import PIL


_lowercase     							=						logging.get_logger(__name__)
class 				__A					( A_      ):
			UpperCamelCase					:Union[str, Any]     =			['''pixel_values''']





			def __init__(self							,    __magic_name__ = True							,    __magic_name__ = None							,    __magic_name__ = PIL.Image.BICUBIC							,    __magic_name__ = True							,    __magic_name__ = None							,    __magic_name__ = 1 / 255							,    __magic_name__ = True							,    __magic_name__ = True							,    __magic_name__ = None							,    __magic_name__ = None							,    **__magic_name__							,    ):
						super().__init__(**__magic_name__				)
						lowerCamelCase__ :      str								=		size if size is not None else {"""height""": 256, """width""": 256}
						lowerCamelCase__ :      Optional[int]								=		get_size_dict(__magic_name__				)
						lowerCamelCase__ :      Any								=		crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
						lowerCamelCase__ :      Optional[int]								=		get_size_dict(__magic_name__							,    param_name="""crop_size"""				)

						lowerCamelCase__ :      str								=		do_resize
						lowerCamelCase__ :      Any								=		size
						lowerCamelCase__ :      Tuple								=		resample
						lowerCamelCase__ :      Union[str, Any]								=		do_center_crop
						lowerCamelCase__ :      List[str]								=		crop_size
						lowerCamelCase__ :      int								=		do_rescale
						lowerCamelCase__ :      Any								=		rescale_factor
						lowerCamelCase__ :      Dict								=		do_normalize
						lowerCamelCase__ :      Dict								=		image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
						lowerCamelCase__ :      int								=		image_std if image_std is not None else IMAGENET_STANDARD_STD





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__ = PIL.Image.BICUBIC							,    __magic_name__ = None							,    **__magic_name__							,    ):
						lowerCamelCase__ :      Optional[int]								=		get_size_dict(__magic_name__				)
						if "height" not in size or "width" not in size:
									raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"				)
						return resize(
						    __magic_name__							,    size=(size["""height"""], size["""width"""])							,    resample=__magic_name__							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__ = None							,    **__magic_name__							,    ):
						lowerCamelCase__ :      Tuple								=		get_size_dict(__magic_name__				)
						if "height" not in size or "width" not in size:
									raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"				)
						return center_crop(__magic_name__							,    size=(size["""height"""], size["""width"""])							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__ = None							,    **__magic_name__							,    ):
						return rescale(__magic_name__							,    scale=__magic_name__							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__ = None							,    **__magic_name__							,    ):
						return normalize(__magic_name__							,    mean=__magic_name__							,    std=__magic_name__							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__=None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = ChannelDimension.FIRST							,    **__magic_name__							,    ):
						lowerCamelCase__ :      Tuple								=		do_resize if do_resize is not None else self.do_resize
						lowerCamelCase__ :      str								=		resample if resample is not None else self.resample
						lowerCamelCase__ :      str								=		do_center_crop if do_center_crop is not None else self.do_center_crop
						lowerCamelCase__ :      Optional[int]								=		do_rescale if do_rescale is not None else self.do_rescale
						lowerCamelCase__ :      str								=		rescale_factor if rescale_factor is not None else self.rescale_factor
						lowerCamelCase__ :      Union[str, Any]								=		do_normalize if do_normalize is not None else self.do_normalize
						lowerCamelCase__ :      Tuple								=		image_mean if image_mean is not None else self.image_mean
						lowerCamelCase__ :      List[Any]								=		image_std if image_std is not None else self.image_std

						lowerCamelCase__ :      str								=		size if size is not None else self.size
						lowerCamelCase__ :      List[str]								=		get_size_dict(__magic_name__				)
						lowerCamelCase__ :      Tuple								=		crop_size if crop_size is not None else self.crop_size
						lowerCamelCase__ :      Optional[Any]								=		get_size_dict(__magic_name__							,    param_name="""crop_size"""				)

						lowerCamelCase__ :      Optional[int]								=		make_list_of_images(__magic_name__				)

						if not valid_images(__magic_name__				):
									raise ValueError(
									    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
									    """torch.Tensor, tf.Tensor or jax.ndarray."""				)

						if do_resize and size is None or resample is None:
									raise ValueError("""Size and resample must be specified if do_resize is True."""				)

						if do_center_crop and crop_size is None:
									raise ValueError("""Crop size must be specified if do_center_crop is True."""				)

						if do_rescale and rescale_factor is None:
									raise ValueError("""Rescale factor must be specified if do_rescale is True."""				)

						if do_normalize and (image_mean is None or image_std is None):
									raise ValueError("""Image mean and std must be specified if do_normalize is True."""				)

						# All transformations expect numpy arrays.
						lowerCamelCase__ :      Optional[int]								=		[to_numpy_array(__magic_name__				) for image in images]

						if do_resize:
									lowerCamelCase__ :      int								=		[self.resize(image=__magic_name__							,    size=__magic_name__							,    resample=__magic_name__				) for image in images]

						if do_center_crop:
									lowerCamelCase__ :      List[Any]								=		[self.center_crop(image=__magic_name__							,    size=__magic_name__				) for image in images]

						if do_rescale:
									lowerCamelCase__ :      Dict								=		[self.rescale(image=__magic_name__							,    scale=__magic_name__				) for image in images]

						if do_normalize:
									lowerCamelCase__ :      Optional[Any]								=		[self.normalize(image=__magic_name__							,    mean=__magic_name__							,    std=__magic_name__				) for image in images]

						lowerCamelCase__ :      List[str]								=		[to_channel_dimension_format(__magic_name__							,    __magic_name__				) for image in images]

						lowerCamelCase__ :      Dict								=		{"""pixel_values""": images}
						return BatchFeature(data=__magic_name__							,    tensor_type=__magic_name__				)



