


"""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 _lowerCAmelCase    (				snake_case_     ):
   __UpperCAmelCase			:	int							  =  ['''image_processor''']
   __UpperCAmelCase			:	Union[str, Any]							  =  '''SamImageProcessor'''







   def __init__(     self						,     UpperCamelCase__						)     ->		Dict:

       '''simple docstring'''




       super().__init__(UpperCamelCase__						)
       snake_case   :				Any				 =   self.image_processor
       snake_case   :				int				 =   -10
       snake_case   :				Any				 =   self.image_processor.size["longest_edge"]







   def __call__(     self						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__ = None						,     **UpperCamelCase__						,     )     ->		BatchEncoding:

       '''simple docstring'''




       snake_case   :				Union[str, Any]				 =   self.image_processor(
           UpperCamelCase__						,     return_tensors=UpperCamelCase__						,     **UpperCamelCase__						,     )

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

       if hasattr(UpperCamelCase__						,     "numpy"						):  # Checks if Torch or TF tensor
           snake_case   :				int				 =   original_sizes.numpy()

       snake_case ,snake_case ,snake_case   :				Any				 =   self._check_and_preprocess_points(
           input_points=UpperCamelCase__						,     input_labels=UpperCamelCase__						,     input_boxes=UpperCamelCase__						,     )

       snake_case   :				int				 =   self._normalize_and_convert(
           UpperCamelCase__						,     UpperCamelCase__						,     input_points=UpperCamelCase__						,     input_labels=UpperCamelCase__						,     input_boxes=UpperCamelCase__						,     return_tensors=UpperCamelCase__						,     )

       return encoding_image_processor







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__="pt"						,     )     ->		List[str]:

       '''simple docstring'''




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

           snake_case   :				int				 =   np.array(UpperCamelCase__						)

       if input_labels is not None:
           snake_case   :				List[Any]				 =   np.array(UpperCamelCase__						)

       if input_boxes is not None:
           if len(UpperCamelCase__						) != len(UpperCamelCase__						):
               snake_case   :				Union[str, Any]				 =   [
                   self._normalize_coordinates(self.target_size						,     UpperCamelCase__						,     original_sizes[0]						,     is_bounding_box=UpperCamelCase__						)
                   for box in input_boxes
               ]
           else:
               snake_case   :				int				 =   [
                   self._normalize_coordinates(self.target_size						,     UpperCamelCase__						,     UpperCamelCase__						,     is_bounding_box=UpperCamelCase__						)
                   for box, original_size in zip(UpperCamelCase__						,     UpperCamelCase__						)
               ]
           snake_case   :				int				 =   np.array(UpperCamelCase__						)

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

       '''simple docstring'''




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







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__=False						)     ->		np.ndarray:

       '''simple docstring'''




       snake_case ,snake_case   :				Optional[int]				 =   original_size
       snake_case ,snake_case   :				Dict				 =   self.image_processor._get_preprocess_shape(UpperCamelCase__						,     longest_edge=UpperCamelCase__						)
       snake_case   :				List[str]				 =   deepcopy(UpperCamelCase__						).astype(UpperCamelCase__						)

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

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

       if is_bounding_box:
           snake_case   :				Optional[int]				 =   coords.reshape(-1						,     4						)

       return coords







   def 			lowerCamelCase		(     self						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     )     ->		List[str]:

       '''simple docstring'''




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

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

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

       return input_points, input_labels, input_boxes







   @property
   def 			lowerCamelCase		(     self						)     ->		Any:

       '''simple docstring'''




       snake_case   :				Tuple				 =   self.image_processor.model_input_names
       return list(dict.fromkeys(UpperCamelCase__						)						)







   def 			lowerCamelCase		(     self						,     *UpperCamelCase__						,     **UpperCamelCase__						)     ->		Optional[int]:

       '''simple docstring'''




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









"""simple docstring"""



import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf


if is_tf_available():
  import tensorflow as tf
  from tensorflow.python.eager import context
  from tensorflow.python.framework import ops

  from transformers import GradientAccumulator, create_optimizer







@require_tf
class _lowerCAmelCase    (				unittest.TestCase     ):







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)     ->		Optional[Any]:

       '''simple docstring'''




       self.assertEqual(len(UpperCamelCase__						)						,     len(UpperCamelCase__						)						)
       for a, b in zip(UpperCamelCase__						,     UpperCamelCase__						):
           self.assertAlmostEqual(UpperCamelCase__						,     UpperCamelCase__						,     delta=UpperCamelCase__						)







   def 			lowerCamelCase		(     self						)     ->		Any:

       '''simple docstring'''




       snake_case   :				List[Any]				 =   GradientAccumulator()
       accumulator([tf.constant([1.0, 2.0]						)]						)
       accumulator([tf.constant([-2.0, 1.0]						)]						)
       accumulator([tf.constant([-1.0, 2.0]						)]						)
       with self.assertRaises(UpperCamelCase__						):
           accumulator([tf.constant([1.0, 1.0]						), tf.constant([2.0, 2.0]						)]						)
       self.assertEqual(accumulator.step						,     3						)
       self.assertEqual(len(accumulator.gradients						)						,     1						)
       self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist()						,     [-2.0, 5.0]						,     tol=1e-2						)
       accumulator.reset()
       self.assertEqual(accumulator.step						,     0						)
       self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist()						,     [0.0, 0.0]						,     tol=1e-2						)







   def 			lowerCamelCase		(     self						)     ->		int:

       '''simple docstring'''




       snake_case   :				Optional[Any]				 =   None
       ops.enable_eager_execution_internal()
       snake_case   :				str				 =   tf.config.list_physical_devices("CPU"						)
       if len(UpperCamelCase__						) == 1:
           tf.config.set_logical_device_configuration(
               physical_devices[0]						,     [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()]						)
       snake_case   :				Optional[int]				 =   tf.config.list_logical_devices(device_type="CPU"						)
       snake_case   :				List[str]				 =   tf.distribute.MirroredStrategy(devices=devices[:2]						)

       with strategy.scope():
           snake_case   :				int				 =   GradientAccumulator()
           snake_case   :				int				 =   tf.Variable([4.0, 3.0]						)
           snake_case ,snake_case   :				Any				 =   create_optimizer(5e-5						,     10						,     5						)
           snake_case   :				Tuple				 =   tf.Variable([0.0, 0.0]						,     trainable=UpperCamelCase__						)

       def accumulate_on_replica(UpperCamelCase__						):
           accumulator([gradient]						)

       def apply_on_replica():
           optimizer.apply_gradients(list(zip(accumulator.gradients						,     [variable]						)						)						)

       @tf.function
       def accumulate(UpperCamelCase__						,     UpperCamelCase__						):
           with strategy.scope():
               snake_case   :				Union[str, Any]				 =   strategy.experimental_local_results(UpperCamelCase__						)
               local_variables[0].assign(UpperCamelCase__						)
               local_variables[1].assign(UpperCamelCase__						)
               strategy.run(UpperCamelCase__						,     args=(gradient_placeholder,)						)

       @tf.function
       def apply_grad():
           with strategy.scope():
               strategy.run(UpperCamelCase__						)

       def _check_local_values(UpperCamelCase__						,     UpperCamelCase__						):
           snake_case   :				List[Any]				 =   strategy.experimental_local_results(accumulator._gradients[0]						)
           self.assertListAlmostEqual(values[0].value()						,     UpperCamelCase__						,     tol=1e-2						)
           self.assertListAlmostEqual(values[1].value()						,     UpperCamelCase__						,     tol=1e-2						)

       accumulate([1.0, 2.0]						,     [-1.0, 1.0]						)
       accumulate([3.0, -1.0]						,     [-1.0, -1.0]						)
       accumulate([-2.0, 2.0]						,     [3.0, -2.0]						)
       self.assertEqual(accumulator.step						,     3						)
       _check_local_values([2.0, 3.0]						,     [1.0, -2.0]						)
       apply_grad()
       self.assertListAlmostEqual(variable.value()						,     [4.0, 3.0]						,     tol=1e-2						)
       accumulator.reset()
       self.assertEqual(accumulator.step						,     0						)
       _check_local_values([0.0, 0.0]						,     [0.0, 0.0]						)





