



"""simple docstring"""




from copy import deepcopy
from typing import Optional, Union

import numpy as np

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


if is_torch_available():
 import torch

if is_tf_available():
 import tensorflow as tf






class       UpperCAmelCase_    (							_SCREAMING_SNAKE_CASE		):
      __SCREAMING_SNAKE_CASE		:  List[str]						=					["""image_processor"""]
      __SCREAMING_SNAKE_CASE		:  Optional[Any]						=					"""SamImageProcessor"""



      def __init__(	self	:      int	,      A	:      List[Any]		):
           super().__init__(__snake_case		)
           _UpperCAmelCase     :      List[Any]														=       self.image_processor
           _UpperCAmelCase     :      Any														=       -1_0
           _UpperCAmelCase     :      int														=       self.image_processor.size["longest_edge"]



      def __call__(	self	:      int	,      A	:      Dict=None	,      A	:      Optional[Any]=None	,      A	:      str=None	,      A	:      Optional[int]=None	,      A	:      Tuple = None	,      **A	:      int	,      ):
           _UpperCAmelCase     :      Union[str, Any]														=       self.image_processor(
               __snake_case	,      return_tensors=__snake_case	,      **__snake_case	,      )

           # pop arguments that are not used in the foward but used nevertheless
           _UpperCAmelCase     :      Dict														=       encoding_image_processor["original_sizes"]

           if hasattr(__snake_case	,      "numpy"		):  # Checks if Torch or TF tensor
                _UpperCAmelCase     :      Optional[int]														=       original_sizes.numpy()

           _UpperCAmelCase							,			_UpperCAmelCase							,			_UpperCAmelCase     :      List[str]														=       self._check_and_preprocess_points(
               input_points=__snake_case	,      input_labels=__snake_case	,      input_boxes=__snake_case	,      )

           _UpperCAmelCase     :      List[str]														=       self._normalize_and_convert(
               __snake_case	,      __snake_case	,      input_points=__snake_case	,      input_labels=__snake_case	,      input_boxes=__snake_case	,      return_tensors=__snake_case	,      )

           return encoding_image_processor



      def 		snake_case_   (	self	:      Union[str, Any]	,      A	:      List[Any]	,      A	:      List[Any]	,      A	:      Optional[Any]=None	,      A	:      List[Any]=None	,      A	:      Optional[Any]=None	,      A	:      Tuple="pt"	,      ):





           if input_points is not None:
                if len(__snake_case		) != len(__snake_case		):
                     _UpperCAmelCase     :      int														=       [
                         self._normalize_coordinates(self.target_size	,      __snake_case	,      original_sizes[0]		) for point in input_points
                     ]
                else:
                     _UpperCAmelCase     :      Union[str, Any]														=       [
                         self._normalize_coordinates(self.target_size	,      __snake_case	,      __snake_case		)
                         for point, original_size in zip(__snake_case	,      __snake_case		)
                     ]
                # check that all arrays have the same shape
                if not all(point.shape == input_points[0].shape for point in input_points		):
                     if input_labels is not None:
                          _UpperCAmelCase							,			_UpperCAmelCase     :      Dict														=       self._pad_points_and_labels(__snake_case	,      __snake_case		)

                _UpperCAmelCase     :      List[Any]														=       np.array(__snake_case		)

           if input_labels is not None:
                _UpperCAmelCase     :      int														=       np.array(__snake_case		)

           if input_boxes is not None:
                if len(__snake_case		) != len(__snake_case		):
                     _UpperCAmelCase     :      Any														=       [
                         self._normalize_coordinates(self.target_size	,      __snake_case	,      original_sizes[0]	,      is_bounding_box=__snake_case		)
                         for box in input_boxes
                     ]
                else:
                     _UpperCAmelCase     :      Optional[Any]														=       [
                         self._normalize_coordinates(self.target_size	,      __snake_case	,      __snake_case	,      is_bounding_box=__snake_case		)
                         for box, original_size in zip(__snake_case	,      __snake_case		)
                     ]
                _UpperCAmelCase     :      int														=       np.array(__snake_case		)

           if input_boxes is not None:
                if return_tensors == "pt":
                     _UpperCAmelCase     :      Tuple														=       torch.from_numpy(__snake_case		)
                     # boxes batch size of 1 by default
                     _UpperCAmelCase     :      Tuple														=       input_boxes.unsqueeze(1		) if len(input_boxes.shape		) != 3 else input_boxes
                elif return_tensors == "tf":
                     _UpperCAmelCase     :      Union[str, Any]														=       tf.convert_to_tensor(__snake_case		)
                     # boxes batch size of 1 by default
                     _UpperCAmelCase     :      Optional[int]														=       tf.expand_dims(__snake_case	,      1		) if len(input_boxes.shape		) != 3 else input_boxes
                encoding_image_processor.update({"input_boxes": input_boxes}		)
           if input_points is not None:
                if return_tensors == "pt":
                     _UpperCAmelCase     :      List[str]														=       torch.from_numpy(__snake_case		)
                     # point batch size of 1 by default
                     _UpperCAmelCase     :      int														=       input_points.unsqueeze(1		) if len(input_points.shape		) != 4 else input_points
                elif return_tensors == "tf":
                     _UpperCAmelCase     :      Optional[int]														=       tf.convert_to_tensor(__snake_case		)
                     # point batch size of 1 by default
                     _UpperCAmelCase     :      List[Any]														=       tf.expand_dims(__snake_case	,      1		) if len(input_points.shape		) != 4 else input_points
                encoding_image_processor.update({"input_points": input_points}		)
           if input_labels is not None:
                if return_tensors == "pt":
                     _UpperCAmelCase     :      Tuple														=       torch.from_numpy(__snake_case		)
                     # point batch size of 1 by default
                     _UpperCAmelCase     :      Tuple														=       input_labels.unsqueeze(1		) if len(input_labels.shape		) != 3 else input_labels
                elif return_tensors == "tf":
                     _UpperCAmelCase     :      str														=       tf.convert_to_tensor(__snake_case		)
                     # point batch size of 1 by default
                     _UpperCAmelCase     :      int														=       tf.expand_dims(__snake_case	,      1		) if len(input_labels.shape		) != 3 else input_labels
                encoding_image_processor.update({"input_labels": input_labels}		)

           return encoding_image_processor



      def 		snake_case_   (	self	:      Optional[int]	,      A	:      int	,      A	:      Dict		):
           _UpperCAmelCase     :      List[str]														=       max([point.shape[0] for point in input_points]		)
           _UpperCAmelCase     :      Optional[Any]														=       []
           for i, point in enumerate(__snake_case		):
                if point.shape[0] != expected_nb_points:
                     _UpperCAmelCase     :      str														=       np.concatenate(
                         [point, np.zeros((expected_nb_points - point.shape[0], 2)		) + self.point_pad_value]	,      axis=0		)
                     _UpperCAmelCase     :      Any														=       np.append(input_labels[i]	,      [self.point_pad_value]		)
                processed_input_points.append(__snake_case		)
           _UpperCAmelCase     :      Optional[int]														=       processed_input_points
           return input_points, input_labels



      def 		snake_case_   (	self	:      Any	,      A	:      str	,      A	:      List[Any]	,      A	:      Union[str, Any]	,      A	:      Union[str, Any]=False		):
           _UpperCAmelCase							,			_UpperCAmelCase     :      Optional[int]														=       original_size
           _UpperCAmelCase							,			_UpperCAmelCase     :      Optional[Any]														=       self.image_processor._get_preprocess_shape(__snake_case	,      longest_edge=__snake_case		)
           _UpperCAmelCase     :      List[Any]														=       deepcopy(__snake_case		).astype(__snake_case		)

           if is_bounding_box:
                _UpperCAmelCase     :      str														=       coords.reshape(-1	,      2	,      2		)

           _UpperCAmelCase     :      Any														=       coords[..., 0] * (new_w / old_w)
           _UpperCAmelCase     :      List[Any]														=       coords[..., 1] * (new_h / old_h)

           if is_bounding_box:
                _UpperCAmelCase     :      Optional[Any]														=       coords.reshape(-1	,      4		)

           return coords



      def 		snake_case_   (	self	:      List[str]	,      A	:      Union[str, Any]=None	,      A	:      List[Any]=None	,      A	:      Optional[int]=None	,      ):





           if input_points is not None:
                if hasattr(__snake_case	,      "numpy"		):  # Checks for TF or Torch tensor
                     _UpperCAmelCase     :      Optional[Any]														=       input_points.numpy().tolist()

                if not isinstance(__snake_case	,      __snake_case		) or not isinstance(input_points[0]	,      __snake_case		):
                     raise ValueError("Input points must be a list of list of floating points."		)
                _UpperCAmelCase     :      List[Any]														=       [np.array(__snake_case		) for input_point in input_points]
           else:
                _UpperCAmelCase     :      Any														=       None

           if input_labels is not None:
                if hasattr(__snake_case	,      "numpy"		):
                     _UpperCAmelCase     :      Dict														=       input_labels.numpy().tolist()

                if not isinstance(__snake_case	,      __snake_case		) or not isinstance(input_labels[0]	,      __snake_case		):
                     raise ValueError("Input labels must be a list of list integers."		)
                _UpperCAmelCase     :      Optional[int]														=       [np.array(__snake_case		) for label in input_labels]
           else:
                _UpperCAmelCase     :      Union[str, Any]														=       None

           if input_boxes is not None:
                if hasattr(__snake_case	,      "numpy"		):
                     _UpperCAmelCase     :      List[Any]														=       input_boxes.numpy().tolist()

                if (
                    not isinstance(__snake_case	,      __snake_case		)
                    or not isinstance(input_boxes[0]	,      __snake_case		)
                    or not isinstance(input_boxes[0][0]	,      __snake_case		)
                ):
                     raise ValueError("Input boxes must be a list of list of list of floating points."		)
                _UpperCAmelCase     :      Any														=       [np.array(__snake_case		).astype(np.floataa		) for box in input_boxes]
           else:
                _UpperCAmelCase     :      Dict														=       None

           return input_points, input_labels, input_boxes



      @property
      def 		snake_case_   (	self	:      Optional[Any]		):
           _UpperCAmelCase     :      Union[str, Any]														=       self.image_processor.model_input_names
           return list(dict.fromkeys(__snake_case		)		)



      def 		snake_case_   (	self	:      int	,      *A	:      int	,      **A	:      Optional[Any]		):
           return self.image_processor.post_process_masks(*__snake_case	,      **__snake_case		)







from typing import Dict, List, Optional, 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_vision_available, logging


if is_vision_available():
      import PIL


a__      :     Dict         =		logging.get_logger(__name__)





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):
  __lowerCAmelCase   :						Optional[int]							=   ["""pixel_values"""]


  def __init__(							self ,__snake_case = True ,__snake_case = None ,__snake_case = None ,__snake_case = PILImageResampling.BILINEAR ,__snake_case = True ,__snake_case = 1 / 2_5_5 ,__snake_case = True ,__snake_case = None ,__snake_case = None ,**__snake_case ,):



       """simple docstring"""





       super().__init__(**__snake_case )
       A_          =       size if size is not None else {'''shortest_edge''': 3_8_4}
       A_          =       get_size_dict(__snake_case ,default_to_square=__snake_case )

       A_          =       do_resize
       A_          =       size
       # Default value set here for backwards compatibility where the value in config is None
       A_          =       crop_pct if crop_pct is not None else 2_2_4 / 2_5_6
       A_          =       resample
       A_          =       do_rescale
       A_          =       rescale_factor
       A_          =       do_normalize
       A_          =       image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       A_          =       image_std if image_std is not None else IMAGENET_STANDARD_STD


  def 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case ,__snake_case ,__snake_case = PILImageResampling.BICUBIC ,__snake_case = None ,**__snake_case ,):



       """simple docstring"""





       A_          =       get_size_dict(__snake_case ,default_to_square=__snake_case )
       if "shortest_edge" not in size:
            raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' )
       A_          =       size['''shortest_edge''']

       if shortest_edge < 3_8_4:
            # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
            A_          =       int(shortest_edge / crop_pct )
            A_          =       get_resize_output_image_size(__snake_case ,size=__snake_case ,default_to_square=__snake_case )
            A_          =       resize(image=__snake_case ,size=__snake_case ,resample=__snake_case ,data_format=__snake_case ,**__snake_case )
            # then crop to (shortest_edge, shortest_edge)
            return center_crop(image=__snake_case ,size=(shortest_edge, shortest_edge) ,data_format=__snake_case ,**__snake_case )
       else:
            # warping (no cropping) when evaluated at 384 or larger
            return resize(
                __snake_case ,size=(shortest_edge, shortest_edge) ,resample=__snake_case ,data_format=__snake_case ,**__snake_case )


  def 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case ,__snake_case = None ,**__snake_case ,):



       """simple docstring"""





       return rescale(__snake_case ,scale=__snake_case ,data_format=__snake_case ,**__snake_case )


  def 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case ,__snake_case ,__snake_case = None ,**__snake_case ,):



       """simple docstring"""





       return normalize(__snake_case ,mean=__snake_case ,std=__snake_case ,data_format=__snake_case ,**__snake_case )




  def 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = ChannelDimension.FIRST ,**__snake_case ,):



       """simple docstring"""





       A_          =       do_resize if do_resize is not None else self.do_resize
       A_          =       crop_pct if crop_pct is not None else self.crop_pct
       A_          =       resample if resample is not None else self.resample
       A_          =       do_rescale if do_rescale is not None else self.do_rescale
       A_          =       rescale_factor if rescale_factor is not None else self.rescale_factor
       A_          =       do_normalize if do_normalize is not None else self.do_normalize
       A_          =       image_mean if image_mean is not None else self.image_mean
       A_          =       image_std if image_std is not None else self.image_std

       A_          =       size if size is not None else self.size
       A_          =       get_size_dict(__snake_case ,default_to_square=__snake_case )

       A_          =       make_list_of_images(__snake_case )

       if not valid_images(__snake_case ):
            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_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None:
            raise ValueError('''crop_pct must be specified if size < 384.''' )

       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.
       A_          =       [to_numpy_array(__snake_case ) for image in images]

       if do_resize:
            A_          =       [self.resize(image=__snake_case ,size=__snake_case ,crop_pct=__snake_case ,resample=__snake_case ) for image in images]

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

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

       A_          =       [to_channel_dimension_format(__snake_case ,__snake_case ) for image in images]

       A_          =       {'''pixel_values''': images}
       return BatchFeature(data=__snake_case ,tensor_type=__snake_case )



