





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							(      __UpperCamelCase    ):
 UpperCAmelCase__									=	["""image_processor"""]
 UpperCAmelCase__									=	"""SamImageProcessor"""
 def __init__(   self						:   List[str]    ,  UpperCAmelCase						:   Any			)    ->			Dict:
     super().__init__(UpperCAmelCase			)
     lowerCamelCase__					:   Union[str, Any]      				=	self.image_processor
     lowerCamelCase__					:   int      				=	-10
     lowerCamelCase__					:   Tuple      				=	self.image_processor.size['longest_edge']
 def __call__(   self						:   List[Any]    ,  UpperCAmelCase						:   Dict=None    ,  UpperCAmelCase						:   Dict=None    ,  UpperCAmelCase						:   Any=None    ,  UpperCAmelCase						:   List[Any]=None    ,  UpperCAmelCase						:   Optional[Union[str, TensorType]] = None    ,  **UpperCAmelCase						:   str    ,  )    ->			BatchEncoding:
     lowerCamelCase__					:   List[Any]      				=	self.image_processor(
         UpperCAmelCase    ,  return_tensors=UpperCAmelCase    ,  **UpperCAmelCase    ,  )

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

     if hasattr(UpperCAmelCase    ,  'numpy'			):  # Checks if Torch or TF tensor
         lowerCamelCase__					:   Optional[int]      				=	original_sizes.numpy()

     lowerCamelCase__				,							lowerCamelCase__				,							lowerCamelCase__					:   str      				=	self._check_and_preprocess_points(
         input_points=UpperCAmelCase    ,  input_labels=UpperCAmelCase    ,  input_boxes=UpperCAmelCase    ,  )

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

     return encoding_image_processor
 def   A_			(   self						:   List[str]    ,  UpperCAmelCase						:   List[Any]    ,  UpperCAmelCase						:   Dict    ,  UpperCAmelCase						:   Union[str, Any]=None    ,  UpperCAmelCase						:   List[str]=None    ,  UpperCAmelCase						:   List[Any]=None    ,  UpperCAmelCase						:   Tuple="pt"    ,  )    ->			Optional[Any]:
     if input_points is not None:
         if len(UpperCAmelCase			) != len(UpperCAmelCase			):
             lowerCamelCase__					:   int      				=	[
                 self._normalize_coordinates(self.target_size    ,  UpperCAmelCase    ,  original_sizes[0]			) for point in input_points
             ]
         else:
             lowerCamelCase__					:   List[str]      				=	[
                 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:
                 lowerCamelCase__				,							lowerCamelCase__					:   Optional[Any]      				=	self._pad_points_and_labels(UpperCAmelCase    ,  UpperCAmelCase			)

         lowerCamelCase__					:   Tuple      				=	np.array(UpperCAmelCase			)

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

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

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

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

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

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

     return coords
 def   A_			(   self						:   Optional[int]    ,  UpperCAmelCase						:   Optional[Any]=None    ,  UpperCAmelCase						:   int=None    ,  UpperCAmelCase						:   Optional[int]=None    ,  )    ->			List[Any]:
     if input_points is not None:
         if hasattr(UpperCAmelCase    ,  'numpy'			):  # Checks for TF or Torch tensor
             lowerCamelCase__					:   Optional[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.'			)
         lowerCamelCase__					:   int      				=	[np.array(UpperCAmelCase			) for input_point in input_points]
     else:
         lowerCamelCase__					:   List[Any]      				=	None

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

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

     return input_points, input_labels, input_boxes
 @property
 def   A_			(   self						:   Dict			)    ->			Optional[Any]:
     lowerCamelCase__					:   str      				=	self.image_processor.model_input_names
     return list(dict.fromkeys(UpperCAmelCase			)			)







 def   A_			(   self						:   int    ,  *UpperCAmelCase						:   Optional[int]    ,  **UpperCAmelCase						:   str			)    ->			Union[str, Any]:
     return self.image_processor.post_process_masks(*UpperCAmelCase    ,  **UpperCAmelCase			)












import enum
import shutil
import sys


_UpperCAmelCase     ,_UpperCAmelCase       : List[Any]			     =       shutil.get_terminal_size()

_UpperCAmelCase       : Union[str, Any]			     =       {"""UP""": """A""", """DOWN""": """B""", """RIGHT""": """C""", """LEFT""": """D"""}

class      lowerCAmelCase							(      enum.Enum    ):
 UpperCAmelCase__									=	0
 UpperCAmelCase__									=	1


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase		,			_UpperCAmelCase=""				)    ->  int:
    sys.stdout.write(str(_UpperCAmelCase				) + end				)
    sys.stdout.flush()


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase		,			_UpperCAmelCase		,			_UpperCAmelCase=""				)    ->  Union[str, Any]:
    forceWrite(F"""\u001b[{color}m{content}\u001b[0m"""		,			_UpperCAmelCase				)


def  SCREAMING_SNAKE_CASE   ( )    ->  Dict:
    forceWrite('\r'				)


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase		,			_UpperCAmelCase				)    ->  Optional[Any]:
    forceWrite(F"""\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}"""				)


def  SCREAMING_SNAKE_CASE   ( )    ->  int:
    forceWrite(' ' * TERMINAL_WIDTH				)
    reset_cursor()


def  SCREAMING_SNAKE_CASE   ( )    ->  Optional[Any]:
    reset_cursor()
    forceWrite('-' * TERMINAL_WIDTH				)





