"""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      _A	(						_UpperCAmelCase					):




    """simple docstring"""




    UpperCamelCase_	:					Tuple							=					['''image_processor''']
    UpperCamelCase_	:					Optional[int]							=					'''SamImageProcessor'''
    def __init__(		self							:     Any	,      A_							:     Optional[Any]    )    ->       Dict:
         super().__init__(A_    )
         __snake_case				=							self.image_processor
         __snake_case				=							-10
         __snake_case				=							self.image_processor.size['''longest_edge''']
    def __call__(		self							:     Union[str, Any]	,      A_							:     List[Any]=None	,      A_							:     str=None	,      A_							:     Optional[int]=None	,      A_							:     List[str]=None	,      A_							:     Optional[Union[str, TensorType]] = None	,      **A_							:     Optional[int]	,      )    ->       BatchEncoding:
         __snake_case				=							self.image_processor(
             A_	,      return_tensors=A_	,      **A_	,      )

         # pop arguments that are not used in the foward but used nevertheless
         __snake_case				=							encoding_image_processor['''original_sizes''']

         if hasattr(A_	,      '''numpy'''    ):  # Checks if Torch or TF tensor
              __snake_case				=							original_sizes.numpy()

         __snake_case		,	__snake_case		,	__snake_case				=							self._check_and_preprocess_points(
             input_points=A_	,      input_labels=A_	,      input_boxes=A_	,      )

         __snake_case				=							self._normalize_and_convert(
             A_	,      A_	,      input_points=A_	,      input_labels=A_	,      input_boxes=A_	,      return_tensors=A_	,      )

         return encoding_image_processor
    def  lowercase					(		self							:     List[Any]	,      A_							:     Union[str, Any]	,      A_							:     str	,      A_							:     Tuple=None	,      A_							:     List[Any]=None	,      A_							:     Dict=None	,      A_							:     List[Any]="pt"	,      )    ->       Dict:
         if input_points is not None:
              if len(A_    ) != len(A_    ):
                   __snake_case				=							[
                       self._normalize_coordinates(self.target_size	,      A_	,      original_sizes[0]    ) for point in input_points
                   ]
              else:
                   __snake_case				=							[
                       self._normalize_coordinates(self.target_size	,      A_	,      A_    )
                       for point, original_size in zip(A_	,      A_    )
                   ]
              # 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:
                        __snake_case		,	__snake_case				=							self._pad_points_and_labels(A_	,      A_    )

              __snake_case				=							np.array(A_    )

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

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

         if input_boxes is not None:
              if return_tensors == "pt":
                   __snake_case				=							torch.from_numpy(A_    )
                   # boxes batch size of 1 by default
                   __snake_case				=							input_boxes.unsqueeze(1    ) if len(input_boxes.shape    ) != 3 else input_boxes
              elif return_tensors == "tf":
                   __snake_case				=							tf.convert_to_tensor(A_    )
                   # boxes batch size of 1 by default
                   __snake_case				=							tf.expand_dims(A_	,      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":
                   __snake_case				=							torch.from_numpy(A_    )
                   # point batch size of 1 by default
                   __snake_case				=							input_points.unsqueeze(1    ) if len(input_points.shape    ) != 4 else input_points
              elif return_tensors == "tf":
                   __snake_case				=							tf.convert_to_tensor(A_    )
                   # point batch size of 1 by default
                   __snake_case				=							tf.expand_dims(A_	,      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":
                   __snake_case				=							torch.from_numpy(A_    )
                   # point batch size of 1 by default
                   __snake_case				=							input_labels.unsqueeze(1    ) if len(input_labels.shape    ) != 3 else input_labels
              elif return_tensors == "tf":
                   __snake_case				=							tf.convert_to_tensor(A_    )
                   # point batch size of 1 by default
                   __snake_case				=							tf.expand_dims(A_	,      1    ) if len(input_labels.shape    ) != 3 else input_labels
              encoding_image_processor.update({'''input_labels''': input_labels}    )

         return encoding_image_processor
    def  lowercase					(		self							:     str	,      A_							:     Tuple	,      A_							:     int    )    ->       Union[str, Any]:
         __snake_case				=							max([point.shape[0] for point in input_points]    )
         __snake_case				=							[]
         for i, point in enumerate(A_    ):
              if point.shape[0] != expected_nb_points:
                   __snake_case				=							np.concatenate(
                       [point, np.zeros((expected_nb_points - point.shape[0], 2)    ) + self.point_pad_value]	,      axis=0    )
                   __snake_case				=							np.append(input_labels[i]	,      [self.point_pad_value]    )
              processed_input_points.append(A_    )
         __snake_case				=							processed_input_points
         return input_points, input_labels
    def  lowercase					(		self							:     Optional[int]	,      A_							:     int	,      A_							:     np.ndarray	,      A_							:     int	,      A_							:     Optional[Any]=False    )    ->       np.ndarray:
         __snake_case		,	__snake_case				=							original_size
         __snake_case		,	__snake_case				=							self.image_processor._get_preprocess_shape(A_	,      longest_edge=A_    )
         __snake_case				=							deepcopy(A_    ).astype(A_    )

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

         __snake_case				=							coords[..., 0] * (new_w / old_w)
         __snake_case				=							coords[..., 1] * (new_h / old_h)

         if is_bounding_box:
              __snake_case				=							coords.reshape(-1	,      4    )

         return coords
    def  lowercase					(		self							:     Any	,      A_							:     Union[str, Any]=None	,      A_							:     Union[str, Any]=None	,      A_							:     List[str]=None	,      )    ->       int:
         if input_points is not None:
              if hasattr(A_	,      '''numpy'''    ):  # Checks for TF or Torch tensor
                   __snake_case				=							input_points.numpy().tolist()

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

         if input_labels is not None:
              if hasattr(A_	,      '''numpy'''    ):
                   __snake_case				=							input_labels.numpy().tolist()

              if not isinstance(A_	,      A_    ) or not isinstance(input_labels[0]	,      A_    ):
                   raise ValueError('''Input labels must be a list of list integers.'''    )
              __snake_case				=							[np.array(A_    ) for label in input_labels]
         else:
              __snake_case				=							None

         if input_boxes is not None:
              if hasattr(A_	,      '''numpy'''    ):
                   __snake_case				=							input_boxes.numpy().tolist()

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

         return input_points, input_labels, input_boxes
    @property
    def  lowercase					(		self							:     Optional[Any]    )    ->       Union[str, Any]:
         __snake_case				=							self.image_processor.model_input_names
         return list(dict.fromkeys(A_    )    )







    def  lowercase					(		self							:     str	,      *A_							:     List[Any]	,      **A_							:     int    )    ->       List[Any]:
         return self.image_processor.post_process_masks(*A_	,      **A_    )
"""simple docstring"""



from typing import Dict, Iterable, 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_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


__lowercase		:		str														=							logging.get_logger(__name__)



class      _A	(						_UpperCAmelCase					):




    """simple docstring"""




    UpperCamelCase_	:					str							=					['''pixel_values''']
    def __init__(		self							:     Optional[int]	,      A_							:     bool = True	,      A_							:     Dict[str, int] = None	,      A_							:     PILImageResampling = PILImageResampling.BICUBIC	,      A_							:     bool = True	,      A_							:     Dict[str, int] = None	,      A_							:     bool = True	,      A_							:     Union[int, float] = 1 / 255	,      A_							:     bool = True	,      A_							:     Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN	,      A_							:     Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD	,      **A_							:     Dict	,      )    ->       None:
         super().__init__(**A_    )
         __snake_case				=							size if size is not None else {'''shortest_edge''': 224}
         __snake_case				=							get_size_dict(A_	,      default_to_square=A_    )
         __snake_case				=							crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
         __snake_case				=							get_size_dict(A_	,      param_name='''crop_size'''    )

         __snake_case				=							do_resize
         __snake_case				=							size
         __snake_case				=							resample
         __snake_case				=							do_center_crop
         __snake_case				=							crop_size
         __snake_case				=							do_rescale
         __snake_case				=							rescale_factor
         __snake_case				=							do_normalize
         __snake_case				=							image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
         __snake_case				=							image_std if image_std is not None else IMAGENET_DEFAULT_STD
    def  lowercase					(		self							:     Any	,      A_							:     np.ndarray	,      A_							:     Dict[str, int]	,      A_							:     PILImageResampling = PILImageResampling.BICUBIC	,      A_							:     Optional[Union[str, ChannelDimension]] = None	,      **A_							:     int	,      )    ->       np.ndarray:
         __snake_case				=							get_size_dict(A_	,      default_to_square=A_    )
         # size_dict is a dict with either keys "height" and "width" or "shortest_edge"
         if "shortest_edge" in size:
              __snake_case				=							int((256 / 224) * size['''shortest_edge''']    )
              __snake_case				=							get_resize_output_image_size(A_	,      size=A_	,      default_to_square=A_    )
              __snake_case				=							{'''height''': output_size[0], '''width''': output_size[1]}
         if "height" not in size_dict or "width" not in size_dict:
              raise ValueError(
                  f"Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}"    )
         return resize(
             A_	,      size=(size_dict['''height'''], size_dict['''width'''])	,      resample=A_	,      data_format=A_	,      **A_    )
    def  lowercase					(		self							:     Any	,      A_							:     np.ndarray	,      A_							:     Dict[str, int]	,      A_							:     Optional[Union[str, ChannelDimension]] = None	,      **A_							:     List[Any]	,      )    ->       np.ndarray:
         __snake_case				=							get_size_dict(A_    )
         if "height" not in size or "width" not in size:
              raise ValueError(f"Size dict must have keys 'height' and 'width'. Got {size.keys()}"    )
         return center_crop(A_	,      size=(size['''height'''], size['''width'''])	,      data_format=A_	,      **A_    )
    def  lowercase					(		self							:     List[str]	,      A_							:     np.ndarray	,      A_							:     Union[int, float]	,      A_							:     Optional[Union[str, ChannelDimension]] = None	,      **A_							:     Optional[Any]	,      )    ->       np.ndarray:
         return rescale(A_	,      scale=A_	,      data_format=A_	,      **A_    )
    def  lowercase					(		self							:     Dict	,      A_							:     np.ndarray	,      A_							:     Union[float, List[float]]	,      A_							:     Union[float, List[float]]	,      A_							:     Optional[Union[str, ChannelDimension]] = None	,      **A_							:     Optional[int]	,      )    ->       np.ndarray:
         return normalize(A_	,      mean=A_	,      std=A_	,      data_format=A_	,      **A_    )







    def  lowercase					(		self							:     Union[str, Any]	,      A_							:     ImageInput	,      A_							:     Optional[bool] = None	,      A_							:     Optional[Dict[str, int]] = None	,      A_							:     PILImageResampling = None	,      A_							:     Optional[bool] = None	,      A_							:     Optional[Dict[str, int]] = None	,      A_							:     Optional[bool] = None	,      A_							:     Optional[float] = None	,      A_							:     Optional[bool] = None	,      A_							:     Optional[Union[float, Iterable[float]]] = None	,      A_							:     Optional[Union[float, Iterable[float]]] = None	,      A_							:     Optional[TensorType] = None	,      A_							:     ChannelDimension = ChannelDimension.FIRST	,      **A_							:     Any	,      )    ->       BatchFeature:
         __snake_case				=							do_resize if do_resize is not None else self.do_resize
         __snake_case				=							resample if resample is not None else self.resample
         __snake_case				=							do_center_crop if do_center_crop is not None else self.do_center_crop
         __snake_case				=							do_rescale if do_rescale is not None else self.do_rescale
         __snake_case				=							rescale_factor if rescale_factor is not None else self.rescale_factor
         __snake_case				=							do_normalize if do_normalize is not None else self.do_normalize
         __snake_case				=							image_mean if image_mean is not None else self.image_mean
         __snake_case				=							image_std if image_std is not None else self.image_std

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

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

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

         if do_center_crop:
              __snake_case				=							[self.center_crop(A_	,      A_    ) for image in images]

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

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

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

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