






'''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 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     int   		=			['image_processor']
       snake_case__    :     List[str]   		=			'SamImageProcessor'




       def __init__(					self      : int	,    A__      : Any					):


            """simple docstring"""







            super().__init__(A__					)
            __lowerCamelCase						:       Optional[Any]				   =				self.image_processor
            __lowerCamelCase						:       List[Any]				   =				-10
            __lowerCamelCase						:       str				   =				self.image_processor.size["""longest_edge"""]




       def __call__(					self      : Union[str, Any]	,    A__      : Optional[int]=None	,    A__      : Union[str, Any]=None	,    A__      : Any=None	,    A__      : Optional[Any]=None	,    A__      : Optional[Union[str, TensorType]] = None	,    **A__      : Optional[int]	,    ):


            """simple docstring"""







            __lowerCamelCase						:       Tuple				   =				self.image_processor(
                A__	,    return_tensors=A__	,    **A__	,    )

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

            if hasattr(A__	,    """numpy"""					):  # Checks if Torch or TF tensor
                 __lowerCamelCase						:       List[Any]				   =				original_sizes.numpy()

            __lowerCamelCase						:       Optional[Any]				   =				self._check_and_preprocess_points(
                input_points=A__	,    input_labels=A__	,    input_boxes=A__	,    )

            __lowerCamelCase						:       Union[str, Any]				   =				self._normalize_and_convert(
                A__	,    A__	,    input_points=A__	,    input_labels=A__	,    input_boxes=A__	,    return_tensors=A__	,    )

            return encoding_image_processor




       def 					a_					(					self      : List[str]	,    A__      : List[Any]	,    A__      : Union[str, Any]	,    A__      : List[Any]=None	,    A__      : List[str]=None	,    A__      : int=None	,    A__      : Optional[Any]="pt"	,    ):


            """simple docstring"""







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

                 __lowerCamelCase						:       int				   =				np.array(A__					)

            if input_labels is not None:
                 __lowerCamelCase						:       int				   =				np.array(A__					)

            if input_boxes is not None:
                 if len(A__					) != len(A__					):
                      __lowerCamelCase						:       Optional[Any]				   =				[
                          self._normalize_coordinates(self.target_size	,    A__	,    original_sizes[0]	,    is_bounding_box=A__					)
                          for box in input_boxes
                      ]
                 else:
                      __lowerCamelCase						:       List[str]				   =				[
                          self._normalize_coordinates(self.target_size	,    A__	,    A__	,    is_bounding_box=A__					)
                          for box, original_size in zip(A__	,    A__					)
                      ]
                 __lowerCamelCase						:       Tuple				   =				np.array(A__					)

            if input_boxes is not None:
                 if return_tensors == "pt":
                      __lowerCamelCase						:       str				   =				torch.from_numpy(A__					)
                      # boxes batch size of 1 by default
                      __lowerCamelCase						:       Optional[int]				   =				input_boxes.unsqueeze(1					) if len(input_boxes.shape					) != 3 else input_boxes
                 elif return_tensors == "tf":
                      __lowerCamelCase						:       Any				   =				tf.convert_to_tensor(A__					)
                      # boxes batch size of 1 by default
                      __lowerCamelCase						:       str				   =				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":
                      __lowerCamelCase						:       Dict				   =				torch.from_numpy(A__					)
                      # point batch size of 1 by default
                      __lowerCamelCase						:       Union[str, Any]				   =				input_points.unsqueeze(1					) if len(input_points.shape					) != 4 else input_points
                 elif return_tensors == "tf":
                      __lowerCamelCase						:       Optional[int]				   =				tf.convert_to_tensor(A__					)
                      # point batch size of 1 by default
                      __lowerCamelCase						:       Any				   =				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":
                      __lowerCamelCase						:       Union[str, Any]				   =				torch.from_numpy(A__					)
                      # point batch size of 1 by default
                      __lowerCamelCase						:       Any				   =				input_labels.unsqueeze(1					) if len(input_labels.shape					) != 3 else input_labels
                 elif return_tensors == "tf":
                      __lowerCamelCase						:       List[Any]				   =				tf.convert_to_tensor(A__					)
                      # point batch size of 1 by default
                      __lowerCamelCase						:       Dict				   =				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 					a_					(					self      : Optional[Any]	,    A__      : List[str]	,    A__      : str					):


            """simple docstring"""







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




       def 					a_					(					self      : Dict	,    A__      : int	,    A__      : np.ndarray	,    A__      : Any	,    A__      : Dict=False					):


            """simple docstring"""







            __lowerCamelCase						:       List[Any]				   =				original_size
            __lowerCamelCase						:       List[str]				   =				self.image_processor._get_preprocess_shape(A__	,    longest_edge=A__					)
            __lowerCamelCase						:       Tuple				   =				deepcopy(A__					).astype(A__					)

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

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

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

            return coords




       def 					a_					(					self      : List[Any]	,    A__      : Optional[Any]=None	,    A__      : str=None	,    A__      : List[Any]=None	,    ):


            """simple docstring"""







            if input_points is not None:
                 if hasattr(A__	,    """numpy"""					):  # Checks for TF or Torch tensor
                      __lowerCamelCase						:       Optional[int]				   =				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."""					)
                 __lowerCamelCase						:       Dict				   =				[np.array(A__					) for input_point in input_points]
            else:
                 __lowerCamelCase						:       int				   =				None

            if input_labels is not None:
                 if hasattr(A__	,    """numpy"""					):
                      __lowerCamelCase						:       Optional[int]				   =				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."""					)
                 __lowerCamelCase						:       List[str]				   =				[np.array(A__					) for label in input_labels]
            else:
                 __lowerCamelCase						:       Union[str, Any]				   =				None

            if input_boxes is not None:
                 if hasattr(A__	,    """numpy"""					):
                      __lowerCamelCase						:       List[Any]				   =				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."""					)
                 __lowerCamelCase						:       Union[str, Any]				   =				[np.array(A__					).astype(np.floataa					) for box in input_boxes]
            else:
                 __lowerCamelCase						:       str				   =				None

            return input_points, input_labels, input_boxes




       @property
       def 					a_					(					self      : Optional[Any]					):


            """simple docstring"""







            __lowerCamelCase						:       Tuple				   =				self.image_processor.model_input_names
            return list(dict.fromkeys(A__					)					)




       def 					a_					(					self      : Optional[Any]	,    *A__      : Optional[int]	,    **A__      : int					):


            """simple docstring"""







            return self.image_processor.post_process_masks(*A__	,    **A__					)











'''simple docstring'''

from ..utils import DummyObject, requires_backends







class 	SCREAMING_SNAKE_CASE	(      metaclass=lowerCAmelCase_  ):
       snake_case__    :     Union[str, Any]   		=			['torch', 'torchsde']




       def __init__(					self      : int	,    *A__      : Optional[Any]	,    **A__      : Dict					):


            """simple docstring"""







            requires_backends(self	,    ["""torch""", """torchsde"""]					)




       @classmethod
       def 					a_					(					cls      : Optional[Any]	,    *A__      : str	,    **A__      : Optional[Any]					):


            """simple docstring"""







            requires_backends(cls	,    ["""torch""", """torchsde"""]					)




       @classmethod
       def 					a_					(					cls      : Union[str, Any]	,    *A__      : Any	,    **A__      : Union[str, Any]					):


            """simple docstring"""







            requires_backends(cls	,    ["""torch""", """torchsde"""]					)



