





"""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,
    flip_channel_order,
    get_resize_output_image_size,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging


if is_vision_available():
  import PIL

if is_torch_available():
  import torch


lowerCamelCase__				  =   logging.get_logger(__name__)



class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase   ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:str	     =					["pixel_values"]

  def __init__(		self   :       List[Any]					,   __a   :       bool = True					,   __a   :       Dict[str, int] = None					,   __a   :       PILImageResampling = PILImageResampling.BILINEAR					,   __a   :       bool = True					,   __a   :       Union[int, float] = 1 / 255					,   __a   :       bool = True					,   __a   :       Dict[str, int] = None					,   __a   :       bool = True					,   **__a   :       Any					,   )		->				None:
        super().__init__(**__a	)
        _UpperCamelCase      :	Any						=       size if size is not None else {"shortest_edge": 224}
        _UpperCamelCase      :	List[Any]						=       get_size_dict(__a					,   default_to_square=__a	)
        _UpperCamelCase      :	Optional[Any]						=       crop_size if crop_size is not None else {"height": 256, "width": 256}
        _UpperCamelCase      :	List[Any]						=       get_size_dict(__a					,   param_name="crop_size"	)

        _UpperCamelCase      :	Optional[Any]						=       do_resize
        _UpperCamelCase      :	Optional[Any]						=       size
        _UpperCamelCase      :	str						=       resample
        _UpperCamelCase      :	Optional[Any]						=       do_rescale
        _UpperCamelCase      :	Optional[int]						=       rescale_factor
        _UpperCamelCase      :	List[Any]						=       do_center_crop
        _UpperCamelCase      :	Union[str, Any]						=       crop_size
        _UpperCamelCase      :	Any						=       do_flip_channel_order

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any					,   __a   :       np.ndarray					,   __a   :       Dict[str, int]					,   __a   :       PILImageResampling = PIL.Image.BILINEAR					,   __a   :       Optional[Union[str, ChannelDimension]] = None					,   **__a   :       int					,   )		->				np.ndarray:
        _UpperCamelCase      :	List[Any]						=       get_size_dict(__a					,   default_to_square=__a	)
        if "shortest_edge" not in size:
              raise ValueError(F'''The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}'''	)
        _UpperCamelCase      :	int						=       get_resize_output_image_size(__a					,   size=size["shortest_edge"]					,   default_to_square=__a	)
        return resize(__a					,   size=__a					,   resample=__a					,   data_format=__a					,   **__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Any					,   __a   :       np.ndarray					,   __a   :       Dict[str, int]					,   __a   :       Optional[Union[str, ChannelDimension]] = None					,   **__a   :       Tuple					,   )		->				np.ndarray:
        _UpperCamelCase      :	Union[str, 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()}'''	)
        return center_crop(__a					,   size=(size["height"], size["width"])					,   data_format=__a					,   **__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       Dict					,   __a   :       np.ndarray					,   __a   :       Union[int, float]					,   __a   :       Optional[Union[str, ChannelDimension]] = None					,   **__a   :       Tuple					,   )		->				Tuple:
        return rescale(__a					,   scale=__a					,   data_format=__a					,   **__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       int					,   __a   :       np.ndarray					,   __a   :       Optional[Union[str, ChannelDimension]] = None	)		->				np.ndarray:
        return flip_channel_order(__a					,   data_format=__a	)

  def    __SCREAMING_SNAKE_CASE				(		self   :       int					,   __a   :       ImageInput					,   __a   :       bool = None					,   __a   :       Dict[str, int] = None					,   __a   :       PILImageResampling = None					,   __a   :       bool = None					,   __a   :       float = None					,   __a   :       bool = None					,   __a   :       Dict[str, int] = None					,   __a   :       bool = None					,   __a   :       Optional[Union[str, TensorType]] = None					,   __a   :       ChannelDimension = ChannelDimension.FIRST					,   **__a   :       List[str]					,   )		->				PIL.Image.Image:
        _UpperCamelCase      :	Optional[Any]						=       do_resize if do_resize is not None else self.do_resize
        _UpperCamelCase      :	List[str]						=       resample if resample is not None else self.resample
        _UpperCamelCase      :	Optional[int]						=       do_rescale if do_rescale is not None else self.do_rescale
        _UpperCamelCase      :	Optional[Any]						=       rescale_factor if rescale_factor is not None else self.rescale_factor
        _UpperCamelCase      :	Optional[int]						=       do_center_crop if do_center_crop is not None else self.do_center_crop
        _UpperCamelCase      :	Dict						=       (
            do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
        )

        _UpperCamelCase      :	Union[str, Any]						=       size if size is not None else self.size
        _UpperCamelCase      :	Optional[int]						=       get_size_dict(__a					,   default_to_square=__a	)
        _UpperCamelCase      :	Optional[int]						=       crop_size if crop_size is not None else self.crop_size
        _UpperCamelCase      :	List[Any]						=       get_size_dict(__a					,   param_name="crop_size"	)

        _UpperCamelCase      :	List[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:
              raise ValueError("Size 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_center_crop and crop_size is None:
              raise ValueError("Crop size must be specified if do_center_crop is True."	)

        # All transformations expect numpy arrays.
        _UpperCamelCase      :	Tuple						=       [to_numpy_array(__a	) for image in images]

        if do_resize:
              _UpperCamelCase      :	List[Any]						=       [self.resize(image=__a					,   size=__a					,   resample=__a	) for image in images]

        if do_center_crop:
              _UpperCamelCase      :	Union[str, Any]						=       [self.center_crop(image=__a					,   size=__a	) for image in images]

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

        # the pretrained checkpoints assume images are BGR, not RGB
        if do_flip_channel_order:
              _UpperCamelCase      :	Optional[int]						=       [self.flip_channel_order(image=__a	) for image in images]

        _UpperCamelCase      :	Optional[int]						=       [to_channel_dimension_format(__a					,   __a	) for image in images]

        _UpperCamelCase      :	List[str]						=       {"pixel_values": images}
        return BatchFeature(data=__a					,   tensor_type=__a	)


  def    __SCREAMING_SNAKE_CASE				(		self   :       Union[str, Any]					,   __a   :       List[str]					,   __a   :       List[Tuple] = None	)		->				List[str]:
        _UpperCamelCase      :	Any						=       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	):
                    _UpperCamelCase      :	Any						=       target_sizes.numpy()

              _UpperCamelCase      :	Tuple						=       []

              for idx in range(len(__a	)	):
                    _UpperCamelCase      :	Tuple						=       torch.nn.functional.interpolate(
                        logits[idx].unsqueeze(dim=0	)					,   size=target_sizes[idx]					,   mode="bilinear"					,   align_corners=__a	)
                    _UpperCamelCase      :	Optional[Any]						=       resized_logits[0].argmax(dim=0	)
                    semantic_segmentation.append(__a	)
        else:
              _UpperCamelCase      :	Optional[int]						=       logits.argmax(dim=1	)
              _UpperCamelCase      :	Union[str, Any]						=       [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]	)]

        return semantic_segmentation







"""simple docstring"""


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


lowerCamelCase__				  =   {
    "configuration_owlvit": [
        "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "OwlViTConfig",
        "OwlViTOnnxConfig",
        "OwlViTTextConfig",
        "OwlViTVisionConfig",
    ],
    "processing_owlvit": ["OwlViTProcessor"],
}


try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowerCamelCase__				  =   ["OwlViTFeatureExtractor"]
  lowerCamelCase__				  =   ["OwlViTImageProcessor"]

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowerCamelCase__				  =   [
      "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
      "OwlViTModel",
      "OwlViTPreTrainedModel",
      "OwlViTTextModel",
      "OwlViTVisionModel",
      "OwlViTForObjectDetection",
  ]

if TYPE_CHECKING:
  from .configuration_owlvit import (
      OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
      OwlViTConfig,
      OwlViTOnnxConfig,
      OwlViTTextConfig,
      OwlViTVisionConfig,
  )
  from .processing_owlvit import OwlViTProcessor

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .feature_extraction_owlvit import OwlViTFeatureExtractor
    from .image_processing_owlvit import OwlViTImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_owlvit import (
        OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
        OwlViTForObjectDetection,
        OwlViTModel,
        OwlViTPreTrainedModel,
        OwlViTTextModel,
        OwlViTVisionModel,
    )

else:
  import sys

  lowerCamelCase__				  =   _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
