

'''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 					_snake_case		(__SCREAMING_SNAKE_CASE):
			__A  :	Any        ="owlvit_text_model"






			def __init__(  self			,_snake_case=4_94_08			,_snake_case=5_12			,_snake_case=20_48			,_snake_case=12			,_snake_case=8			,_snake_case=16			,_snake_case="quick_gelu"			,_snake_case=1E-5			,_snake_case=0.0			,_snake_case=0.02			,_snake_case=1.0			,_snake_case=0			,_snake_case=4_94_06			,_snake_case=4_94_07			,**_snake_case			,):
				super().__init__(pad_token_id=_snake_case			,bos_token_id=_snake_case			,eos_token_id=_snake_case			,**_snake_case     )

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






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

				UpperCAmelCase_					,					UpperCAmelCase_     :      Union[str, Any]						=  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":
					UpperCAmelCase_     :      Tuple						=  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 					_snake_case		(__SCREAMING_SNAKE_CASE):
			__A  :	Tuple        ="owlvit_vision_model"






			def __init__(  self			,_snake_case=7_68			,_snake_case=30_72			,_snake_case=12			,_snake_case=12			,_snake_case=3			,_snake_case=7_68			,_snake_case=32			,_snake_case="quick_gelu"			,_snake_case=1E-5			,_snake_case=0.0			,_snake_case=0.02			,_snake_case=1.0			,**_snake_case			,):
				super().__init__(**_snake_case     )

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






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

				UpperCAmelCase_					,					UpperCAmelCase_     :      List[Any]						=  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":
					UpperCAmelCase_     :      Optional[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(_snake_case			,**_snake_case     )




class 					_snake_case		(__SCREAMING_SNAKE_CASE):
			__A  :	Tuple        ="owlvit"
			__A  :	Optional[int]        =True






			def __init__(  self			,_snake_case=None			,_snake_case=None			,_snake_case=5_12			,_snake_case=2.6592			,_snake_case=True			,**_snake_case			,):
				super().__init__(**_snake_case     )

				if text_config is None:
					UpperCAmelCase_     :      Tuple						=  {}
					logger.info("text_config is None. Initializing the OwlViTTextConfig with default values."     )

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

				UpperCAmelCase_     :      Tuple						=  OwlViTTextConfig(**_snake_case     )
				UpperCAmelCase_     :      Optional[int]						=  OwlViTVisionConfig(**_snake_case     )

				UpperCAmelCase_     :      List[Any]						=  projection_dim
				UpperCAmelCase_     :      Union[str, Any]						=  logit_scale_init_value
				UpperCAmelCase_     :      int						=  return_dict
				UpperCAmelCase_     :      Optional[Any]						=  1.0






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

				UpperCAmelCase_					,					UpperCAmelCase_     :      List[Any]						=  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 		UpperCamelCase__							(  cls			,_snake_case			,_snake_case			,**_snake_case     ):
				UpperCAmelCase_     :      Tuple						=  {}
				UpperCAmelCase_     :      List[Any]						=  text_config
				UpperCAmelCase_     :      int						=  vision_config

				return cls.from_dict(_snake_case			,**_snake_case     )






			def 		UpperCamelCase__							(  self     ):
				UpperCAmelCase_     :      str						=  copy.deepcopy(self.__dict__     )
				UpperCAmelCase_     :      Any						=  self.text_config.to_dict()
				UpperCAmelCase_     :      Tuple						=  self.vision_config.to_dict()
				UpperCAmelCase_     :      Union[str, Any]						=  self.__class__.model_type
				return output




class 					_snake_case		(__SCREAMING_SNAKE_CASE):






			@property
			def 		UpperCamelCase__							(  self     ):
				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 		UpperCamelCase__							(  self     ):
				return OrderedDict(
				    [
				        ("logits_per_image", {0: "batch"}),
				        ("logits_per_text", {0: "batch"}),
				        ("text_embeds", {0: "batch"}),
				        ("image_embeds", {0: "batch"}),
				    ]     )






			@property
			def 		UpperCamelCase__							(  self     ):
				return 1E-4






			def 		UpperCamelCase__							(  self			,_snake_case			,_snake_case = -1			,_snake_case = -1			,_snake_case = None			,):
				UpperCAmelCase_     :      str						=  super().generate_dummy_inputs(
				    processor.tokenizer			,batch_size=_snake_case			,seq_length=_snake_case			,framework=_snake_case     )
				UpperCAmelCase_     :      List[Any]						=  super().generate_dummy_inputs(
				    processor.image_processor			,batch_size=_snake_case			,framework=_snake_case     )
				return {**text_input_dict, **image_input_dict}






			@property
			def 		UpperCamelCase__							(  self     ):
				return 14










'''simple docstring'''
import os
from typing import List, Optional, Union

from ...image_processing_utils import BatchFeature
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
from ..auto import AutoTokenizer
class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					_UpperCamelCase							=		["""image_processor""", """tokenizer"""]
					_UpperCamelCase							=		"""BlipImageProcessor"""
					_UpperCamelCase							=		"""AutoTokenizer"""



					def __init__(	self     :						Union[str, Any]      ,       _lowercase     :						Union[str, Any]      ,       _lowercase     :						List[Any]      ,       _lowercase     :						List[str])    ->							Union[str, Any]:
								super().__init__(_lowercase      ,       _lowercase)

								# add QFormer tokenizer
								A_									= qformer_tokenizer



					def __call__(	self     :						Optional[int]      ,       _lowercase     :						ImageInput = None      ,       _lowercase     :						Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None      ,       _lowercase     :						bool = True      ,       _lowercase     :						Union[bool, str, PaddingStrategy] = False      ,       _lowercase     :						Union[bool, str, TruncationStrategy] = None      ,       _lowercase     :						Optional[int] = None      ,       _lowercase     :						int = 0      ,       _lowercase     :						Optional[int] = None      ,       _lowercase     :						Optional[bool] = None      ,       _lowercase     :						bool = False      ,       _lowercase     :						bool = False      ,       _lowercase     :						bool = False      ,       _lowercase     :						bool = False      ,       _lowercase     :						bool = False      ,       _lowercase     :						bool = True      ,       _lowercase     :						Optional[Union[str, TensorType]] = None      ,       **_lowercase     :						List[Any]      ,       )    ->							BatchFeature:
								if images is None and text is None:
											raise ValueError('You have to specify at least images or text.')

								A_									= BatchFeature()

								if text is not None:
											A_									= self.tokenizer(
											    text=_lowercase      ,       add_special_tokens=_lowercase      ,       padding=_lowercase      ,       truncation=_lowercase      ,       max_length=_lowercase      ,       stride=_lowercase      ,       pad_to_multiple_of=_lowercase      ,       return_attention_mask=_lowercase      ,       return_overflowing_tokens=_lowercase      ,       return_special_tokens_mask=_lowercase      ,       return_offsets_mapping=_lowercase      ,       return_token_type_ids=_lowercase      ,       return_length=_lowercase      ,       verbose=_lowercase      ,       return_tensors=_lowercase      ,       **_lowercase      ,       )
											encoding.update(_lowercase)
											A_									= self.qformer_tokenizer(
											    text=_lowercase      ,       add_special_tokens=_lowercase      ,       padding=_lowercase      ,       truncation=_lowercase      ,       max_length=_lowercase      ,       stride=_lowercase      ,       pad_to_multiple_of=_lowercase      ,       return_attention_mask=_lowercase      ,       return_overflowing_tokens=_lowercase      ,       return_special_tokens_mask=_lowercase      ,       return_offsets_mapping=_lowercase      ,       return_token_type_ids=_lowercase      ,       return_length=_lowercase      ,       verbose=_lowercase      ,       return_tensors=_lowercase      ,       **_lowercase      ,       )
											A_									= qformer_text_encoding.pop('input_ids')
											A_									= qformer_text_encoding.pop('attention_mask')

								if images is not None:
											A_									= self.image_processor(_lowercase      ,       return_tensors=_lowercase)
											encoding.update(_lowercase)

								return encoding



					def     __snake_case						(	self     :						List[Any]      ,       *_lowercase     :						Optional[Any]      ,       **_lowercase     :						List[Any])    ->							Union[str, Any]:
								return self.tokenizer.batch_decode(*_lowercase      ,       **_lowercase)



					def     __snake_case						(	self     :						Optional[int]      ,       *_lowercase     :						List[Any]      ,       **_lowercase     :						List[str])    ->							str:
								return self.tokenizer.decode(*_lowercase      ,       **_lowercase)



					@property
					# Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
					def     __snake_case						(	self     :						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))



					def     __snake_case						(	self     :						Optional[Any]      ,       _lowercase     :						Optional[int]      ,       **_lowercase     :						int)    ->							Tuple:
								if os.path.isfile(_lowercase):
											raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file')
								os.makedirs(_lowercase      ,       exist_ok=_lowercase)
								A_									= os.path.join(_lowercase      ,       'qformer_tokenizer')
								self.qformer_tokenizer.save_pretrained(_lowercase)
								return super().save_pretrained(_lowercase      ,       **_lowercase)



					@classmethod
					def     __snake_case						(	cls     :						Dict      ,       _lowercase     :						Dict      ,       **_lowercase     :						int)    ->							Any:
								A_									= AutoTokenizer.from_pretrained(_lowercase      ,       subfolder='qformer_tokenizer')
								A_									= cls._get_arguments_from_pretrained(_lowercase      ,       **_lowercase)
								args.append(_lowercase)
								return cls(*_lowercase)




