



'''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     UpperCamelCase_				(							__magic_name__    ):
	lowercase    =				['image_processor']
	lowercase    =				'SamImageProcessor'





	def __init__(						self	,	A					)    ->    Dict:
								super().__init__(A					)
								UpperCAmelCase  :	List[Any]							  =	self.image_processor
								UpperCAmelCase  :	Any							  =	-10
								UpperCAmelCase  :	Optional[Any]							  =	self.image_processor.size["""longest_edge"""]





	def __call__(						self	,	A=None	,	A=None	,	A=None	,	A=None	,	A = None	,	**A	,	)    ->    BatchEncoding:
								UpperCAmelCase  :	Optional[Any]							  =	self.image_processor(
								    A	,	return_tensors=A	,	**A	,	)

								# pop arguments that are not used in the foward but used nevertheless
								UpperCAmelCase  :	List[str]							  =	encoding_image_processor["""original_sizes"""]

								if hasattr(A	,	"""numpy"""					):  # Checks if Torch or TF tensor
															UpperCAmelCase  :	Any							  =	original_sizes.numpy()

								UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  :	Optional[Any]							  =	self._check_and_preprocess_points(
								    input_points=A	,	input_labels=A	,	input_boxes=A	,	)

								UpperCAmelCase  :	Dict							  =	self._normalize_and_convert(
								    A	,	A	,	input_points=A	,	input_labels=A	,	input_boxes=A	,	return_tensors=A	,	)

								return encoding_image_processor





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

															UpperCAmelCase  :	Any							  =	np.array(A					)

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

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

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





	def 				_lowercase(						self	,	A	,	A	,	A	,	A=False					)    ->    np.ndarray:
								UpperCAmelCase  ,  UpperCAmelCase  :	Tuple							  =	original_size
								UpperCAmelCase  ,  UpperCAmelCase  :	List[Any]							  =	self.image_processor._get_preprocess_shape(A	,	longest_edge=A					)
								UpperCAmelCase  :	Any							  =	deepcopy(A					).astype(A					)

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

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

								if is_bounding_box:
															UpperCAmelCase  :	List[str]							  =	coords.reshape(-1	,	4					)

								return coords





	def 				_lowercase(						self	,	A=None	,	A=None	,	A=None	,	)    ->    List[str]:
								if input_points is not None:
															if hasattr(A	,	"""numpy"""					):  # Checks for TF or Torch tensor
																						UpperCAmelCase  :	Dict							  =	input_points.numpy().tolist()

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

								if input_labels is not None:
															if hasattr(A	,	"""numpy"""					):
																						UpperCAmelCase  :	Any							  =	input_labels.numpy().tolist()

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

								if input_boxes is not None:
															if hasattr(A	,	"""numpy"""					):
																						UpperCAmelCase  :	Tuple							  =	input_boxes.numpy().tolist()

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

								return input_points, input_labels, input_boxes





	@property
	def 				_lowercase(						self					)    ->    Optional[Any]:
								UpperCAmelCase  :	str							  =	self.image_processor.model_input_names
								return list(dict.fromkeys(A					)					)






	def 				_lowercase(						self	,	*A	,	**A					)    ->    Tuple:
								return self.image_processor.post_process_masks(*A	,	**A					)






'''simple docstring'''




from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tensorflow_text_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


a     :    Optional[Any]      						=					{
    """configuration_bert""": ["""BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BertConfig""", """BertOnnxConfig"""],
    """tokenization_bert""": ["""BasicTokenizer""", """BertTokenizer""", """WordpieceTokenizer"""],
}

try:
							if not is_tokenizers_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							a     :    Dict      						=					["""BertTokenizerFast"""]

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							a     :    List[Any]      						=					[
							    """BERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
							    """BertForMaskedLM""",
							    """BertForMultipleChoice""",
							    """BertForNextSentencePrediction""",
							    """BertForPreTraining""",
							    """BertForQuestionAnswering""",
							    """BertForSequenceClassification""",
							    """BertForTokenClassification""",
							    """BertLayer""",
							    """BertLMHeadModel""",
							    """BertModel""",
							    """BertPreTrainedModel""",
							    """load_tf_weights_in_bert""",
							]

try:
							if not is_tf_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							a     :    List[str]      						=					[
							    """TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
							    """TFBertEmbeddings""",
							    """TFBertForMaskedLM""",
							    """TFBertForMultipleChoice""",
							    """TFBertForNextSentencePrediction""",
							    """TFBertForPreTraining""",
							    """TFBertForQuestionAnswering""",
							    """TFBertForSequenceClassification""",
							    """TFBertForTokenClassification""",
							    """TFBertLMHeadModel""",
							    """TFBertMainLayer""",
							    """TFBertModel""",
							    """TFBertPreTrainedModel""",
							]
try:
							if not is_tensorflow_text_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							a     :    int      						=					["""TFBertTokenizer"""]

try:
							if not is_flax_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							a     :    Optional[Any]      						=					[
							    """FlaxBertForCausalLM""",
							    """FlaxBertForMaskedLM""",
							    """FlaxBertForMultipleChoice""",
							    """FlaxBertForNextSentencePrediction""",
							    """FlaxBertForPreTraining""",
							    """FlaxBertForQuestionAnswering""",
							    """FlaxBertForSequenceClassification""",
							    """FlaxBertForTokenClassification""",
							    """FlaxBertModel""",
							    """FlaxBertPreTrainedModel""",
							]

if TYPE_CHECKING:
							from .configuration_bert import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BertConfig, BertOnnxConfig
							from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer

							try:
														if not is_tokenizers_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_bert_fast import BertTokenizerFast

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_bert import (
														    BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
														    BertForMaskedLM,
														    BertForMultipleChoice,
														    BertForNextSentencePrediction,
														    BertForPreTraining,
														    BertForQuestionAnswering,
														    BertForSequenceClassification,
														    BertForTokenClassification,
														    BertLayer,
														    BertLMHeadModel,
														    BertModel,
														    BertPreTrainedModel,
														    load_tf_weights_in_bert,
														)

							try:
														if not is_tf_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_tf_bert import (
														    TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
														    TFBertEmbeddings,
														    TFBertForMaskedLM,
														    TFBertForMultipleChoice,
														    TFBertForNextSentencePrediction,
														    TFBertForPreTraining,
														    TFBertForQuestionAnswering,
														    TFBertForSequenceClassification,
														    TFBertForTokenClassification,
														    TFBertLMHeadModel,
														    TFBertMainLayer,
														    TFBertModel,
														    TFBertPreTrainedModel,
														)

							try:
														if not is_tensorflow_text_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_bert_tf import TFBertTokenizer

							try:
														if not is_flax_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_flax_bert import (
														    FlaxBertForCausalLM,
														    FlaxBertForMaskedLM,
														    FlaxBertForMultipleChoice,
														    FlaxBertForNextSentencePrediction,
														    FlaxBertForPreTraining,
														    FlaxBertForQuestionAnswering,
														    FlaxBertForSequenceClassification,
														    FlaxBertForTokenClassification,
														    FlaxBertModel,
														    FlaxBertPreTrainedModel,
														)

else:
							import sys

							a     :    Optional[int]      						=					_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

