


"""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 							A_      (       _a ):
  lowerCAmelCase__      			=	['image_processor']
  lowerCAmelCase__      			=	'SamImageProcessor'


  def __init__(			self:						Tuple							,__lowerCAmelCase:						List[Any]    ):







     '''simple docstring'''







     super().__init__(__lowerCAmelCase    )
     _lowerCamelCase   :				int							=     self.image_processor
     _lowerCamelCase   :				str							=     -10
     _lowerCamelCase   :				Optional[Any]							=     self.image_processor.size["longest_edge"]


  def __call__(			self:						Dict							,__lowerCAmelCase:						Optional[Any]=None							,__lowerCAmelCase:						Any=None							,__lowerCAmelCase:						Optional[int]=None							,__lowerCAmelCase:						List[Any]=None							,__lowerCAmelCase:						Optional[Union[str, TensorType]] = None							,**__lowerCAmelCase:						Union[str, Any]							,):







     '''simple docstring'''







     _lowerCamelCase   :				Union[str, Any]							=     self.image_processor(
         __lowerCAmelCase							,return_tensors=__lowerCAmelCase							,**__lowerCAmelCase							,)

     # pop arguments that are not used in the foward but used nevertheless
     _lowerCamelCase   :				Union[str, Any]							=     encoding_image_processor["original_sizes"]

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

     _lowerCamelCase,					_lowerCamelCase,					_lowerCamelCase   :				Dict							=     self._check_and_preprocess_points(
         input_points=__lowerCAmelCase							,input_labels=__lowerCAmelCase							,input_boxes=__lowerCAmelCase							,)

     _lowerCamelCase   :				Optional[Any]							=     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:						Optional[int]							,__lowerCAmelCase:						Tuple							,__lowerCAmelCase:						str							,__lowerCAmelCase:						Tuple=None							,__lowerCAmelCase:						Optional[Any]=None							,__lowerCAmelCase:						Union[str, Any]=None							,__lowerCAmelCase:						Union[str, Any]="pt"							,):







     '''simple docstring'''







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

        _lowerCamelCase   :				List[str]							=     np.array(__lowerCAmelCase    )

     if input_labels is not None:
        _lowerCamelCase   :				Union[str, Any]							=     np.array(__lowerCAmelCase    )

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

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







     '''simple docstring'''







     _lowerCamelCase   :				str							=     max([point.shape[0] for point in input_points]    )
     _lowerCamelCase   :				int							=     []
     for i, point in enumerate(__lowerCAmelCase    ):
        if point.shape[0] != expected_nb_points:
           _lowerCamelCase   :				str							=     np.concatenate(
               [point, np.zeros((expected_nb_points - point.shape[0], 2)    ) + self.point_pad_value]							,axis=0    )
           _lowerCamelCase   :				Dict							=     np.append(input_labels[i]							,[self.point_pad_value]    )
        processed_input_points.append(__lowerCAmelCase    )
     _lowerCamelCase   :				str							=     processed_input_points
     return input_points, input_labels


  def 							_lowercase					(			self:						Any							,__lowerCAmelCase:						int							,__lowerCAmelCase:						np.ndarray							,__lowerCAmelCase:						List[str]							,__lowerCAmelCase:						List[str]=False    ):







     '''simple docstring'''







     _lowerCamelCase,					_lowerCamelCase   :				int							=     original_size
     _lowerCamelCase,					_lowerCamelCase   :				Dict							=     self.image_processor._get_preprocess_shape(__lowerCAmelCase							,longest_edge=__lowerCAmelCase    )
     _lowerCamelCase   :				Dict							=     deepcopy(__lowerCAmelCase    ).astype(__lowerCAmelCase    )

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

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

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

     return coords


  def 							_lowercase					(			self:						int							,__lowerCAmelCase:						List[Any]=None							,__lowerCAmelCase:						Optional[int]=None							,__lowerCAmelCase:						str=None							,):







     '''simple docstring'''







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

     if input_labels is not None:
        if hasattr(__lowerCAmelCase							,"numpy"    ):
           _lowerCamelCase   :				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."    )
        _lowerCamelCase   :				Any							=     [np.array(__lowerCAmelCase    ) for label in input_labels]
     else:
        _lowerCamelCase   :				Tuple							=     None

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

     return input_points, input_labels, input_boxes


  @property
  def 							_lowercase					(			self:						int    ):







     '''simple docstring'''







     _lowerCamelCase   :				List[str]							=     self.image_processor.model_input_names
     return list(dict.fromkeys(__lowerCAmelCase    )    )






  def 							_lowercase					(			self:						List[str]							,*__lowerCAmelCase:						int							,**__lowerCAmelCase:						Tuple    ):







     '''simple docstring'''







     return self.image_processor.post_process_masks(*__lowerCAmelCase							,**__lowerCAmelCase    )
import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding




class 					_UpperCAmelCase			(     lowerCAmelCase  ):



 '''simple docstring'''




 __A			       =					['''image_processor''', '''tokenizer''']
 __A			       =					'''ViTImageProcessor'''
 __A			       =					('''CLIPTokenizer''', '''CLIPTokenizerFast''')







 def __init__(		self				:   Union[str, Any]							, lowercase_				:   Optional[int]=None							, lowercase_				:   Dict=None							, **lowercase_				:   List[str])						->	str:


   """simple docstring"""







   _UpperCamelCase           =    None
   if "feature_extractor" in kwargs:
     warnings.warn(
         "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
         " instead."							, lowercase_							, )
     _UpperCamelCase           =    kwargs.pop("feature_extractor")

   _UpperCamelCase           =    image_processor if image_processor is not None else feature_extractor
   if image_processor is None:
     raise ValueError("You need to specify an `image_processor`.")
   if tokenizer is None:
     raise ValueError("You need to specify a `tokenizer`.")

   super().__init__(lowercase_							, lowercase_)







 def __call__(		self				:   Any							, lowercase_				:   List[str]=None							, lowercase_				:   int=None							, lowercase_				:   Optional[Any]=None							, lowercase_				:   Dict=None							, **lowercase_				:   Dict)						->	int:


   """simple docstring"""







   if text is None and visual_prompt is None and images is None:
     raise ValueError("You have to specify either text, visual prompt or images.")

   if text is not None and visual_prompt is not None:
     raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt.")

   if text is not None:
     _UpperCamelCase           =    self.tokenizer(lowercase_							, return_tensors=lowercase_							, **lowercase_)

   if visual_prompt is not None:
     _UpperCamelCase           =    self.image_processor(lowercase_							, return_tensors=lowercase_							, **lowercase_)

   if images is not None:
     _UpperCamelCase           =    self.image_processor(lowercase_							, return_tensors=lowercase_							, **lowercase_)

   if visual_prompt is not None and images is not None:
     _UpperCamelCase           =    {
         "pixel_values": image_features.pixel_values,
         "conditional_pixel_values": prompt_features.pixel_values,
     }
     return encoding
   elif text is not None and images is not None:
     _UpperCamelCase           =    image_features.pixel_values
     return encoding
   elif text is not None:
     return encoding
   elif visual_prompt is not None:
     _UpperCamelCase           =    {
         "conditional_pixel_values": prompt_features.pixel_values,
     }
     return encoding
   else:
     return BatchEncoding(data=dict(**lowercase_)							, tensor_type=lowercase_)







 def 		__UpperCAmelCase				(		self				:   Optional[Any]							, *lowercase_				:   List[Any]							, **lowercase_				:   List[Any])						->	int:


   """simple docstring"""







   return self.tokenizer.batch_decode(*lowercase_							, **lowercase_)







 def 		__UpperCAmelCase				(		self				:   Union[str, Any]							, *lowercase_				:   Any							, **lowercase_				:   int)						->	Optional[int]:


   """simple docstring"""







   return self.tokenizer.decode(*lowercase_							, **lowercase_)







 @property
 def 		__UpperCAmelCase				(		self				:   Optional[int])						->	str:


   """simple docstring"""







   warnings.warn(
       "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."							, lowercase_							, )
   return self.image_processor_class







 @property
 def 		__UpperCAmelCase				(		self				:   int)						->	int:


   """simple docstring"""







   warnings.warn(
       "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."							, lowercase_							, )
   return self.image_processor




