




import copy
import os
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union


if TYPE_CHECKING:
						from ...processing_utils import ProcessorMixin
						from ...utils import TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


SCREAMING_SNAKE_CASE:     Any									= logging.get_logger(__name__)

SCREAMING_SNAKE_CASE:     int									= {
    '''google/owlvit-base-patch32''': '''https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json''',
    '''google/owlvit-base-patch16''': '''https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json''',
    '''google/owlvit-large-patch14''': '''https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json''',
}



class    lowercase_		(SCREAMING_SNAKE_CASE__ ):
						lowerCAmelCase__			      ="owlvit_text_model"



						def __init__(			self	:   Union[str, Any]					,							snake_case__	:   Tuple=4_94_08					,							snake_case__	:   Any=5_12					,							snake_case__	:   Optional[int]=20_48					,							snake_case__	:   List[Any]=12					,							snake_case__	:   Optional[Any]=8					,							snake_case__	:   Optional[int]=16					,							snake_case__	:   Tuple="quick_gelu"					,							snake_case__	:   List[str]=1e-5					,							snake_case__	:   Optional[Any]=0.0					,							snake_case__	:   Optional[Any]=0.02					,							snake_case__	:   str=1.0					,							snake_case__	:   Optional[Any]=0					,							snake_case__	:   List[str]=4_94_06					,							snake_case__	:   Dict=4_94_07					,							**snake_case__	:   str					,							):

								"""simple docstring"""

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

								SCREAMING_SNAKE_CASE_					      =							vocab_size
								SCREAMING_SNAKE_CASE_					      =							hidden_size
								SCREAMING_SNAKE_CASE_					      =							intermediate_size
								SCREAMING_SNAKE_CASE_					      =							num_hidden_layers
								SCREAMING_SNAKE_CASE_					      =							num_attention_heads
								SCREAMING_SNAKE_CASE_					      =							max_position_embeddings
								SCREAMING_SNAKE_CASE_					      =							hidden_act
								SCREAMING_SNAKE_CASE_					      =							layer_norm_eps
								SCREAMING_SNAKE_CASE_					      =							attention_dropout
								SCREAMING_SNAKE_CASE_					      =							initializer_range
								SCREAMING_SNAKE_CASE_					      =							initializer_factor






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

								"""simple docstring"""

								cls._set_token_in_kwargs(snake_case__  )

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

								# get the text config dict if we are loading from OwlViTConfig
								if config_dict.get('model_type'  ) == "owlvit":
										SCREAMING_SNAKE_CASE_					      =							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    lowercase_		(SCREAMING_SNAKE_CASE__ ):
						lowerCAmelCase__			      ="owlvit_vision_model"



						def __init__(			self	:   int					,							snake_case__	:   List[str]=7_68					,							snake_case__	:   Any=30_72					,							snake_case__	:   Dict=12					,							snake_case__	:   Union[str, Any]=12					,							snake_case__	:   List[Any]=3					,							snake_case__	:   str=7_68					,							snake_case__	:   List[Any]=32					,							snake_case__	:   Tuple="quick_gelu"					,							snake_case__	:   List[Any]=1e-5					,							snake_case__	:   Tuple=0.0					,							snake_case__	:   Tuple=0.02					,							snake_case__	:   List[Any]=1.0					,							**snake_case__	:   int					,							):

								"""simple docstring"""

								super().__init__(**snake_case__  )

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






						@classmethod
						def 	__a					(			cls	:   List[str]					,							snake_case__	:   Union[str, os.PathLike]					,							**snake_case__	:   List[Any]  ):

								"""simple docstring"""

								cls._set_token_in_kwargs(snake_case__  )

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

								# get the vision config dict if we are loading from OwlViTConfig
								if config_dict.get('model_type'  ) == "owlvit":
										SCREAMING_SNAKE_CASE_					      =							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    lowercase_		(SCREAMING_SNAKE_CASE__ ):
						lowerCAmelCase__			      ="owlvit"
						lowerCAmelCase__			      =True



						def __init__(			self	:   List[str]					,							snake_case__	:   Any=None					,							snake_case__	:   Optional[Any]=None					,							snake_case__	:   Optional[Any]=5_12					,							snake_case__	:   List[Any]=2.65_92					,							snake_case__	:   Any=True					,							**snake_case__	:   int					,							):

								"""simple docstring"""

								super().__init__(**snake_case__  )

								if text_config is None:
										SCREAMING_SNAKE_CASE_					      =							{}
										logger.info('text_config is None. Initializing the OwlViTTextConfig with default values.'  )

								if vision_config is None:
										SCREAMING_SNAKE_CASE_					      =							{}
										logger.info('vision_config is None. initializing the OwlViTVisionConfig with default values.'  )

								SCREAMING_SNAKE_CASE_					      =							OwlViTTextConfig(**snake_case__  )
								SCREAMING_SNAKE_CASE_					      =							OwlViTVisionConfig(**snake_case__  )

								SCREAMING_SNAKE_CASE_					      =							projection_dim
								SCREAMING_SNAKE_CASE_					      =							logit_scale_init_value
								SCREAMING_SNAKE_CASE_					      =							return_dict
								SCREAMING_SNAKE_CASE_					      =							1.0



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

								"""simple docstring"""

								cls._set_token_in_kwargs(snake_case__  )

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

								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__  )



						@classmethod
						def 	__a					(			cls	:   Optional[int]					,							snake_case__	:   Dict					,							snake_case__	:   Dict					,							**snake_case__	:   Optional[Any]  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							{}
								SCREAMING_SNAKE_CASE_					      =							text_config
								SCREAMING_SNAKE_CASE_					      =							vision_config

								return cls.from_dict(snake_case__					,							**snake_case__  )






						def 	__a					(			self	:   List[Any]  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							copy.deepcopy(self.__dict__  )
								SCREAMING_SNAKE_CASE_					      =							self.text_config.to_dict()
								SCREAMING_SNAKE_CASE_					      =							self.vision_config.to_dict()
								SCREAMING_SNAKE_CASE_					      =							self.__class__.model_type
								return output



class    lowercase_		(SCREAMING_SNAKE_CASE__ ):



						@property
						def 	__a					(			self	:   List[str]  ):

								"""simple docstring"""

								return OrderedDict(
								    [
								        ('input_ids', {0: 'batch', 1: 'sequence'}),
								        ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
								        ('attention_mask', {0: 'batch', 1: 'sequence'}),
								    ]  )



						@property
						def 	__a					(			self	:   str  ):

								"""simple docstring"""

								return OrderedDict(
								    [
								        ('logits_per_image', {0: 'batch'}),
								        ('logits_per_text', {0: 'batch'}),
								        ('text_embeds', {0: 'batch'}),
								        ('image_embeds', {0: 'batch'}),
								    ]  )



						@property
						def 	__a					(			self	:   str  ):

								"""simple docstring"""

								return 1e-4



						def 	__a					(			self	:   Any					,							snake_case__	:   "ProcessorMixin"					,							snake_case__	:   int = -1					,							snake_case__	:   int = -1					,							snake_case__	:   Optional["TensorType"] = None					,							):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							super().generate_dummy_inputs(
								    processor.tokenizer					,							batch_size=snake_case__					,							seq_length=snake_case__					,							framework=snake_case__  )
								SCREAMING_SNAKE_CASE_					      =							super().generate_dummy_inputs(
								    processor.image_processor					,							batch_size=snake_case__					,							framework=snake_case__  )
								return {**text_input_dict, **image_input_dict}






						@property
						def 	__a					(			self	:   str  ):

								"""simple docstring"""

								return 14





import numpy as np
from numpy import ndarray
from scipy.optimize import Bounds, LinearConstraint, minimize


def 					_a							(					lowerCAmelCase )->	float:
		return np.dot(lowerCAmelCase    ,						lowerCAmelCase )



class    lowercase_		:



						def __init__(			self	:   int					,							*,
						    snake_case__	:   float = np.inf					,							snake_case__	:   str = "linear"					,							snake_case__	:   float = 0.0					,							):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							regularization
								SCREAMING_SNAKE_CASE_					      =							gamma
								if kernel == "linear":
										SCREAMING_SNAKE_CASE_					      =							self.__linear
								elif kernel == "rbf":
										if self.gamma == 0:
												raise ValueError('rbf kernel requires gamma'  )
										if not isinstance(self.gamma					,							(float, int)  ):
												raise ValueError('gamma must be float or int'  )
										if not self.gamma > 0:
												raise ValueError('gamma must be > 0'  )
										SCREAMING_SNAKE_CASE_					      =							self.__rbf
										# in the future, there could be a default value like in sklearn
										# sklear: def_gamma = 1/(n_features * X.var()) (wiki)
										# previously it was 1/(n_features)
								else:
										SCREAMING_SNAKE_CASE_					      =							f'''Unknown kernel: {kernel}'''
										raise ValueError(snake_case__  )



						def 	__a					(			self	:   Tuple					,							snake_case__	:   ndarray					,							snake_case__	:   ndarray  ):

								"""simple docstring"""

								return np.dot(snake_case__					,							snake_case__  )



						def 	__a					(			self	:   int					,							snake_case__	:   ndarray					,							snake_case__	:   ndarray  ):

								"""simple docstring"""

								return np.exp(-(self.gamma * norm_squared(vectora - vectora  ))  )



						def 	__a					(			self	:   int					,							snake_case__	:   list[ndarray]					,							snake_case__	:   ndarray  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							observations
								SCREAMING_SNAKE_CASE_					      =							classes

								# using Wolfe's Dual to calculate w.
								# Primal problem: minimize 1/2*norm_squared(w)
								#   constraint: yn(w . xn + b) >= 1
								#
								# With l a vector
								# Dual problem: maximize sum_n(ln) -
								#       1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm))
								#   constraint: self.C >= ln >= 0
								#           and sum_n(ln*yn) = 0
								# Then we get w using w = sum_n(ln*yn*xn)
								# At the end we can get b ~= mean(yn - w . xn)
								#
								# Since we use kernels, we only need l_star to calculate b
								# and to classify observations

								((SCREAMING_SNAKE_CASE_)      ,				)					      =							np.shape(snake_case__  )

								def to_minimize(snake_case__	:   ndarray  ) -> float:
										SCREAMING_SNAKE_CASE_					      =							0
										((SCREAMING_SNAKE_CASE_)      ,				)					      =							np.shape(snake_case__  )
										for i in range(snake_case__  ):
												for j in range(snake_case__  ):
														s += (
														    candidate[i]
														    * candidate[j]
														    * classes[i]
														    * classes[j]
														    * self.kernel(observations[i]					,							observations[j]  )
														)
										return 1 / 2 * s - sum(snake_case__  )

								SCREAMING_SNAKE_CASE_					      =							LinearConstraint(snake_case__					,							0					,							0  )
								SCREAMING_SNAKE_CASE_					      =							Bounds(0					,							self.regularization  )

								SCREAMING_SNAKE_CASE_					      =							minimize(
								    snake_case__					,							np.ones(snake_case__  )					,							bounds=snake_case__					,							constraints=[ly_contraint]  ).x
								SCREAMING_SNAKE_CASE_					      =							l_star

								# calculating mean offset of separation plane to points
								SCREAMING_SNAKE_CASE_					      =							0
								for i in range(snake_case__  ):
										for j in range(snake_case__  ):
												s += classes[i] - classes[i] * self.optimum[i] * self.kernel(
												    observations[i]					,							observations[j]  )
								SCREAMING_SNAKE_CASE_					      =							s / n






						def 	__a					(			self	:   Any					,							snake_case__	:   ndarray  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							sum(
								    self.optimum[n]
								    * self.classes[n]
								    * self.kernel(self.observations[n]					,							snake_case__  )
								    for n in range(len(self.classes  )  )  )
								return 1 if s + self.offset >= 0 else -1


if __name__ == "__main__":
						import doctest

						doctest.testmod()