

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			(  lowercase_						):



			'''simple docstring'''






			__snake_case        =	["image_processor"]
			__snake_case        =	"SamImageProcessor"


			def __init__(				self	:						Dict		,      lowerCAmelCase_	:						int			)      ->		Any:





									'''simple docstring'''
									super().__init__(lowerCAmelCase_			)
									A__					:       List[Any]     =self.image_processor
									A__					:       List[Any]     =-10
									A__					:       Optional[int]     =self.image_processor.size["""longest_edge"""]


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





									'''simple docstring'''
									A__					:       int     =self.image_processor(
									    lowerCAmelCase_		,      return_tensors=lowerCAmelCase_		,      **lowerCAmelCase_		,      )

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

									if hasattr(lowerCAmelCase_		,      """numpy"""			):  # Checks if Torch or TF tensor
															A__					:       Dict     =original_sizes.numpy()

									A__   ,						A__   ,						A__					:       List[Any]     =self._check_and_preprocess_points(
									    input_points=lowerCAmelCase_		,      input_labels=lowerCAmelCase_		,      input_boxes=lowerCAmelCase_		,      )

									A__					:       List[str]     =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	:						List[Any]		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						Optional[int]		,      lowerCAmelCase_	:						Optional[int]=None		,      lowerCAmelCase_	:						Optional[int]=None		,      lowerCAmelCase_	:						Optional[int]=None		,      lowerCAmelCase_	:						Union[str, Any]="pt"		,      )      ->		Optional[Any]:





									'''simple docstring'''




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

															A__					:       List[Any]     =np.array(lowerCAmelCase_			)

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

									if input_boxes is not None:
															if len(lowerCAmelCase_			) != len(lowerCAmelCase_			):
																					A__					:       Optional[Any]     =[
																					    self._normalize_coordinates(self.target_size		,      lowerCAmelCase_		,      original_sizes[0]		,      is_bounding_box=lowerCAmelCase_			)
																					    for box in input_boxes
																					]
															else:
																					A__					:       List[str]     =[
																					    self._normalize_coordinates(self.target_size		,      lowerCAmelCase_		,      lowerCAmelCase_		,      is_bounding_box=lowerCAmelCase_			)
																					    for box, original_size in zip(lowerCAmelCase_		,      lowerCAmelCase_			)
																					]
															A__					:       Dict     =np.array(lowerCAmelCase_			)

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





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


			def lowercase__						(				self	:						Tuple		,      lowerCAmelCase_	:						int		,      lowerCAmelCase_	:						np.ndarray		,      lowerCAmelCase_	:						Any		,      lowerCAmelCase_	:						List[str]=False			)      ->		np.ndarray:





									'''simple docstring'''
									A__   ,						A__					:       Tuple     =original_size
									A__   ,						A__					:       int     =self.image_processor._get_preprocess_shape(lowerCAmelCase_		,      longest_edge=lowerCAmelCase_			)
									A__					:       List[Any]     =deepcopy(lowerCAmelCase_			).astype(lowerCAmelCase_			)

									if is_bounding_box:
															A__					:       Optional[Any]     =coords.reshape(-1		,      2		,      2			)

									A__					:       Dict     =coords[..., 0] * (new_w / old_w)
									A__					:       Tuple     =coords[..., 1] * (new_h / old_h)

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

									return coords


			def lowercase__						(				self	:						Tuple		,      lowerCAmelCase_	:						Any=None		,      lowerCAmelCase_	:						List[Any]=None		,      lowerCAmelCase_	:						Dict=None		,      )      ->		Any:





									'''simple docstring'''




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

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

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

									return input_points, input_labels, input_boxes


			@property
			def lowercase__						(				self	:						Optional[int]			)      ->		Optional[Any]:





									'''simple docstring'''
									A__					:       Optional[Any]     =self.image_processor.model_input_names
									return list(dict.fromkeys(lowerCAmelCase_			)			)



			def lowercase__						(				self	:						str		,      *lowerCAmelCase_	:						List[str]		,      **lowerCAmelCase_	:						int			)      ->		Union[str, Any]:





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




'''simple docstring'''



from typing import Dict

from .base import GenericTensor, Pipeline



class lowerCamelCase			(  lowercase_						):



			'''simple docstring'''






			def lowercase__						(				self	:						List[str]		,      lowerCAmelCase_	:						Tuple=None		,      lowerCAmelCase_	:						Dict=None		,      lowerCAmelCase_	:						Any=None		,      **lowerCAmelCase_	:						Union[str, Any]			)      ->		Optional[Any]:





									'''simple docstring'''
									if tokenize_kwargs is None:
															A__					:       List[Any]     ={}

									if truncation is not None:
															if "truncation" in tokenize_kwargs:
																					raise ValueError(
																					    """truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)"""			)
															A__					:       str     =truncation

									A__					:       Optional[int]     =tokenize_kwargs

									A__					:       List[Any]     ={}
									if return_tensors is not None:
															A__					:       Any     =return_tensors

									return preprocess_params, {}, postprocess_params


			def lowercase__						(				self	:						int		,      lowerCAmelCase_	:						Union[str, Any]		,      **lowerCAmelCase_	:						Dict			)      ->		Dict[str, GenericTensor]:





									'''simple docstring'''
									A__					:       List[str]     =self.framework
									A__					:       Union[str, Any]     =self.tokenizer(lowerCAmelCase_		,      return_tensors=lowerCAmelCase_		,      **lowerCAmelCase_			)
									return model_inputs


			def lowercase__						(				self	:						Optional[int]		,      lowerCAmelCase_	:						Dict			)      ->		Optional[Any]:





									'''simple docstring'''
									A__					:       Union[str, Any]     =self.model(**lowerCAmelCase_			)
									return model_outputs


			def lowercase__						(				self	:						Tuple		,      lowerCAmelCase_	:						Tuple		,      lowerCAmelCase_	:						Any=False			)      ->		List[Any]:





									'''simple docstring'''
									# [0] is the first available tensor, logits or last_hidden_state.
									if return_tensors:
															return model_outputs[0]
									if self.framework == "pt":
															return model_outputs[0].tolist()
									elif self.framework == "tf":
															return model_outputs[0].numpy().tolist()



			def __call__(				self	:						int		,      *lowerCAmelCase_	:						Any		,      **lowerCAmelCase_	:						Union[str, Any]			)      ->		List[str]:





									'''simple docstring'''
									return super().__call__(*lowerCAmelCase_		,      **lowerCAmelCase_			)

