


'''simple docstring'''


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


lowerCamelCase__    	=     logging.get_logger(__name__)

lowerCamelCase__    	=     {
    '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 	lowerCAmelCase__			(			UpperCAmelCase__	):
			lowerCAmelCase :	Dict          =     "owlvit_text_model"




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



					'''simple docstring'''







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

					_UpperCAmelCase		:       List[str]								=      vocab_size
					_UpperCAmelCase		:       List[str]								=      hidden_size
					_UpperCAmelCase		:       Optional[int]								=      intermediate_size
					_UpperCAmelCase		:       str								=      num_hidden_layers
					_UpperCAmelCase		:       List[Any]								=      num_attention_heads
					_UpperCAmelCase		:       Dict								=      max_position_embeddings
					_UpperCAmelCase		:       Dict								=      hidden_act
					_UpperCAmelCase		:       Optional[Any]								=      layer_norm_eps
					_UpperCAmelCase		:       Any								=      attention_dropout
					_UpperCAmelCase		:       Tuple								=      initializer_range
					_UpperCAmelCase		:       Optional[Any]								=      initializer_factor






			@classmethod
			def 							lowerCAmelCase__    (		cls  :     int	,  lowerCamelCase__  :     List[str]	,  **lowerCamelCase__  :     Optional[int] )   ->"PretrainedConfig":



					'''simple docstring'''







					cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE )

					_UpperCAmelCase					,    _UpperCAmelCase		:       Tuple								=      cls.get_config_dict(_SCREAMING_SNAKE_CASE	,  **_SCREAMING_SNAKE_CASE )

					# get the text config dict if we are loading from OwlViTConfig
					if config_dict.get("model_type" ) == "owlvit":
							_UpperCAmelCase		:       str								=      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(_SCREAMING_SNAKE_CASE	,  **_SCREAMING_SNAKE_CASE )






class 	lowerCAmelCase__			(			UpperCAmelCase__	):
			lowerCAmelCase :	int          =     "owlvit_vision_model"




			def __init__(		self  :     List[str]	,  lowerCamelCase__  :     Tuple=7_68	,  lowerCamelCase__  :     str=30_72	,  lowerCamelCase__  :     List[str]=12	,  lowerCamelCase__  :     List[Any]=12	,  lowerCamelCase__  :     Any=3	,  lowerCamelCase__  :     Optional[Any]=7_68	,  lowerCamelCase__  :     str=32	,  lowerCamelCase__  :     Optional[int]="quick_gelu"	,  lowerCamelCase__  :     List[Any]=1E-5	,  lowerCamelCase__  :     int=0.0	,  lowerCamelCase__  :     int=0.0_2	,  lowerCamelCase__  :     Any=1.0	,  **lowerCamelCase__  :     Optional[int]	,  )   ->List[Any]:



					'''simple docstring'''







					super().__init__(**_SCREAMING_SNAKE_CASE )

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






			@classmethod
			def 							lowerCAmelCase__    (		cls  :     Tuple	,  lowerCamelCase__  :     Optional[int]	,  **lowerCamelCase__  :     Optional[Any] )   ->"PretrainedConfig":



					'''simple docstring'''







					cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE )

					_UpperCAmelCase					,    _UpperCAmelCase		:       Optional[Any]								=      cls.get_config_dict(_SCREAMING_SNAKE_CASE	,  **_SCREAMING_SNAKE_CASE )

					# get the vision config dict if we are loading from OwlViTConfig
					if config_dict.get("model_type" ) == "owlvit":
							_UpperCAmelCase		:       List[Any]								=      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(_SCREAMING_SNAKE_CASE	,  **_SCREAMING_SNAKE_CASE )






class 	lowerCAmelCase__			(			UpperCAmelCase__	):
			lowerCAmelCase :	Dict          =     "owlvit"
			lowerCAmelCase :	Union[str, Any]          =     True




			def __init__(		self  :     int	,  lowerCamelCase__  :     int=None	,  lowerCamelCase__  :     List[str]=None	,  lowerCamelCase__  :     Optional[Any]=5_12	,  lowerCamelCase__  :     List[Any]=2.6_5_9_2	,  lowerCamelCase__  :     Any=True	,  **lowerCamelCase__  :     Any	,  )   ->List[str]:



					'''simple docstring'''







					super().__init__(**_SCREAMING_SNAKE_CASE )

					if text_config is None:
							_UpperCAmelCase		:       List[str]								=      {}
							logger.info("text_config is None. Initializing the OwlViTTextConfig with default values." )

					if vision_config is None:
							_UpperCAmelCase		:       Dict								=      {}
							logger.info("vision_config is None. initializing the OwlViTVisionConfig with default values." )

					_UpperCAmelCase		:       Union[str, Any]								=      OwlViTTextConfig(**_SCREAMING_SNAKE_CASE )
					_UpperCAmelCase		:       Optional[Any]								=      OwlViTVisionConfig(**_SCREAMING_SNAKE_CASE )

					_UpperCAmelCase		:       int								=      projection_dim
					_UpperCAmelCase		:       int								=      logit_scale_init_value
					_UpperCAmelCase		:       str								=      return_dict
					_UpperCAmelCase		:       Dict								=      1.0




			@classmethod
			def 							lowerCAmelCase__    (		cls  :     Optional[Any]	,  lowerCamelCase__  :     str	,  **lowerCamelCase__  :     List[str] )   ->"PretrainedConfig":



					'''simple docstring'''







					cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE )

					_UpperCAmelCase					,    _UpperCAmelCase		:       int								=      cls.get_config_dict(_SCREAMING_SNAKE_CASE	,  **_SCREAMING_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(_SCREAMING_SNAKE_CASE	,  **_SCREAMING_SNAKE_CASE )




			@classmethod
			def 							lowerCAmelCase__    (		cls  :     Union[str, Any]	,  lowerCamelCase__  :     Dict	,  lowerCamelCase__  :     List[Any]	,  **lowerCamelCase__  :     List[Any] )   ->str:



					'''simple docstring'''







					_UpperCAmelCase		:       Optional[Any]								=      {}
					_UpperCAmelCase		:       int								=      text_config
					_UpperCAmelCase		:       List[str]								=      vision_config

					return cls.from_dict(_SCREAMING_SNAKE_CASE	,  **_SCREAMING_SNAKE_CASE )






			def 							lowerCAmelCase__    (		self  :     Any )   ->Optional[int]:



					'''simple docstring'''







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






class 	lowerCAmelCase__			(			UpperCAmelCase__	):




			@property
			def 							lowerCAmelCase__    (		self  :     Optional[Any] )   ->Mapping[str, Mapping[int, 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 							lowerCAmelCase__    (		self  :     List[str] )   ->Mapping[str, Mapping[int, 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 							lowerCAmelCase__    (		self  :     Tuple )   ->float:



					'''simple docstring'''







					return 1E-4




			def 							lowerCAmelCase__    (		self  :     Optional[Any]	,  lowerCamelCase__  :     List[str]	,  lowerCamelCase__  :     int = -1	,  lowerCamelCase__  :     str = -1	,  lowerCamelCase__  :     int = None	,  )   ->Mapping[str, Any]:



					'''simple docstring'''







					_UpperCAmelCase		:       Any								=      super().generate_dummy_inputs(
					    processor.tokenizer	,  batch_size=_SCREAMING_SNAKE_CASE	,  seq_length=_SCREAMING_SNAKE_CASE	,  framework=_SCREAMING_SNAKE_CASE )
					_UpperCAmelCase		:       str								=      super().generate_dummy_inputs(
					    processor.image_processor	,  batch_size=_SCREAMING_SNAKE_CASE	,  framework=_SCREAMING_SNAKE_CASE )
					return {**text_input_dict, **image_input_dict}






			@property
			def 							lowerCAmelCase__    (		self  :     Any )   ->int:



					'''simple docstring'''







					return 14







'''simple docstring'''


from __future__ import annotations

import math

import numpy as np
from numpy.linalg import norm






def  __lowerCAmelCase (__lowerCAmelCase      , __lowerCAmelCase   ):
		return math.sqrt(sum(pow(a - b      , 2   ) for a, b in zip(__lowerCAmelCase      , __lowerCAmelCase   )   )   )






def  __lowerCAmelCase (__lowerCAmelCase      , __lowerCAmelCase   ):

		if dataset.ndim != value_array.ndim:
				_UpperCAmelCase		:       Optional[Any]								=      (
				    "Wrong input data's dimensions... "
				    F"""dataset : {dataset.ndim}, value_array : {value_array.ndim}"""
				)
				raise ValueError(__lowerCAmelCase   )

		try:
				if dataset.shape[1] != value_array.shape[1]:
						_UpperCAmelCase		:       Optional[int]								=      (
						    "Wrong input data's shape... "
						    F"""dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}"""
						)
						raise ValueError(__lowerCAmelCase   )
		except IndexError:
				if dataset.ndim != value_array.ndim:
						raise TypeError("Wrong shape"   )

		if dataset.dtype != value_array.dtype:
				_UpperCAmelCase		:       Union[str, Any]								=      (
				    "Input data have different datatype... "
				    F"""dataset : {dataset.dtype}, value_array : {value_array.dtype}"""
				)
				raise TypeError(__lowerCAmelCase   )

		_UpperCAmelCase		:       Optional[int]								=      []

		for value in value_array:
				_UpperCAmelCase		:       List[str]								=      euclidean(__lowerCAmelCase      , dataset[0]   )
				_UpperCAmelCase		:       Dict								=      dataset[0].tolist()

				for dataset_value in dataset[1:]:
						_UpperCAmelCase		:       int								=      euclidean(__lowerCAmelCase      , __lowerCAmelCase   )

						if dist > temp_dist:
								_UpperCAmelCase		:       Tuple								=      temp_dist
								_UpperCAmelCase		:       Dict								=      dataset_value.tolist()

				answer.append([vector, dist]   )

		return answer






def  __lowerCAmelCase (__lowerCAmelCase      , __lowerCAmelCase   ):
		return np.dot(__lowerCAmelCase      , __lowerCAmelCase   ) / (norm(__lowerCAmelCase   ) * norm(__lowerCAmelCase   ))


if __name__ == "__main__":
						import doctest

						doctest.testmod()



