




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(					_a       ):






    """simple docstring"""





    lowerCAmelCase        =				['''image_processor''']
    lowerCAmelCase        =				'''SamImageProcessor'''





    def __init__(				self       ,_SCREAMING_SNAKE_CASE  )			->		Tuple:
         super().__init__(_snake_case  )
         UpperCAmelCase_      :							Optional[int]       =      self.image_processor
         UpperCAmelCase_      :							str       =      -10
         UpperCAmelCase_      :							Dict       =      self.image_processor.size['''longest_edge''']





    def __call__(				self       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE = None       ,**_SCREAMING_SNAKE_CASE       ,)			->		Tuple:
         UpperCAmelCase_      :							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_      :							int       =      encoding_image_processor['''original_sizes''']

         if hasattr(_snake_case       ,'''numpy'''  ):  # Checks if Torch or TF tensor
              UpperCAmelCase_      :							Dict       =      original_sizes.numpy()

         UpperCAmelCase_,   UpperCAmelCase_,   UpperCAmelCase_      :							Union[str, Any]       =      self._check_and_preprocess_points(
             input_points=_snake_case       ,input_labels=_snake_case       ,input_boxes=_snake_case       ,)

         UpperCAmelCase_      :							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 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE="pt"       ,)			->		List[Any]:


         if input_points is not None:
              if len(_snake_case  ) != len(_snake_case  ):
                   UpperCAmelCase_      :							Optional[Any]       =      [
                       self._normalize_coordinates(self.target_size       ,_snake_case       ,original_sizes[0]  ) for point in input_points
                   ]
              else:
                   UpperCAmelCase_      :							int       =      [
                       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_      :							List[str]       =      self._pad_points_and_labels(_snake_case       ,_snake_case  )

              UpperCAmelCase_      :							Optional[Any]       =      np.array(_snake_case  )

         if input_labels is not None:
              UpperCAmelCase_      :							Tuple       =      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_      :							Union[str, 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_      :							str       =      np.array(_snake_case  )

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

         return encoding_image_processor





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )			->		List[Any]:
         UpperCAmelCase_      :							str       =      max([point.shape[0] for point in input_points]  )
         UpperCAmelCase_      :							Optional[int]       =      []
         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_      :							Optional[int]       =      np.append(input_labels[i]       ,[self.point_pad_value]  )
              processed_input_points.append(_snake_case  )
         UpperCAmelCase_      :							str       =      processed_input_points
         return input_points, input_labels





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE=False  )			->		List[Any]:
         UpperCAmelCase_,   UpperCAmelCase_      :							int       =      original_size
         UpperCAmelCase_,   UpperCAmelCase_      :							List[str]       =      self.image_processor._get_preprocess_shape(_snake_case       ,longest_edge=_snake_case  )
         UpperCAmelCase_      :							Optional[Any]       =      deepcopy(_snake_case  ).astype(_snake_case  )

         if is_bounding_box:
              UpperCAmelCase_      :							List[str]       =      coords.reshape(-1       ,2       ,2  )

         UpperCAmelCase_      :							Dict       =      coords[..., 0] * (new_w / old_w)
         UpperCAmelCase_      :							str       =      coords[..., 1] * (new_h / old_h)

         if is_bounding_box:
              UpperCAmelCase_      :							Union[str, Any]       =      coords.reshape(-1       ,4  )

         return coords





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE=None       ,_SCREAMING_SNAKE_CASE=None       ,)			->		int:


         if input_points is not None:
              if hasattr(_snake_case       ,'''numpy'''  ):  # Checks for TF or Torch tensor
                   UpperCAmelCase_      :							List[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_      :							Tuple       =      [np.array(_snake_case  ) for input_point in input_points]
         else:
              UpperCAmelCase_      :							int       =      None

         if input_labels is not None:
              if hasattr(_snake_case       ,'''numpy'''  ):
                   UpperCAmelCase_      :							Optional[Any]       =      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_      :							List[str]       =      [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[str]       =      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_      :							List[Any]       =      [np.array(_snake_case  ).astype(np.floataa  ) for box in input_boxes]
         else:
              UpperCAmelCase_      :							Any       =      None

         return input_points, input_labels, input_boxes





    @property
    def 							a__				(				self  )			->		List[Any]:
         UpperCAmelCase_      :							Union[str, Any]       =      self.image_processor.model_input_names
         return list(dict.fromkeys(_snake_case  )  )





    def 							a__				(				self       ,*_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )			->		Dict:
         return self.image_processor.post_process_masks(*_snake_case       ,**_snake_case  )





def lowerCamelCase__       (      _lowercase			,						_lowercase				):

     '''simple docstring'''


     return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2







def lowerCamelCase__       (      _lowercase			,						_lowercase=0				):

     '''simple docstring'''


     return sorted(_lowercase			,						key=lambda _lowercase				: x[column]				)







def lowerCamelCase__       (      _lowercase			,						_lowercase			,						_lowercase=float('''inf'''				)				):

     '''simple docstring'''


     for i in range(points_counts - 1				):
          for j in range(i + 1			,						_lowercase				):
               UpperCAmelCase_      :							Optional[int]       =      euclidean_distance_sqr(points[i]			,						points[j]				)
               if current_dis < min_dis:
                    UpperCAmelCase_      :							Optional[Any]       =      current_dis
     return min_dis







def lowerCamelCase__       (      _lowercase			,						_lowercase			,						_lowercase=float('''inf'''				)				):

     '''simple docstring'''


     for i in range(min(6			,						points_counts - 1				)			,						_lowercase				):
          for j in range(max(0			,						i - 6				)			,						_lowercase				):
               UpperCAmelCase_      :							List[str]       =      euclidean_distance_sqr(points[i]			,						points[j]				)
               if current_dis < min_dis:
                    UpperCAmelCase_      :							Optional[int]       =      current_dis
     return min_dis







def lowerCamelCase__       (      _lowercase			,						_lowercase			,						_lowercase				):

     '''simple docstring'''


     if points_counts <= 3:
          return dis_between_closest_pair(_lowercase			,						_lowercase				)

     # recursion
     UpperCAmelCase_      :							Optional[int]       =      points_counts // 2
     UpperCAmelCase_      :							List[Any]       =      closest_pair_of_points_sqr(
         _lowercase			,						points_sorted_on_y[:mid]			,						_lowercase				)
     UpperCAmelCase_      :							Dict       =      closest_pair_of_points_sqr(
         _lowercase			,						points_sorted_on_y[mid:]			,						points_counts - mid				)
     UpperCAmelCase_      :							Union[str, Any]       =      min(_lowercase			,						_lowercase				)
     UpperCAmelCase_      :							str       =      []
     for point in points_sorted_on_x:
          if abs(point[0] - points_sorted_on_x[mid][0]				) < closest_pair_dis:
               cross_strip.append(_lowercase				)

     UpperCAmelCase_      :							Optional[Any]       =      dis_between_closest_in_strip(
         _lowercase			,						len(_lowercase				)			,						_lowercase				)
     return min(_lowercase			,						_lowercase				)







def lowerCamelCase__       (      _lowercase			,						_lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							Tuple       =      column_based_sort(_lowercase			,						column=0				)
     UpperCAmelCase_      :							List[Any]       =      column_based_sort(_lowercase			,						column=1				)
     return (
         closest_pair_of_points_sqr(
             _lowercase			,						_lowercase			,						_lowercase				)
     ) ** 0.5


if __name__ == "__main__":
     __a          =			[(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
     print('Distance:', closest_pair_of_points(points, len(points)))