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






       """simple docstring"""
       _snake_case     :					int						    =   ['image_processor']
       _snake_case     :					Tuple						    =   'SamImageProcessor'





       def __init__(							self       :		str	,			lowerCAmelCase__       :		Optional[Any]					)   ->					int:

            '''simple docstring'''




            super().__init__(lowerCAmelCase__					)
            _UpperCamelCase       =	self.image_processor
            _UpperCamelCase       =	-10
            _UpperCamelCase       =	self.image_processor.size['''longest_edge''']





       def __call__(							self       :		List[str]	,			lowerCAmelCase__       :		Any=None	,			lowerCAmelCase__       :		Tuple=None	,			lowerCAmelCase__       :		Dict=None	,			lowerCAmelCase__       :		Union[str, Any]=None	,			lowerCAmelCase__       :		Optional[Union[str, TensorType]] = None	,			**lowerCAmelCase__       :		Union[str, Any]	,			)   ->					BatchEncoding:

            '''simple docstring'''




            _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 snake_case__						(							self       :		Any	,			lowerCAmelCase__       :		str	,			lowerCAmelCase__       :		List[Any]	,			lowerCAmelCase__       :		Dict=None	,			lowerCAmelCase__       :		Optional[int]=None	,			lowerCAmelCase__       :		Tuple=None	,			lowerCAmelCase__       :		List[str]="pt"	,			)   ->					Tuple:

            '''simple docstring'''




            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 snake_case__						(							self       :		List[Any]	,			lowerCAmelCase__       :		Dict	,			lowerCAmelCase__       :		Optional[Any]					)   ->					Optional[Any]:

            '''simple docstring'''




            _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 snake_case__						(							self       :		List[Any]	,			lowerCAmelCase__       :		int	,			lowerCAmelCase__       :		np.ndarray	,			lowerCAmelCase__       :		Any	,			lowerCAmelCase__       :		str=False					)   ->					np.ndarray:

            '''simple docstring'''




            _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 snake_case__						(							self       :		Optional[Any]	,			lowerCAmelCase__       :		Tuple=None	,			lowerCAmelCase__       :		List[str]=None	,			lowerCAmelCase__       :		Optional[int]=None	,			)   ->					List[str]:

            '''simple docstring'''




            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 snake_case__						(							self       :		Any					)   ->					Optional[int]:

            '''simple docstring'''




            _UpperCamelCase       =	self.image_processor.model_input_names
            return list(dict.fromkeys(lowerCAmelCase__					)					)







       def snake_case__						(							self       :		List[str]	,			*lowerCAmelCase__       :		Dict	,			**lowerCAmelCase__       :		str					)   ->					Any:

            '''simple docstring'''




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










'''simple docstring'''

import importlib.metadata
from typing import Union

from packaging.version import Version, parse

from .constants import STR_OPERATION_TO_FUNC


lowercase__						:      List[Any]	=    parse(importlib.metadata.version('torch'))







def  a__    (    lowercase :					Union[str, Version], lowercase :					str, lowercase :					str				)		->		List[str]:





     """simple docstring"""

     if operation not in STR_OPERATION_TO_FUNC.keys():
          raise ValueError(F"""`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys()				)}, received {operation}"""				)
     _UpperCamelCase       =	STR_OPERATION_TO_FUNC[operation]
     if isinstance(lowercase, lowercase				):
          _UpperCamelCase       =	parse(importlib.metadata.version(lowercase				)				)
     return operation(lowercase, parse(lowercase				)				)







def  a__    (    lowercase :					str, lowercase :					str				)		->		List[Any]:





     """simple docstring"""

     return compare_versions(lowercase, lowercase, lowercase				)



