





'''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


UpperCAmelCase					:		Optional[Any]		=							logging.get_logger(__name__)

UpperCAmelCase					:		List[str]		=							{
    '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						(a__					):
  _lowercase  :	List[str]       					=				"""owlvit_text_model"""







  def __init__(		self     ,     lowercase__=49_408     ,     lowercase__=512     ,     lowercase__=2_048     ,     lowercase__=12     ,     lowercase__=8     ,     lowercase__=16     ,     lowercase__="quick_gelu"     ,     lowercase__=1E-5     ,     lowercase__=0.0     ,     lowercase__=0.02     ,     lowercase__=1.0     ,     lowercase__=0     ,     lowercase__=49_406     ,     lowercase__=49_407     ,     **lowercase__     ,     )		->						Optional[int]:






        """simple docstring"""





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

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







  @classmethod
  def 				UpperCAmelCase_				(		cls     ,     lowercase__     ,     **lowercase__		)		->						"PretrainedConfig":






        """simple docstring"""





        cls._set_token_in_kwargs(lowercase__		)

        _snake_case     ,							_snake_case		:	int					     =     cls.get_config_dict(lowercase__     ,     **lowercase__		)

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





class lowerCamelCase						(a__					):
  _lowercase  :	List[Any]       					=				"""owlvit_vision_model"""







  def __init__(		self     ,     lowercase__=768     ,     lowercase__=3_072     ,     lowercase__=12     ,     lowercase__=12     ,     lowercase__=3     ,     lowercase__=768     ,     lowercase__=32     ,     lowercase__="quick_gelu"     ,     lowercase__=1E-5     ,     lowercase__=0.0     ,     lowercase__=0.02     ,     lowercase__=1.0     ,     **lowercase__     ,     )		->						Tuple:






        """simple docstring"""





        super().__init__(**lowercase__		)

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







  @classmethod
  def 				UpperCAmelCase_				(		cls     ,     lowercase__     ,     **lowercase__		)		->						"PretrainedConfig":






        """simple docstring"""





        cls._set_token_in_kwargs(lowercase__		)

        _snake_case     ,							_snake_case		:	Any					     =     cls.get_config_dict(lowercase__     ,     **lowercase__		)

        # get the vision config dict if we are loading from OwlViTConfig
        if config_dict.get('''model_type'''		) == "owlvit":
              _snake_case		:	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 lowerCamelCase						(a__					):
  _lowercase  :	Dict       					=				"""owlvit"""
  _lowercase  :	Dict       					=				True







  def __init__(		self     ,     lowercase__=None     ,     lowercase__=None     ,     lowercase__=512     ,     lowercase__=2.6_592     ,     lowercase__=True     ,     **lowercase__     ,     )		->						List[str]:






        """simple docstring"""





        super().__init__(**lowercase__		)

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

        if vision_config is None:
              _snake_case		:	List[str]					     =     {}
              logger.info('''vision_config is None. initializing the OwlViTVisionConfig with default values.'''		)

        _snake_case		:	Union[str, Any]					     =     OwlViTTextConfig(**lowercase__		)
        _snake_case		:	Dict					     =     OwlViTVisionConfig(**lowercase__		)

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







  @classmethod
  def 				UpperCAmelCase_				(		cls     ,     lowercase__     ,     **lowercase__		)		->						"PretrainedConfig":






        """simple docstring"""





        cls._set_token_in_kwargs(lowercase__		)

        _snake_case     ,							_snake_case		:	Optional[int]					     =     cls.get_config_dict(lowercase__     ,     **lowercase__		)

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







  @classmethod
  def 				UpperCAmelCase_				(		cls     ,     lowercase__     ,     lowercase__     ,     **lowercase__		)		->						Union[str, Any]:






        """simple docstring"""





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

        return cls.from_dict(lowercase__     ,     **lowercase__		)







  def 				UpperCAmelCase_				(		self		)		->						Tuple:






        """simple docstring"""





        _snake_case		:	int					     =     copy.deepcopy(self.__dict__		)
        _snake_case		:	Tuple					     =     self.text_config.to_dict()
        _snake_case		:	str					     =     self.vision_config.to_dict()
        _snake_case		:	List[str]					     =     self.__class__.model_type
        return output





class lowerCamelCase						(a__					):







  @property
  def 				UpperCAmelCase_				(		self		)		->						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 				UpperCAmelCase_				(		self		)		->						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 				UpperCAmelCase_				(		self		)		->						float:






        """simple docstring"""





        return 1E-4







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__ = -1     ,     lowercase__ = -1     ,     lowercase__ = None     ,     )		->						Mapping[str, Any]:






        """simple docstring"""





        _snake_case		:	str					     =     super().generate_dummy_inputs(
            processor.tokenizer     ,     batch_size=lowercase__     ,     seq_length=lowercase__     ,     framework=lowercase__		)
        _snake_case		:	int					     =     super().generate_dummy_inputs(
            processor.image_processor     ,     batch_size=lowercase__     ,     framework=lowercase__		)
        return {**text_input_dict, **image_input_dict}







  @property
  def 				UpperCAmelCase_				(		self		)		->						int:






        """simple docstring"""





        return 14









'''simple docstring'''

from typing import List, Optional, Union

import numpy as np
import PIL.Image

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


UpperCAmelCase					:		Dict		=							logging.get_logger(__name__)





class lowerCamelCase						(a__					):
  _lowercase  :	int       					=				["""pixel_values"""]







  def __init__(		self     ,     lowercase__ = True     ,     lowercase__ = 32     ,     lowercase__=PILImageResampling.BILINEAR     ,     lowercase__ = True     ,     **lowercase__     ,     )		->						None:






        """simple docstring"""





        _snake_case		:	Any					     =     do_resize
        _snake_case		:	List[str]					     =     do_rescale
        _snake_case		:	Any					     =     size_divisor
        _snake_case		:	Optional[Any]					     =     resample
        super().__init__(**lowercase__		)







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__     ,     lowercase__ = None     ,     **lowercase__		)		->						np.ndarray:






        """simple docstring"""





        _snake_case     ,							_snake_case		:	Dict					     =     get_image_size(lowercase__		)
        # Rounds the height and width down to the closest multiple of size_divisor
        _snake_case		:	Optional[int]					     =     height // size_divisor * size_divisor
        _snake_case		:	Dict					     =     width // size_divisor * size_divisor
        _snake_case		:	str					     =     resize(lowercase__     ,     (new_h, new_w)     ,     resample=lowercase__     ,     data_format=lowercase__     ,     **lowercase__		)
        return image







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__     ,     lowercase__ = None     ,     **lowercase__		)		->						np.ndarray:






        """simple docstring"""





        return rescale(image=lowercase__     ,     scale=lowercase__     ,     data_format=lowercase__     ,     **lowercase__		)







  def 				UpperCAmelCase_				(		self     ,     lowercase__     ,     lowercase__ = None     ,     lowercase__ = None     ,     lowercase__=None     ,     lowercase__ = None     ,     lowercase__ = None     ,     lowercase__ = ChannelDimension.FIRST     ,     **lowercase__     ,     )		->						BatchFeature:






        """simple docstring"""





        _snake_case		:	Any					     =     do_resize if do_resize is not None else self.do_resize
        _snake_case		:	List[Any]					     =     do_rescale if do_rescale is not None else self.do_rescale
        _snake_case		:	List[str]					     =     size_divisor if size_divisor is not None else self.size_divisor
        _snake_case		:	int					     =     resample if resample is not None else self.resample

        if do_resize and size_divisor is None:
              raise ValueError('''size_divisor is required for resizing'''		)

        _snake_case		:	Tuple					     =     make_list_of_images(lowercase__		)

        if not valid_images(lowercase__		):
              raise ValueError('''Invalid image(s)'''		)

        # All transformations expect numpy arrays.
        _snake_case		:	Tuple					     =     [to_numpy_array(lowercase__		) for img in images]

        if do_resize:
              _snake_case		:	Optional[int]					     =     [self.resize(lowercase__     ,     size_divisor=lowercase__     ,     resample=lowercase__		) for image in images]

        if do_rescale:
              _snake_case		:	Union[str, Any]					     =     [self.rescale(lowercase__     ,     scale=1 / 255		) for image in images]

        _snake_case		:	Union[str, Any]					     =     [to_channel_dimension_format(lowercase__     ,     lowercase__		) for image in images]

        _snake_case		:	List[str]					     =     {'''pixel_values''': images}
        return BatchFeature(data=lowercase__     ,     tensor_type=lowercase__		)


