"""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					(		lowerCAmelCase_ ):
    _snake_case  :	List[Any]  				=				['image_processor']
    _snake_case  :	Union[str, Any]  				=				'SamImageProcessor'


    def __init__(       self						:	Union[str, Any] ,					__lowerCAmelCase						:	Optional[int]       ):
      super().__init__(__lowerCAmelCase       )
      _UpperCAmelCase    			=   self.image_processor
      _UpperCAmelCase    			=   -10
      _UpperCAmelCase    			=   self.image_processor.size["""longest_edge"""]


    def __call__(       self						:	int ,					__lowerCAmelCase						:	int=None ,					__lowerCAmelCase						:	List[Any]=None ,					__lowerCAmelCase						:	Optional[Any]=None ,					__lowerCAmelCase						:	Optional[int]=None ,					__lowerCAmelCase						:	Optional[Union[str, TensorType]] = None ,					**__lowerCAmelCase						:	List[Any] ,					):
      _UpperCAmelCase    			=   self.image_processor(
          __lowerCAmelCase ,					return_tensors=__lowerCAmelCase ,					**__lowerCAmelCase ,					)

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

      if hasattr(__lowerCAmelCase ,					"""numpy"""       ):  # Checks if Torch or TF tensor
        _UpperCAmelCase    			=   original_sizes.numpy()

      _UpperCAmelCase			,					_UpperCAmelCase			,					_UpperCAmelCase    			=   self._check_and_preprocess_points(
          input_points=__lowerCAmelCase ,					input_labels=__lowerCAmelCase ,					input_boxes=__lowerCAmelCase ,					)

      _UpperCAmelCase    			=   self._normalize_and_convert(
          __lowerCAmelCase ,					__lowerCAmelCase ,					input_points=__lowerCAmelCase ,					input_labels=__lowerCAmelCase ,					input_boxes=__lowerCAmelCase ,					return_tensors=__lowerCAmelCase ,					)

      return encoding_image_processor


    def   lowerCAmelCase_	(       self						:	List[str] ,					__lowerCAmelCase						:	Optional[Any] ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	Union[str, Any]=None ,					__lowerCAmelCase						:	int=None ,					__lowerCAmelCase						:	str=None ,					__lowerCAmelCase						:	Any="pt" ,					):
      if input_points is not None:
        if len(__lowerCAmelCase       ) != len(__lowerCAmelCase       ):
          _UpperCAmelCase    			=   [
              self._normalize_coordinates(self.target_size ,					__lowerCAmelCase ,					original_sizes[0]       ) for point in input_points
          ]
        else:
          _UpperCAmelCase    			=   [
              self._normalize_coordinates(self.target_size ,					__lowerCAmelCase ,					__lowerCAmelCase       )
              for point, original_size in zip(__lowerCAmelCase ,					__lowerCAmelCase       )
          ]
        # 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    			=   self._pad_points_and_labels(__lowerCAmelCase ,					__lowerCAmelCase       )

        _UpperCAmelCase    			=   np.array(__lowerCAmelCase       )

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

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

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

      return encoding_image_processor


    def   lowerCAmelCase_	(       self						:	int ,					__lowerCAmelCase						:	Tuple ,					__lowerCAmelCase						:	int       ):
      _UpperCAmelCase    			=   max([point.shape[0] for point in input_points]       )
      _UpperCAmelCase    			=   []
      for i, point in enumerate(__lowerCAmelCase       ):
        if point.shape[0] != expected_nb_points:
          _UpperCAmelCase    			=   np.concatenate(
              [point, np.zeros((expected_nb_points - point.shape[0], 2)       ) + self.point_pad_value] ,					axis=0       )
          _UpperCAmelCase    			=   np.append(input_labels[i] ,					[self.point_pad_value]       )
        processed_input_points.append(__lowerCAmelCase       )
      _UpperCAmelCase    			=   processed_input_points
      return input_points, input_labels


    def   lowerCAmelCase_	(       self						:	List[str] ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	np.ndarray ,					__lowerCAmelCase						:	int ,					__lowerCAmelCase						:	List[Any]=False       ):
      _UpperCAmelCase			,					_UpperCAmelCase    			=   original_size
      _UpperCAmelCase			,					_UpperCAmelCase    			=   self.image_processor._get_preprocess_shape(__lowerCAmelCase ,					longest_edge=__lowerCAmelCase       )
      _UpperCAmelCase    			=   deepcopy(__lowerCAmelCase       ).astype(__lowerCAmelCase       )

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

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

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

      return coords


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

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

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

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

      if input_boxes is not None:
        if hasattr(__lowerCAmelCase ,					"""numpy"""       ):
          _UpperCAmelCase    			=   input_boxes.numpy().tolist()

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

      return input_points, input_labels, input_boxes


    @property
    def   lowerCAmelCase_	(       self						:	Dict       ):
      _UpperCAmelCase    			=   self.image_processor.model_input_names
      return list(dict.fromkeys(__lowerCAmelCase       )       )


    def   lowerCAmelCase_	(       self						:	List[str] ,					*__lowerCAmelCase						:	Tuple ,					**__lowerCAmelCase						:	List[str]       ):
      return self.image_processor.post_process_masks(*__lowerCAmelCase ,					**__lowerCAmelCase       )

"""simple docstring"""


from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase__			=    logging.get_logger(__name__)


class 							a					(		lowerCAmelCase_ ):
    _snake_case  :	List[Any]  				=				'timm_backbone'


    def __init__(       self						:	List[Any] ,					__lowerCAmelCase						:	str=None ,					__lowerCAmelCase						:	Optional[int]=3 ,					__lowerCAmelCase						:	Any=True ,					__lowerCAmelCase						:	Optional[int]=True ,					__lowerCAmelCase						:	Optional[Any]=None ,					**__lowerCAmelCase						:	Optional[Any] ,					):
      super().__init__(**__lowerCAmelCase       )
      _UpperCAmelCase    			=   backbone
      _UpperCAmelCase    			=   num_channels
      _UpperCAmelCase    			=   features_only
      _UpperCAmelCase    			=   use_pretrained_backbone
      _UpperCAmelCase    			=   True
      _UpperCAmelCase    			=   out_indices if out_indices is not None else (-1,)
