





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

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

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

     A__,     A__,     A__    =      self._check_and_preprocess_points(
         input_points=lowercase_						,	input_labels=lowercase_						,	input_boxes=lowercase_						,	)

     A__    =      self._normalize_and_convert(
         lowercase_						,	lowercase_						,	input_points=lowercase_						,	input_labels=lowercase_						,	input_boxes=lowercase_						,	return_tensors=lowercase_						,	)

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

         A__    =      np.array(lowercase_							)

     if input_labels is not None:
         A__    =      np.array(lowercase_							)

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

     if input_boxes is not None:
         if return_tensors == "pt":
             A__    =      torch.from_numpy(lowercase_							)
             # boxes batch size of 1 by default
             A__    =      input_boxes.unsqueeze(1							) if len(input_boxes.shape							) != 3 else input_boxes
         elif return_tensors == "tf":
             A__    =      tf.convert_to_tensor(lowercase_							)
             # boxes batch size of 1 by default
             A__    =      tf.expand_dims(lowercase_						,	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__    =      torch.from_numpy(lowercase_							)
             # point batch size of 1 by default
             A__    =      input_points.unsqueeze(1							) if len(input_points.shape							) != 4 else input_points
         elif return_tensors == "tf":
             A__    =      tf.convert_to_tensor(lowercase_							)
             # point batch size of 1 by default
             A__    =      tf.expand_dims(lowercase_						,	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__    =      torch.from_numpy(lowercase_							)
             # point batch size of 1 by default
             A__    =      input_labels.unsqueeze(1							) if len(input_labels.shape							) != 3 else input_labels
         elif return_tensors == "tf":
             A__    =      tf.convert_to_tensor(lowercase_							)
             # point batch size of 1 by default
             A__    =      tf.expand_dims(lowercase_						,	1							) if len(input_labels.shape							) != 3 else input_labels
         encoding_image_processor.update({"input_labels": input_labels}							)

     return encoding_image_processor
 def 					UpperCAmelCase_							(    self				:Any						,	lowercase_				:Union[str, Any]						,	lowercase_				:Union[str, Any]							)->							Dict:
     A__    =      max([point.shape[0] for point in input_points]							)
     A__    =      []
     for i, point in enumerate(lowercase_							):
         if point.shape[0] != expected_nb_points:
             A__    =      np.concatenate(
                 [point, np.zeros((expected_nb_points - point.shape[0], 2)							) + self.point_pad_value]						,	axis=0							)
             A__    =      np.append(input_labels[i]						,	[self.point_pad_value]							)
         processed_input_points.append(lowercase_							)
     A__    =      processed_input_points
     return input_points, input_labels
 def 					UpperCAmelCase_							(    self				:Tuple						,	lowercase_				:int						,	lowercase_				:np.ndarray						,	lowercase_				:int						,	lowercase_				:Optional[int]=False							)->							np.ndarray:
     A__,     A__    =      original_size
     A__,     A__    =      self.image_processor._get_preprocess_shape(lowercase_						,	longest_edge=lowercase_							)
     A__    =      deepcopy(lowercase_							).astype(lowercase_							)

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

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

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

     return coords
 def 					UpperCAmelCase_							(    self				:Optional[Any]						,	lowercase_				:Dict=None						,	lowercase_				:List[Any]=None						,	lowercase_				:Optional[Any]=None						,	)->							List[Any]:
     if input_points is not None:
         if hasattr(lowercase_						,	"numpy"							):  # Checks for TF or Torch tensor
             A__    =      input_points.numpy().tolist()

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

     if input_labels is not None:
         if hasattr(lowercase_						,	"numpy"							):
             A__    =      input_labels.numpy().tolist()

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

     if input_boxes is not None:
         if hasattr(lowercase_						,	"numpy"							):
             A__    =      input_boxes.numpy().tolist()

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

     return input_points, input_labels, input_boxes
 @property
 def 					UpperCAmelCase_							(    self				:Optional[Any]							)->							Dict:
     A__    =      self.image_processor.model_input_names
     return list(dict.fromkeys(lowercase_							)							)



 def 					UpperCAmelCase_							(    self				:Optional[int]						,	*lowercase_				:List[Any]						,	**lowercase_				:Dict							)->							Dict:
     return self.image_processor.post_process_masks(*lowercase_						,	**lowercase_							)










'''simple docstring'''

__lowerCAmelCase							:     Dict		     ="\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n"

__lowerCAmelCase							:     Optional[Any]		     =[{"type": "code", "content": INSTALL_CONTENT}]
__lowerCAmelCase							:     Tuple		     ={
    "{processor_class}": "FakeProcessorClass",
    "{model_class}": "FakeModelClass",
    "{object_class}": "FakeObjectClass",
}



