




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


A     =logging.get_logger(__name__)

A     ={
    '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 			_a  (	__a ):
       __a				:     Optional[int]   				=					"""owlvit_text_model"""
       def __init__(	self						:	Tuple   ,				lowercase						:	Union[str, Any]=49_408   ,				lowercase						:	str=512   ,				lowercase						:	int=2_048   ,				lowercase						:	Optional[Any]=12   ,				lowercase						:	Any=8   ,				lowercase						:	Optional[int]=16   ,				lowercase						:	Union[str, Any]="quick_gelu"   ,				lowercase						:	Dict=1E-5   ,				lowercase						:	Tuple=0.0   ,				lowercase						:	str=0.02   ,				lowercase						:	Dict=1.0   ,				lowercase						:	str=0   ,				lowercase						:	List[str]=49_406   ,				lowercase						:	int=49_407   ,				**lowercase						:	List[Any]   ,				):



           '''simple docstring'''

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

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







       @classmethod
       def     A      (	cls						:	int   ,				lowercase						:	Union[str, os.PathLike]   ,				**lowercase						:	List[Any]				):



           '''simple docstring'''

           cls._set_token_in_kwargs(lowercase				)

           UpperCAmelCase       ,     UpperCAmelCase			       =		cls.get_config_dict(lowercase   ,				**lowercase				)

           # get the text config dict if we are loading from OwlViTConfig
           if config_dict.get('''model_type'''				) == "owlvit":
               UpperCAmelCase			       =		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 			_a  (	__a ):
       __a				:     Dict   				=					"""owlvit_vision_model"""
       def __init__(	self						:	Tuple   ,				lowercase						:	str=768   ,				lowercase						:	Dict=3_072   ,				lowercase						:	int=12   ,				lowercase						:	Tuple=12   ,				lowercase						:	Optional[int]=3   ,				lowercase						:	Optional[int]=768   ,				lowercase						:	Optional[int]=32   ,				lowercase						:	Union[str, Any]="quick_gelu"   ,				lowercase						:	Dict=1E-5   ,				lowercase						:	List[Any]=0.0   ,				lowercase						:	List[Any]=0.02   ,				lowercase						:	str=1.0   ,				**lowercase						:	str   ,				):



           '''simple docstring'''

           super().__init__(**lowercase				)

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







       @classmethod
       def     A      (	cls						:	Optional[Any]   ,				lowercase						:	Union[str, os.PathLike]   ,				**lowercase						:	int				):



           '''simple docstring'''

           cls._set_token_in_kwargs(lowercase				)

           UpperCAmelCase       ,     UpperCAmelCase			       =		cls.get_config_dict(lowercase   ,				**lowercase				)

           # get the vision config dict if we are loading from OwlViTConfig
           if config_dict.get('''model_type'''				) == "owlvit":
               UpperCAmelCase			       =		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  (	__a ):
       __a				:     Dict   				=					"""owlvit"""
       __a				:     Optional[Any]   				=					True
       def __init__(	self						:	Tuple   ,				lowercase						:	Tuple=None   ,				lowercase						:	Optional[Any]=None   ,				lowercase						:	List[str]=512   ,				lowercase						:	Any=2.6592   ,				lowercase						:	List[Any]=True   ,				**lowercase						:	str   ,				):



           '''simple docstring'''

           super().__init__(**lowercase				)

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

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

           UpperCAmelCase			       =		OwlViTTextConfig(**lowercase				)
           UpperCAmelCase			       =		OwlViTVisionConfig(**lowercase				)

           UpperCAmelCase			       =		projection_dim
           UpperCAmelCase			       =		logit_scale_init_value
           UpperCAmelCase			       =		return_dict
           UpperCAmelCase			       =		1.0
       @classmethod
       def     A      (	cls						:	Tuple   ,				lowercase						:	Union[str, os.PathLike]   ,				**lowercase						:	List[str]				):



           '''simple docstring'''

           cls._set_token_in_kwargs(lowercase				)

           UpperCAmelCase       ,     UpperCAmelCase			       =		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     A      (	cls						:	List[str]   ,				lowercase						:	Dict   ,				lowercase						:	Dict   ,				**lowercase						:	Dict				):



           '''simple docstring'''

           UpperCAmelCase			       =		{}
           UpperCAmelCase			       =		text_config
           UpperCAmelCase			       =		vision_config

           return cls.from_dict(lowercase   ,				**lowercase				)







       def     A      (	self						:	Dict				):



           '''simple docstring'''

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






class 			_a  (	__a ):
       @property
       def     A      (	self						:	Optional[Any]				):



           '''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						:	Any				):



           '''simple docstring'''

           return 1E-4
       def     A      (	self						:	Tuple   ,				lowercase						:	"ProcessorMixin"   ,				lowercase						:	int = -1   ,				lowercase						:	int = -1   ,				lowercase						:	Optional["TensorType"] = None   ,				):



           '''simple docstring'''

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







       @property
       def     A      (	self						:	List[Any]				):



           '''simple docstring'''

           return 14










'''simple docstring'''







from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    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_torch_available, is_torch_tensor, logging


if is_torch_available():
   import torch


A     =logging.get_logger(__name__)


class 			_a  (	__a ):
       __a				:     str   				=					["""pixel_values"""]
       def __init__(	self						:	Optional[int]   ,				lowercase						:	bool = True   ,				lowercase						:	Optional[Dict[str, int]] = None   ,				lowercase						:	PILImageResampling = PILImageResampling.BILINEAR   ,				lowercase						:	bool = True   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	bool = True   ,				lowercase						:	Union[int, float] = 1 / 255   ,				lowercase						:	bool = True   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				**lowercase						:	Union[str, Any]   ,				):



           '''simple docstring'''

           super().__init__(**lowercase				)
           UpperCAmelCase			       =		size if size is not None else {'''shortest_edge''': 256}
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           UpperCAmelCase			       =		crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				param_name='''crop_size'''				)
           UpperCAmelCase			       =		do_resize
           UpperCAmelCase			       =		size
           UpperCAmelCase			       =		resample
           UpperCAmelCase			       =		do_center_crop
           UpperCAmelCase			       =		crop_size
           UpperCAmelCase			       =		do_rescale
           UpperCAmelCase			       =		rescale_factor
           UpperCAmelCase			       =		do_normalize
           UpperCAmelCase			       =		image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
           UpperCAmelCase			       =		image_std if image_std is not None else IMAGENET_STANDARD_STD
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Dict[str, int]   ,				lowercase						:	PILImageResampling = PILImageResampling.BICUBIC   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	Any   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           if "shortest_edge" not in size:
               raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"				)
           UpperCAmelCase			       =		get_resize_output_image_size(lowercase   ,				size=size['''shortest_edge''']   ,				default_to_square=lowercase				)
           return resize(lowercase   ,				size=lowercase   ,				resample=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Union[str, Any]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Dict[str, int]   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	int   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		get_size_dict(lowercase				)
           if "height" not in size or "width" not in size:
               raise ValueError(f"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}"				)
           return center_crop(lowercase   ,				size=(size['''height'''], size['''width'''])   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Tuple   ,				lowercase						:	np.ndarray   ,				lowercase						:	float   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	List[str]				):



           '''simple docstring'''

           return rescale(lowercase   ,				scale=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Optional[int]   ,				lowercase						:	np.ndarray   ,				lowercase						:	Union[float, List[float]]   ,				lowercase						:	Union[float, List[float]]   ,				lowercase						:	Optional[Union[str, ChannelDimension]] = None   ,				**lowercase						:	Union[str, Any]   ,				):



           '''simple docstring'''

           return normalize(lowercase   ,				mean=lowercase   ,				std=lowercase   ,				data_format=lowercase   ,				**lowercase				)
       def     A      (	self						:	Optional[int]   ,				lowercase						:	ImageInput   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	PILImageResampling = None   ,				lowercase						:	bool = None   ,				lowercase						:	Dict[str, int] = None   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Optional[float] = None   ,				lowercase						:	Optional[bool] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[float, List[float]]] = None   ,				lowercase						:	Optional[Union[str, TensorType]] = None   ,				lowercase						:	Union[str, ChannelDimension] = ChannelDimension.FIRST   ,				**lowercase						:	Dict   ,				):



           '''simple docstring'''

           UpperCAmelCase			       =		do_resize if do_resize is not None else self.do_resize
           UpperCAmelCase			       =		size if size is not None else self.size
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				default_to_square=lowercase				)
           UpperCAmelCase			       =		resample if resample is not None else self.resample
           UpperCAmelCase			       =		do_center_crop if do_center_crop is not None else self.do_center_crop
           UpperCAmelCase			       =		crop_size if crop_size is not None else self.crop_size
           UpperCAmelCase			       =		get_size_dict(lowercase   ,				param_name='''crop_size'''				)
           UpperCAmelCase			       =		do_rescale if do_rescale is not None else self.do_rescale
           UpperCAmelCase			       =		rescale_factor if rescale_factor is not None else self.rescale_factor
           UpperCAmelCase			       =		do_normalize if do_normalize is not None else self.do_normalize
           UpperCAmelCase			       =		image_mean if image_mean is not None else self.image_mean
           UpperCAmelCase			       =		image_std if image_std is not None else self.image_std

           UpperCAmelCase			       =		make_list_of_images(lowercase				)

           if not valid_images(lowercase				):
               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:
               raise ValueError('''Size 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.
           UpperCAmelCase			       =		[to_numpy_array(lowercase				) for image in images]

           if do_resize:
               UpperCAmelCase			       =		[self.resize(image=lowercase   ,				size=lowercase   ,				resample=lowercase				) for image in images]

           if do_center_crop:
               UpperCAmelCase			       =		[self.center_crop(image=lowercase   ,				size=lowercase				) for image in images]

           if do_rescale:
               UpperCAmelCase			       =		[self.rescale(image=lowercase   ,				scale=lowercase				) for image in images]

           if do_normalize:
               UpperCAmelCase			       =		[self.normalize(image=lowercase   ,				mean=lowercase   ,				std=lowercase				) for image in images]

           UpperCAmelCase			       =		[to_channel_dimension_format(lowercase   ,				lowercase				) for image in images]

           UpperCAmelCase			       =		{'''pixel_values''': images}
           return BatchFeature(data=lowercase   ,				tensor_type=lowercase				)







       def     A      (	self						:	Tuple   ,				lowercase						:	str   ,				lowercase						:	List[Tuple] = None				):



           '''simple docstring'''

           UpperCAmelCase			       =		outputs.logits

           # Resize logits and compute semantic segmentation maps
           if target_sizes is not None:
               if len(lowercase				) != len(lowercase				):
                   raise ValueError(
                       '''Make sure that you pass in as many target sizes as the batch dimension of the logits'''				)

               if is_torch_tensor(lowercase				):
                   UpperCAmelCase			       =		target_sizes.numpy()

               UpperCAmelCase			       =		[]

               for idx in range(len(lowercase				)				):
                   UpperCAmelCase			       =		torch.nn.functional.interpolate(
                       logits[idx].unsqueeze(dim=0				)   ,				size=target_sizes[idx]   ,				mode='''bilinear'''   ,				align_corners=lowercase				)
                   UpperCAmelCase			       =		resized_logits[0].argmax(dim=0				)
                   semantic_segmentation.append(lowercase				)
           else:
               UpperCAmelCase			       =		logits.argmax(dim=1				)
               UpperCAmelCase			       =		[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]				)]

           return semantic_segmentation




