


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       lowerCamelCase__   (       lowerCAmelCase):
     SCREAMING_SNAKE_CASE__      			=			['''image_processor''']
     SCREAMING_SNAKE_CASE__      			=			'''SamImageProcessor'''





     def __init__(self		,     UpperCAmelCase       )     ->   List[str]:
      super().__init__(UpperCAmelCase       )
      _lowercase							      =self.image_processor
      _lowercase							      =-1_0
      _lowercase							      =self.image_processor.size['''longest_edge''']





     def __call__(self		,     UpperCAmelCase=None		,     UpperCAmelCase=None		,     UpperCAmelCase=None		,     UpperCAmelCase=None		,     UpperCAmelCase = None		,     **UpperCAmelCase		,     )     ->   BatchEncoding:
      _lowercase							      =self.image_processor(
          UpperCAmelCase		,     return_tensors=UpperCAmelCase		,     **UpperCAmelCase		,     )

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

      if hasattr(UpperCAmelCase		,     '''numpy'''       ):  # Checks if Torch or TF tensor
       _lowercase							      =original_sizes.numpy()

      _lowercase      ,    _lowercase      ,    _lowercase							      =self._check_and_preprocess_points(
          input_points=UpperCAmelCase		,     input_labels=UpperCAmelCase		,     input_boxes=UpperCAmelCase		,     )

      _lowercase							      =self._normalize_and_convert(
          UpperCAmelCase		,     UpperCAmelCase		,     input_points=UpperCAmelCase		,     input_labels=UpperCAmelCase		,     input_boxes=UpperCAmelCase		,     return_tensors=UpperCAmelCase		,     )

      return encoding_image_processor





     def      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase=None		,     UpperCAmelCase=None		,     UpperCAmelCase=None		,     UpperCAmelCase="pt"		,     )     ->   Tuple:
      if input_points is not None:
       if len(UpperCAmelCase       ) != len(UpperCAmelCase       ):
        _lowercase							      =[
            self._normalize_coordinates(self.target_size		,     UpperCAmelCase		,     original_sizes[0]       ) for point in input_points
        ]
       else:
        _lowercase							      =[
            self._normalize_coordinates(self.target_size		,     UpperCAmelCase		,     UpperCAmelCase       )
            for point, original_size in zip(UpperCAmelCase		,     UpperCAmelCase       )
        ]
       # 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:
         _lowercase      ,    _lowercase							      =self._pad_points_and_labels(UpperCAmelCase		,     UpperCAmelCase       )

       _lowercase							      =np.array(UpperCAmelCase       )

      if input_labels is not None:
       _lowercase							      =np.array(UpperCAmelCase       )

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

      if input_boxes is not None:
       if return_tensors == "pt":
        _lowercase							      =torch.from_numpy(UpperCAmelCase       )
        # boxes batch size of 1 by default
        _lowercase							      =input_boxes.unsqueeze(1       ) if len(input_boxes.shape       ) != 3 else input_boxes
       elif return_tensors == "tf":
        _lowercase							      =tf.convert_to_tensor(UpperCAmelCase       )
        # boxes batch size of 1 by default
        _lowercase							      =tf.expand_dims(UpperCAmelCase		,     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":
        _lowercase							      =torch.from_numpy(UpperCAmelCase       )
        # point batch size of 1 by default
        _lowercase							      =input_points.unsqueeze(1       ) if len(input_points.shape       ) != 4 else input_points
       elif return_tensors == "tf":
        _lowercase							      =tf.convert_to_tensor(UpperCAmelCase       )
        # point batch size of 1 by default
        _lowercase							      =tf.expand_dims(UpperCAmelCase		,     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":
        _lowercase							      =torch.from_numpy(UpperCAmelCase       )
        # point batch size of 1 by default
        _lowercase							      =input_labels.unsqueeze(1       ) if len(input_labels.shape       ) != 3 else input_labels
       elif return_tensors == "tf":
        _lowercase							      =tf.convert_to_tensor(UpperCAmelCase       )
        # point batch size of 1 by default
        _lowercase							      =tf.expand_dims(UpperCAmelCase		,     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		,     UpperCAmelCase		,     UpperCAmelCase       )     ->   Any:
      _lowercase							      =max([point.shape[0] for point in input_points]       )
      _lowercase							      =[]
      for i, point in enumerate(UpperCAmelCase       ):
       if point.shape[0] != expected_nb_points:
        _lowercase							      =np.concatenate(
            [point, np.zeros((expected_nb_points - point.shape[0], 2)       ) + self.point_pad_value]		,     axis=0       )
        _lowercase							      =np.append(input_labels[i]		,     [self.point_pad_value]       )
       processed_input_points.append(UpperCAmelCase       )
      _lowercase							      =processed_input_points
      return input_points, input_labels





     def      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase=False       )     ->   np.ndarray:
      _lowercase      ,    _lowercase							      =original_size
      _lowercase      ,    _lowercase							      =self.image_processor._get_preprocess_shape(UpperCAmelCase		,     longest_edge=UpperCAmelCase       )
      _lowercase							      =deepcopy(UpperCAmelCase       ).astype(UpperCAmelCase       )

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

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

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

      return coords





     def      __A					(self		,     UpperCAmelCase=None		,     UpperCAmelCase=None		,     UpperCAmelCase=None		,     )     ->   Dict:
      if input_points is not None:
       if hasattr(UpperCAmelCase		,     '''numpy'''       ):  # Checks for TF or Torch tensor
        _lowercase							      =input_points.numpy().tolist()

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

      if input_labels is not None:
       if hasattr(UpperCAmelCase		,     '''numpy'''       ):
        _lowercase							      =input_labels.numpy().tolist()

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

      if input_boxes is not None:
       if hasattr(UpperCAmelCase		,     '''numpy'''       ):
        _lowercase							      =input_boxes.numpy().tolist()

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

      return input_points, input_labels, input_boxes





     @property
     def      __A					(self       )     ->   Tuple:
      _lowercase							      =self.image_processor.model_input_names
      return list(dict.fromkeys(UpperCAmelCase       )       )





     def      __A					(self		,     *UpperCAmelCase		,     **UpperCAmelCase       )     ->   Optional[int]:
      return self.image_processor.post_process_masks(*UpperCAmelCase		,     **UpperCAmelCase       )





# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


UpperCAmelCase__   	=							{
    '''configuration_efficientnet''': [
        '''EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''EfficientNetConfig''',
        '''EfficientNetOnnxConfig''',
    ]
}

try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCAmelCase__   	=							['''EfficientNetImageProcessor''']

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCAmelCase__   	=							[
      '''EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST''',
      '''EfficientNetForImageClassification''',
      '''EfficientNetModel''',
      '''EfficientNetPreTrainedModel''',
  ]

if TYPE_CHECKING:
  from .configuration_efficientnet import (
      EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
      EfficientNetConfig,
      EfficientNetOnnxConfig,
  )

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .image_processing_efficientnet import EfficientNetImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_efficientnet import (
        EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
        EfficientNetForImageClassification,
        EfficientNetModel,
        EfficientNetPreTrainedModel,
    )

else:
  import sys

  UpperCAmelCase__   	=							_LazyModule(__name__, globals()['''__file__'''], _import_structure)

