'''simple docstring'''





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

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    is_torch_available,
    is_torch_tensor,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_torch_available():
      import torch

if is_vision_available():
      import PIL


SCREAMING_SNAKE_CASE__		:					List[str]						=					logging.get_logger(__name__)







def     _a				(      lowercase__  :			np.ndarray     ,  lowercase__  :			Union[int, Iterable[int]]     ,  lowercase__  :			bool     ,  lowercase__  :			int ):







     '''simple docstring'''


     def constraint_to_multiple_of(lowercase__  :			Any     ,  lowercase__  :			Optional[Any]     ,  lowercase__  :			List[Any]=0     ,  lowercase__  :			Union[str, Any]=None ):
          SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		round(val / multiple ) * multiple

          if max_val is not None and x > max_val:
               SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		math.floor(val / multiple ) * multiple

          if x < min_val:
               SCREAMING_SNAKE_CASE__				:				Optional[int]			=		math.ceil(val / multiple ) * multiple

          return x

     SCREAMING_SNAKE_CASE__				:				Tuple			=		(output_size, output_size) if isinstance(lowercase__     ,  lowercase__ ) else output_size

     SCREAMING_SNAKE_CASE__				:				Any			=		get_image_size(lowercase__ )
     SCREAMING_SNAKE_CASE__				:				Tuple			=		output_size

     # determine new height and width
     SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		output_height / input_height
     SCREAMING_SNAKE_CASE__				:				List[Any]			=		output_width / input_width

     if keep_aspect_ratio:
          # scale as little as possible
          if abs(1 - scale_width ) < abs(1 - scale_height ):
               # fit width
               SCREAMING_SNAKE_CASE__				:				Optional[int]			=		scale_width
          else:
               # fit height
               SCREAMING_SNAKE_CASE__				:				Tuple			=		scale_height

     SCREAMING_SNAKE_CASE__				:				Optional[int]			=		constraint_to_multiple_of(scale_height * input_height     ,  multiple=lowercase__ )
     SCREAMING_SNAKE_CASE__				:				int			=		constraint_to_multiple_of(scale_width * input_width     ,  multiple=lowercase__ )

     return (new_height, new_width)







class       snake_case					(      UpperCamelCase_						):
  lowercase_			=     ['pixel_values']




  def __init__(      self     :	Tuple     , a_     :	Union[str, Any] = True     , a_     :	int = None     , a_     :	List[str] = PILImageResampling.BILINEAR     , a_     :	Any = False     , a_     :	List[Any] = 1     , a_     :	List[str] = True     , a_     :	int = 1 / 255     , a_     :	List[str] = True     , a_     :	List[str] = None     , a_     :	int = None     , **a_     :	Optional[Any]     , )->       None:




       """simple docstring"""
       super().__init__(**__a				)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		size if size is not None else {'height': 384, 'width': 384}
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		get_size_dict(__a				)
       SCREAMING_SNAKE_CASE__				:				int			=		do_resize
       SCREAMING_SNAKE_CASE__				:				Any			=		size
       SCREAMING_SNAKE_CASE__				:				Any			=		keep_aspect_ratio
       SCREAMING_SNAKE_CASE__				:				int			=		ensure_multiple_of
       SCREAMING_SNAKE_CASE__				:				Dict			=		resample
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		do_rescale
       SCREAMING_SNAKE_CASE__				:				List[str]			=		rescale_factor
       SCREAMING_SNAKE_CASE__				:				int			=		do_normalize
       SCREAMING_SNAKE_CASE__				:				str			=		image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       SCREAMING_SNAKE_CASE__				:				Tuple			=		image_std if image_std is not None else IMAGENET_STANDARD_STD




  def 	__lowercase(      self     :	Optional[int]     , a_     :	Optional[Any]     , a_     :	Dict     , a_     :	List[str] = False     , a_     :	Union[str, Any] = 1     , a_     :	Union[str, Any] = PILImageResampling.BICUBIC     , a_     :	str = None     , **a_     :	int     , )->       np.ndarray:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Any			=		get_size_dict(__a				)
       if "height" not in size or "width" not in size:
            raise ValueError(F'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}'''				)
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		get_resize_output_image_size(
           __a     , output_size=(size['height'], size['width'])     , keep_aspect_ratio=__a     , multiple=__a     , )
       return resize(__a     , size=__a     , resample=__a     , data_format=__a     , **__a				)




  def 	__lowercase(      self     :	Dict     , a_     :	Union[str, Any]     , a_     :	Union[str, Any]     , a_     :	List[Any] = None     , **a_     :	Tuple     , )->       Union[str, Any]:




       """simple docstring"""
       return rescale(__a     , scale=__a     , data_format=__a     , **__a				)




  def 	__lowercase(      self     :	Optional[Any]     , a_     :	Optional[Any]     , a_     :	int     , a_     :	Optional[Any]     , a_     :	List[str] = None     , **a_     :	int     , )->       np.ndarray:




       """simple docstring"""
       return normalize(__a     , mean=__a     , std=__a     , data_format=__a     , **__a				)




  def 	__lowercase(      self     :	Union[str, Any]     , a_     :	int     , a_     :	List[str] = None     , a_     :	Union[str, Any] = None     , a_     :	Dict = None     , a_     :	int = None     , a_     :	Union[str, Any] = None     , a_     :	Optional[Any] = None     , a_     :	str = None     , a_     :	Union[str, Any] = None     , a_     :	Dict = None     , a_     :	Union[str, Any] = None     , a_     :	Optional[int] = None     , a_     :	Optional[Any] = ChannelDimension.FIRST     , **a_     :	List[Any]     , )->       PIL.Image.Image:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		do_resize if do_resize is not None else self.do_resize
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		size if size is not None else self.size
       SCREAMING_SNAKE_CASE__				:				Any			=		get_size_dict(__a				)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
       SCREAMING_SNAKE_CASE__				:				List[str]			=		resample if resample is not None else self.resample
       SCREAMING_SNAKE_CASE__				:				int			=		do_rescale if do_rescale is not None else self.do_rescale
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		rescale_factor if rescale_factor is not None else self.rescale_factor
       SCREAMING_SNAKE_CASE__				:				Dict			=		do_normalize if do_normalize is not None else self.do_normalize
       SCREAMING_SNAKE_CASE__				:				Dict			=		image_mean if image_mean is not None else self.image_mean
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		image_std if image_std is not None else self.image_std

       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		make_list_of_images(__a				)

       if not valid_images(__a				):
            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 or resample is None:
            raise ValueError('Size and resample must be specified if do_resize 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.
       SCREAMING_SNAKE_CASE__				:				Any			=		[to_numpy_array(__a				) for image in images]

       if do_resize:
            SCREAMING_SNAKE_CASE__				:				int			=		[self.resize(image=__a     , size=__a     , resample=__a				) for image in images]

       if do_rescale:
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		[self.rescale(image=__a     , scale=__a				) for image in images]

       if do_normalize:
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		[self.normalize(image=__a     , mean=__a     , std=__a				) for image in images]

       SCREAMING_SNAKE_CASE__				:				List[str]			=		[to_channel_dimension_format(__a     , __a				) for image in images]

       SCREAMING_SNAKE_CASE__				:				Any			=		{'pixel_values': images}
       return BatchFeature(data=__a     , tensor_type=__a				)




  def 	__lowercase(      self     :	Optional[Any]     , a_     :	Optional[Any]     , a_     :	Optional[int] = None				)->       str:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[str]			=		outputs.logits

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

            if is_torch_tensor(__a				):
                 SCREAMING_SNAKE_CASE__				:				int			=		target_sizes.numpy()

            SCREAMING_SNAKE_CASE__				:				List[str]			=		[]

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

       return semantic_segmentation




import warnings
from typing import List

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available

class       snake_case					(      UpperCamelCase_						):
  lowercase_			=     ['image_processor', 'tokenizer']
  lowercase_			=     'OwlViTImageProcessor'
  lowercase_			=     ('CLIPTokenizer', 'CLIPTokenizerFast')




  def __init__(      self     :	List[str]     , a_     :	List[Any]=None     , a_     :	str=None     , **a_     :	Any				)->       Optional[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		None
       if "feature_extractor" in kwargs:
            warnings.warn(
                'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
                ' instead.'     , a_     , )
            SCREAMING_SNAKE_CASE__				:				Tuple			=		kwargs.pop('feature_extractor'				)

       SCREAMING_SNAKE_CASE__				:				List[str]			=		image_processor if image_processor is not None else feature_extractor
       if image_processor is None:
            raise ValueError('You need to specify an `image_processor`.'				)
       if tokenizer is None:
            raise ValueError('You need to specify a `tokenizer`.'				)

       super().__init__(a_     , a_				)




  def __call__(      self     :	Any     , a_     :	Optional[int]=None     , a_     :	Tuple=None     , a_     :	List[Any]=None     , a_     :	Tuple="max_length"     , a_     :	str="np"     , **a_     :	Any				)->       int:




       """simple docstring"""

       if text is None and query_images is None and images is None:
            raise ValueError(
                'You have to specify at least one text or query image or image. All three cannot be none.'				)

       if text is not None:
            if isinstance(a_     , a_				) or (isinstance(a_     , a_				) and not isinstance(text[0]     , a_				)):
                 SCREAMING_SNAKE_CASE__				:				Tuple			=		[self.tokenizer(a_     , padding=a_     , return_tensors=a_     , **a_				)]

            elif isinstance(a_     , a_				) and isinstance(text[0]     , a_				):
                 SCREAMING_SNAKE_CASE__				:				Any			=		[]

                 # Maximum number of queries across batch
                 SCREAMING_SNAKE_CASE__				:				str			=		max([len(a_				) for t in text]				)

                 # Pad all batch samples to max number of text queries
                 for t in text:
                      if len(a_				) != max_num_queries:
                           SCREAMING_SNAKE_CASE__				:				Tuple			=		t + [' '] * (max_num_queries - len(a_				))

                      SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		self.tokenizer(a_     , padding=a_     , return_tensors=a_     , **a_				)
                      encodings.append(a_				)
            else:
                 raise TypeError('Input text should be a string, a list of strings or a nested list of strings'				)

            if return_tensors == "np":
                 SCREAMING_SNAKE_CASE__				:				Dict			=		np.concatenate([encoding['input_ids'] for encoding in encodings]     , axis=0				)
                 SCREAMING_SNAKE_CASE__				:				List[Any]			=		np.concatenate([encoding['attention_mask'] for encoding in encodings]     , axis=0				)

            elif return_tensors == "jax" and is_flax_available():
                 import jax.numpy as jnp

                 SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		jnp.concatenate([encoding['input_ids'] for encoding in encodings]     , axis=0				)
                 SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		jnp.concatenate([encoding['attention_mask'] for encoding in encodings]     , axis=0				)

            elif return_tensors == "pt" and is_torch_available():
                 import torch

                 SCREAMING_SNAKE_CASE__				:				int			=		torch.cat([encoding['input_ids'] for encoding in encodings]     , dim=0				)
                 SCREAMING_SNAKE_CASE__				:				Optional[int]			=		torch.cat([encoding['attention_mask'] for encoding in encodings]     , dim=0				)

            elif return_tensors == "tf" and is_tf_available():
                 import tensorflow as tf

                 SCREAMING_SNAKE_CASE__				:				str			=		tf.stack([encoding['input_ids'] for encoding in encodings]     , axis=0				)
                 SCREAMING_SNAKE_CASE__				:				Dict			=		tf.stack([encoding['attention_mask'] for encoding in encodings]     , axis=0				)

            else:
                 raise ValueError('Target return tensor type could not be returned'				)

            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		BatchEncoding()
            SCREAMING_SNAKE_CASE__				:				List[str]			=		input_ids
            SCREAMING_SNAKE_CASE__				:				Tuple			=		attention_mask

       if query_images is not None:
            SCREAMING_SNAKE_CASE__				:				Any			=		BatchEncoding()
            SCREAMING_SNAKE_CASE__				:				Dict			=		self.image_processor(
                a_     , return_tensors=a_     , **a_				).pixel_values
            SCREAMING_SNAKE_CASE__				:				Dict			=		query_pixel_values

       if images is not None:
            SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.image_processor(a_     , return_tensors=a_     , **a_				)

       if text is not None and images is not None:
            SCREAMING_SNAKE_CASE__				:				Dict			=		image_features.pixel_values
            return encoding
       elif query_images is not None and images is not None:
            SCREAMING_SNAKE_CASE__				:				Optional[int]			=		image_features.pixel_values
            return encoding
       elif text is not None or query_images is not None:
            return encoding
       else:
            return BatchEncoding(data=dict(**a_				)     , tensor_type=a_				)




  def 	__lowercase(      self     :	str     , *a_     :	List[str]     , **a_     :	int				)->       List[Any]:




       """simple docstring"""
       return self.image_processor.post_process(*a_     , **a_				)




  def 	__lowercase(      self     :	Tuple     , *a_     :	List[str]     , **a_     :	str				)->       Union[str, Any]:




       """simple docstring"""
       return self.image_processor.post_process_object_detection(*a_     , **a_				)




  def 	__lowercase(      self     :	Optional[Any]     , *a_     :	str     , **a_     :	Dict				)->       Optional[int]:




       """simple docstring"""
       return self.image_processor.post_process_image_guided_detection(*a_     , **a_				)




  def 	__lowercase(      self     :	Optional[int]     , *a_     :	Tuple     , **a_     :	Tuple				)->       Optional[Any]:




       """simple docstring"""
       return self.tokenizer.batch_decode(*a_     , **a_				)




  def 	__lowercase(      self     :	Tuple     , *a_     :	Tuple     , **a_     :	Tuple				)->       List[str]:




       """simple docstring"""
       return self.tokenizer.decode(*a_     , **a_				)




  @property
  def 	__lowercase(      self     :	Tuple				)->       Any:




       """simple docstring"""
       warnings.warn(
           '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'     , a_     , )
       return self.image_processor_class




  @property
  def 	__lowercase(      self     :	List[Any]				)->       List[str]:




       """simple docstring"""
       warnings.warn(
           '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'     , a_     , )
       return self.image_processor



