'''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				):



  """simple docstring"""
  __lowerCAmelCase				      =					["""image_processor"""]
  __lowerCAmelCase				      =					"""SamImageProcessor"""







  def __init__(							self   ,    snake_case_					):

    '''simple docstring'''







    super().__init__(snake_case_					)
    __UpperCAmelCase:					str		= self.image_processor
    __UpperCAmelCase:					List[Any]		= -10
    __UpperCAmelCase:					List[str]		= self.image_processor.size["""longest_edge"""]







  def __call__(							self   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_ = None   ,    **snake_case_   ,    ):

    '''simple docstring'''







    __UpperCAmelCase:					List[str]		= self.image_processor(
        snake_case_   ,    return_tensors=snake_case_   ,    **snake_case_   ,    )

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

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

    __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase:					Dict		= self._check_and_preprocess_points(
        input_points=snake_case_   ,    input_labels=snake_case_   ,    input_boxes=snake_case_   ,    )

    __UpperCAmelCase:					Union[str, Any]		= 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    lowercase_  (							self   ,    snake_case_   ,    snake_case_   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_="pt"   ,    ):

    '''simple docstring'''







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

      __UpperCAmelCase:					List[str]		= np.array(snake_case_					)

    if input_labels is not None:
      __UpperCAmelCase:					List[str]		= np.array(snake_case_					)

    if input_boxes is not None:
      if len(snake_case_					) != len(snake_case_					):
        __UpperCAmelCase:					Dict		= [
            self._normalize_coordinates(self.target_size   ,    snake_case_   ,    original_sizes[0]   ,    is_bounding_box=snake_case_					)
            for box in input_boxes
        ]
      else:
        __UpperCAmelCase:					List[str]		= [
            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:					List[str]		= 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:					int		= tf.convert_to_tensor(snake_case_					)
        # boxes batch size of 1 by default
        __UpperCAmelCase:					List[Any]		= 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:					int		= torch.from_numpy(snake_case_					)
        # point batch size of 1 by default
        __UpperCAmelCase:					Union[str, Any]		= input_points.unsqueeze(1					) if len(input_points.shape					) != 4 else input_points
      elif return_tensors == "tf":
        __UpperCAmelCase:					Optional[Any]		= 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:					Union[str, Any]		= torch.from_numpy(snake_case_					)
        # point batch size of 1 by default
        __UpperCAmelCase:					Optional[Any]		= input_labels.unsqueeze(1					) if len(input_labels.shape					) != 3 else input_labels
      elif return_tensors == "tf":
        __UpperCAmelCase:					Dict		= tf.convert_to_tensor(snake_case_					)
        # point batch size of 1 by default
        __UpperCAmelCase:					str		= 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    lowercase_  (							self   ,    snake_case_   ,    snake_case_					):

    '''simple docstring'''







    __UpperCAmelCase:					int		= max([point.shape[0] for point in input_points]					)
    __UpperCAmelCase:					Tuple		= []
    for i, point in enumerate(snake_case_					):
      if point.shape[0] != expected_nb_points:
        __UpperCAmelCase:					Optional[Any]		= 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:					Union[str, Any]		= processed_input_points
    return input_points, input_labels







  def    lowercase_  (							self   ,    snake_case_   ,    snake_case_   ,    snake_case_   ,    snake_case_=False					):

    '''simple docstring'''







    __UpperCAmelCase, __UpperCAmelCase:					Tuple		= original_size
    __UpperCAmelCase, __UpperCAmelCase:					Any		= 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:					Optional[int]		= coords.reshape(-1   ,    2   ,    2					)

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

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

    return coords







  def    lowercase_  (							self   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_=None   ,    ):

    '''simple docstring'''







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

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

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

    return input_points, input_labels, input_boxes







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[Any]		= self.image_processor.model_input_names
    return list(dict.fromkeys(snake_case_					)					)







  def    lowercase_  (							self   ,    *snake_case_   ,    **snake_case_					):

    '''simple docstring'''







    return self.image_processor.post_process_masks(*snake_case_   ,    **snake_case_					)
'''simple docstring'''






from typing import TYPE_CHECKING

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


SCREAMING_SNAKE_CASE_	   =			{
    'configuration_electra': ['ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ElectraConfig', 'ElectraOnnxConfig'],
    'tokenization_electra': ['ElectraTokenizer'],
}

try:
    if not is_tokenizers_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    SCREAMING_SNAKE_CASE_	   =			['ElectraTokenizerFast']

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    SCREAMING_SNAKE_CASE_	   =			[
        'ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST',
        'ElectraForCausalLM',
        'ElectraForMaskedLM',
        'ElectraForMultipleChoice',
        'ElectraForPreTraining',
        'ElectraForQuestionAnswering',
        'ElectraForSequenceClassification',
        'ElectraForTokenClassification',
        'ElectraModel',
        'ElectraPreTrainedModel',
        'load_tf_weights_in_electra',
    ]

try:
    if not is_tf_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    SCREAMING_SNAKE_CASE_	   =			[
        'TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST',
        'TFElectraForMaskedLM',
        'TFElectraForMultipleChoice',
        'TFElectraForPreTraining',
        'TFElectraForQuestionAnswering',
        'TFElectraForSequenceClassification',
        'TFElectraForTokenClassification',
        'TFElectraModel',
        'TFElectraPreTrainedModel',
    ]

try:
    if not is_flax_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    SCREAMING_SNAKE_CASE_	   =			[
        'FlaxElectraForCausalLM',
        'FlaxElectraForMaskedLM',
        'FlaxElectraForMultipleChoice',
        'FlaxElectraForPreTraining',
        'FlaxElectraForQuestionAnswering',
        'FlaxElectraForSequenceClassification',
        'FlaxElectraForTokenClassification',
        'FlaxElectraModel',
        'FlaxElectraPreTrainedModel',
    ]


if TYPE_CHECKING:
    from .configuration_electra import ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ElectraConfig, ElectraOnnxConfig
    from .tokenization_electra import ElectraTokenizer

    try:
        if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_electra_fast import ElectraTokenizerFast

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_electra import (
            ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST,
            ElectraForCausalLM,
            ElectraForMaskedLM,
            ElectraForMultipleChoice,
            ElectraForPreTraining,
            ElectraForQuestionAnswering,
            ElectraForSequenceClassification,
            ElectraForTokenClassification,
            ElectraModel,
            ElectraPreTrainedModel,
            load_tf_weights_in_electra,
        )

    try:
        if not is_tf_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_tf_electra import (
            TF_ELECTRA_PRETRAINED_MODEL_ARCHIVE_LIST,
            TFElectraForMaskedLM,
            TFElectraForMultipleChoice,
            TFElectraForPreTraining,
            TFElectraForQuestionAnswering,
            TFElectraForSequenceClassification,
            TFElectraForTokenClassification,
            TFElectraModel,
            TFElectraPreTrainedModel,
        )

    try:
        if not is_flax_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_flax_electra import (
            FlaxElectraForCausalLM,
            FlaxElectraForMaskedLM,
            FlaxElectraForMultipleChoice,
            FlaxElectraForPreTraining,
            FlaxElectraForQuestionAnswering,
            FlaxElectraForSequenceClassification,
            FlaxElectraForTokenClassification,
            FlaxElectraModel,
            FlaxElectraPreTrainedModel,
        )

else:
    import sys

    SCREAMING_SNAKE_CASE_	   =			_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)