





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__     ( __snake_case    ):
      _UpperCAmelCase			:str							=     ['image_processor']
      _UpperCAmelCase			:Tuple							=     'SamImageProcessor'





      def __init__(				self ,							A_     ):
       '''simple docstring'''




       super().__init__(A_     )
       UpperCamelCase			:      List[Any] 			=     self.image_processor
       UpperCamelCase			:      Tuple 			=     -10
       UpperCamelCase			:      Optional[int] 			=     self.image_processor.size["longest_edge"]





      def __call__(				self ,							A_=None ,							A_=None ,							A_=None ,							A_=None ,							A_ = None ,							**A_ ,							):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     self.image_processor(
           A_ ,							return_tensors=A_ ,							**A_ ,							)

       # pop arguments that are not used in the foward but used nevertheless
       UpperCamelCase			:      Union[str, Any] 			=     encoding_image_processor["original_sizes"]

       if hasattr(A_ ,							"numpy"     ):  # Checks if Torch or TF tensor
        UpperCamelCase			:      Tuple 			=     original_sizes.numpy()

       UpperCamelCase			,					UpperCamelCase			,					UpperCamelCase			:      Dict 			=     self._check_and_preprocess_points(
           input_points=A_ ,							input_labels=A_ ,							input_boxes=A_ ,							)

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

       return encoding_image_processor





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_=None ,							A_=None ,							A_=None ,							A_="pt" ,							):
       '''simple docstring'''




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

        UpperCamelCase			:      Optional[Any] 			=     np.array(A_     )

       if input_labels is not None:
        UpperCamelCase			:      Optional[Any] 			=     np.array(A_     )

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

       if input_boxes is not None:
        if return_tensors == "pt":
         UpperCamelCase			:      Optional[int] 			=     torch.from_numpy(A_     )
         # boxes batch size of 1 by default
         UpperCamelCase			:      Optional[Any] 			=     input_boxes.unsqueeze(1     ) if len(input_boxes.shape     ) != 3 else input_boxes
        elif return_tensors == "tf":
         UpperCamelCase			:      str 			=     tf.convert_to_tensor(A_     )
         # boxes batch size of 1 by default
         UpperCamelCase			:      Any 			=     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":
         UpperCamelCase			:      int 			=     torch.from_numpy(A_     )
         # 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(A_     )
         # point batch size of 1 by default
         UpperCamelCase			:      Optional[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":
         UpperCamelCase			:      str 			=     torch.from_numpy(A_     )
         # point batch size of 1 by default
         UpperCamelCase			:      Optional[int] 			=     input_labels.unsqueeze(1     ) if len(input_labels.shape     ) != 3 else input_labels
        elif return_tensors == "tf":
         UpperCamelCase			:      Any 			=     tf.convert_to_tensor(A_     )
         # point batch size of 1 by default
         UpperCamelCase			:      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  __UpperCamelCase(				self ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     max([point.shape[0] for point in input_points]     )
       UpperCamelCase			:      List[Any] 			=     []
       for i, point in enumerate(A_     ):
        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			:      Dict 			=     np.append(input_labels[i] ,							[self.point_pad_value]     )
        processed_input_points.append(A_     )
       UpperCamelCase			:      Union[str, Any] 			=     processed_input_points
       return input_points, input_labels





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_ ,							A_=False     ):
       '''simple docstring'''




       UpperCamelCase			,					UpperCamelCase			:      Optional[int] 			=     original_size
       UpperCamelCase			,					UpperCamelCase			:      str 			=     self.image_processor._get_preprocess_shape(A_ ,							longest_edge=A_     )
       UpperCamelCase			:      List[Any] 			=     deepcopy(A_     ).astype(A_     )

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

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

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

       return coords





      def  __UpperCamelCase(				self ,							A_=None ,							A_=None ,							A_=None ,							):
       '''simple docstring'''




       if input_points is not None:
        if hasattr(A_ ,							"numpy"     ):  # Checks for TF or Torch tensor
         UpperCamelCase			:      List[Any] 			=     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."     )
        UpperCamelCase			:      Any 			=     [np.array(A_     ) for input_point in input_points]
       else:
        UpperCamelCase			:      Union[str, Any] 			=     None

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

       if input_boxes is not None:
        if hasattr(A_ ,							"numpy"     ):
         UpperCamelCase			:      Union[str, 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."     )
        UpperCamelCase			:      Optional[int] 			=     [np.array(A_     ).astype(np.floataa     ) for box in input_boxes]
       else:
        UpperCamelCase			:      Dict 			=     None

       return input_points, input_labels, input_boxes





      @property
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[int] 			=     self.image_processor.model_input_names
       return list(dict.fromkeys(A_     )     )





      def  __UpperCamelCase(				self ,							*A_ ,							**A_     ):
       '''simple docstring'''




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







from typing import TYPE_CHECKING

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


__lowerCamelCase :  Union[str, Any]										=  {
    """configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""]
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowerCamelCase :  Dict										=  ["""VisionEncoderDecoderModel"""]

try:
    if not is_tf_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowerCamelCase :  List[str]										=  ["""TFVisionEncoderDecoderModel"""]

try:
    if not is_flax_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowerCamelCase :  int										=  ["""FlaxVisionEncoderDecoderModel"""]

if TYPE_CHECKING:
    from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel

    try:
        if not is_tf_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel

    try:
        if not is_flax_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel

else:
    import sys

    __lowerCamelCase :  str										=  _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
