




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_  						=			['''image_processor''']
			snake_case_  						=			'''SamImageProcessor'''


			def __init__( self     ,		lowerCamelCase__				)       -> Union[str, Any]:



							'''simple docstring'''
							super().__init__(lowerCamelCase__				)
							__lowerCamelCase									=       self.image_processor
							__lowerCamelCase									=       -10
							__lowerCamelCase									=       self.image_processor.size['longest_edge']


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



							'''simple docstring'''
							__lowerCamelCase									=       self.image_processor(
							    lowerCamelCase__     ,		return_tensors=lowerCamelCase__     ,		**lowerCamelCase__     ,		)

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

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

							__lowerCamelCase			,		__lowerCamelCase			,		__lowerCamelCase									=       self._check_and_preprocess_points(
							    input_points=lowerCamelCase__     ,		input_labels=lowerCamelCase__     ,		input_boxes=lowerCamelCase__     ,		)

							__lowerCamelCase									=       self._normalize_and_convert(
							    lowerCamelCase__     ,		lowerCamelCase__     ,		input_points=lowerCamelCase__     ,		input_labels=lowerCamelCase__     ,		input_boxes=lowerCamelCase__     ,		return_tensors=lowerCamelCase__     ,		)

							return encoding_image_processor


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__=None     ,		lowerCamelCase__=None     ,		lowerCamelCase__=None     ,		lowerCamelCase__="pt"     ,		)       -> Optional[Any]:



							'''simple docstring'''
							if input_points is not None:
											if len(lowerCamelCase__				) != len(lowerCamelCase__				):
															__lowerCamelCase									=       [
															    self._normalize_coordinates(self.target_size     ,		lowerCamelCase__     ,		original_sizes[0]				) for point in input_points
															]
											else:
															__lowerCamelCase									=       [
															    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:
																			__lowerCamelCase			,		__lowerCamelCase									=       self._pad_points_and_labels(lowerCamelCase__     ,		lowerCamelCase__				)

											__lowerCamelCase									=       np.array(lowerCamelCase__				)

							if input_labels is not None:
											__lowerCamelCase									=       np.array(lowerCamelCase__				)

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

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



							'''simple docstring'''
							__lowerCamelCase									=       max([point.shape[0] for point in input_points]				)
							__lowerCamelCase									=       []
							for i, point in enumerate(lowerCamelCase__				):
											if point.shape[0] != expected_nb_points:
															__lowerCamelCase									=       np.concatenate(
															    [point, np.zeros((expected_nb_points - point.shape[0], 2)				) + self.point_pad_value]     ,		axis=0				)
															__lowerCamelCase									=       np.append(input_labels[i]     ,		[self.point_pad_value]				)
											processed_input_points.append(lowerCamelCase__				)
							__lowerCamelCase									=       processed_input_points
							return input_points, input_labels


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__=False				)       -> np.ndarray:



							'''simple docstring'''
							__lowerCamelCase			,		__lowerCamelCase									=       original_size
							__lowerCamelCase			,		__lowerCamelCase									=       self.image_processor._get_preprocess_shape(lowerCamelCase__     ,		longest_edge=lowerCamelCase__				)
							__lowerCamelCase									=       deepcopy(lowerCamelCase__				).astype(lowerCamelCase__				)

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

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

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

							return coords


			def  lowercase_       ( self     ,		lowerCamelCase__=None     ,		lowerCamelCase__=None     ,		lowerCamelCase__=None     ,		)       -> Optional[int]:



							'''simple docstring'''
							if input_points is not None:
											if hasattr(lowerCamelCase__     ,		'numpy'				):  # Checks for TF or Torch tensor
															__lowerCamelCase									=       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.'				)
											__lowerCamelCase									=       [np.array(lowerCamelCase__				) for input_point in input_points]
							else:
											__lowerCamelCase									=       None

							if input_labels is not None:
											if hasattr(lowerCamelCase__     ,		'numpy'				):
															__lowerCamelCase									=       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.'				)
											__lowerCamelCase									=       [np.array(lowerCamelCase__				) for label in input_labels]
							else:
											__lowerCamelCase									=       None

							if input_boxes is not None:
											if hasattr(lowerCamelCase__     ,		'numpy'				):
															__lowerCamelCase									=       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.'				)
											__lowerCamelCase									=       [np.array(lowerCamelCase__				).astype(np.floataa				) for box in input_boxes]
							else:
											__lowerCamelCase									=       None

							return input_points, input_labels, input_boxes


			@property
			def  lowercase_       ( self				)       -> Union[str, Any]:



							'''simple docstring'''
							__lowerCamelCase									=       self.image_processor.model_input_names
							return list(dict.fromkeys(lowerCamelCase__				)				)






			def  lowercase_       ( self     ,		*lowerCamelCase__     ,		**lowerCamelCase__				)       -> Dict:



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








import importlib.metadata
import operator
import re
import sys
from typing import Optional

from packaging import version


__A								=       {
    "<": operator.lt,
    "<=": operator.le,
    "==": operator.eq,
    "!=": operator.ne,
    ">=": operator.ge,
    ">": operator.gt,
}







def      lowerCamelCase_						(			UpperCamelCase__							: List[str]					,	UpperCamelCase__							: Dict					,	UpperCamelCase__							: Dict					,	UpperCamelCase__							: Any					,	UpperCamelCase__							: Dict					,	UpperCamelCase__							: int )	->			List[Any]:





				"""simple docstring"""


				if got_ver is None or want_ver is None:
								raise ValueError(
								    F"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider"""
								    F""" reinstalling {pkg}.""" )
				if not ops[op](version.parse(UpperCamelCase__ )					,	version.parse(UpperCamelCase__ ) ):
								raise ImportError(
								    F"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}""" )







def      lowerCamelCase_						(			UpperCamelCase__							: str					,	UpperCamelCase__							: Optional[str] = None )	->			None:





				"""simple docstring"""


				__lowerCamelCase									=       F"""\n{hint}""" if hint is not None else ''

				# non-versioned check
				if re.match(R'^[\w_\-\d]+$'					,	UpperCamelCase__ ):
								__lowerCamelCase			,		__lowerCamelCase			,		__lowerCamelCase									=       requirement, None, None
				else:
								__lowerCamelCase									=       re.findall(R'^([^!=<>\s]+)([\s!=<>]{1,2}.+)'					,	UpperCamelCase__ )
								if not match:
												raise ValueError(
												    'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but'
												    F""" got {requirement}""" )
								__lowerCamelCase			,		__lowerCamelCase									=       match[0]
								__lowerCamelCase									=       want_full.split(',' )  # there could be multiple requirements
								__lowerCamelCase									=       {}
								for w in want_range:
												__lowerCamelCase									=       re.findall(R'^([\s!=<>]{1,2})(.+)'					,	UpperCamelCase__ )
												if not match:
																raise ValueError(
																    'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,'
																    F""" but got {requirement}""" )
												__lowerCamelCase			,		__lowerCamelCase									=       match[0]
												__lowerCamelCase									=       want_ver
												if op not in ops:
																raise ValueError(F"""{requirement}: need one of {list(ops.keys() )}, but got {op}""" )

    # special case
				if pkg == "python":
								__lowerCamelCase									=       '.'.join([str(UpperCamelCase__ ) for x in sys.version_info[:3]] )
								for op, want_ver in wanted.items():
												_compare_versions(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__ )
								return

				# check if any version is installed
				try:
								__lowerCamelCase									=       importlib.metadata.version(UpperCamelCase__ )
				except importlib.metadata.PackageNotFoundError:
								raise importlib.metadata.PackageNotFoundError(
								    F"""The '{requirement}' distribution was not found and is required by this application. {hint}""" )

				# check that the right version is installed if version number or a range was provided
				if want_ver is not None:
								for op, want_ver in wanted.items():
												_compare_versions(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__ )







def      lowerCamelCase_						(			UpperCamelCase__							: Optional[int] )	->			Optional[int]:





				"""simple docstring"""


				__lowerCamelCase									=       'Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main'
				return require_version(UpperCamelCase__					,	UpperCamelCase__ )


