'''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 (       __lowerCAmelCase				):



  """simple docstring"""
  __lowerCAmelCase				      =					["""image_processor"""]
  __lowerCAmelCase				      =					"""SamImageProcessor"""







  def __init__(							self   ,    snake_case_					):

    '''simple docstring'''







    super().__init__(snake_case_					)
    __UpperCAmelCase:					str		= self.image_processor
    __UpperCAmelCase:					List[Any]		= -10
    __UpperCAmelCase:					List[str]		= self.image_processor.size["""longest_edge"""]







  def __call__(							self   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_ = None   ,    **snake_case_   ,    ):

    '''simple docstring'''







    __UpperCAmelCase:					List[str]		= self.image_processor(
        snake_case_   ,    return_tensors=snake_case_   ,    **snake_case_   ,    )

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

    if hasattr(snake_case_   ,    """numpy"""					):  # Checks if Torch or TF tensor
      __UpperCAmelCase:					Tuple		= original_sizes.numpy()

    __UpperCAmelCase:					Dict		= self._check_and_preprocess_points(
        input_points=snake_case_   ,    input_labels=snake_case_   ,    input_boxes=snake_case_   ,    )

    __UpperCAmelCase:					Union[str, Any]		= self._normalize_and_convert(
        snake_case_   ,    snake_case_   ,    input_points=snake_case_   ,    input_labels=snake_case_   ,    input_boxes=snake_case_   ,    return_tensors=snake_case_   ,    )

    return encoding_image_processor







  def    lowercase_  (							self   ,    snake_case_   ,    snake_case_   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_="pt"   ,    ):

    '''simple docstring'''







    if input_points is not None:
      if len(snake_case_					) != len(snake_case_					):
        __UpperCAmelCase:					List[Any]		= [
            self._normalize_coordinates(self.target_size   ,    snake_case_   ,    original_sizes[0]					) for point in input_points
        ]
      else:
        __UpperCAmelCase:					Any		= [
            self._normalize_coordinates(self.target_size   ,    snake_case_   ,    snake_case_					)
            for point, original_size in zip(snake_case_   ,    snake_case_					)
        ]
      # 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:					Optional[Any]		= self._pad_points_and_labels(snake_case_   ,    snake_case_					)

      __UpperCAmelCase:					List[str]		= np.array(snake_case_					)

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

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

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

    '''simple docstring'''







    __UpperCAmelCase:					int		= max([point.shape[0] for point in input_points]					)
    __UpperCAmelCase:					Tuple		= []
    for i, point in enumerate(snake_case_					):
      if point.shape[0] != expected_nb_points:
        __UpperCAmelCase:					Optional[Any]		= np.concatenate(
            [point, np.zeros((expected_nb_points - point.shape[0], 2)					) + self.point_pad_value]   ,    axis=0					)
        __UpperCAmelCase:					Optional[int]		= np.append(input_labels[i]   ,    [self.point_pad_value]					)
      processed_input_points.append(snake_case_					)
    __UpperCAmelCase:					Union[str, Any]		= processed_input_points
    return input_points, input_labels







  def    lowercase_  (							self   ,    snake_case_   ,    snake_case_   ,    snake_case_   ,    snake_case_=False					):

    '''simple docstring'''







    __UpperCAmelCase:					Tuple		= original_size
    __UpperCAmelCase:					Any		= self.image_processor._get_preprocess_shape(snake_case_   ,    longest_edge=snake_case_					)
    __UpperCAmelCase:					Optional[Any]		= deepcopy(snake_case_					).astype(snake_case_					)

    if is_bounding_box:
      __UpperCAmelCase:					Optional[int]		= 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:					Union[str, Any]		= coords.reshape(-1   ,    4					)

    return coords







  def    lowercase_  (							self   ,    snake_case_=None   ,    snake_case_=None   ,    snake_case_=None   ,    ):

    '''simple docstring'''







    if input_points is not None:
      if hasattr(snake_case_   ,    """numpy"""					):  # Checks for TF or Torch tensor
        __UpperCAmelCase:					List[str]		= input_points.numpy().tolist()

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

    if input_labels is not None:
      if hasattr(snake_case_   ,    """numpy"""					):
        __UpperCAmelCase:					Dict		= input_labels.numpy().tolist()

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

    if input_boxes is not None:
      if hasattr(snake_case_   ,    """numpy"""					):
        __UpperCAmelCase:					List[Any]		= input_boxes.numpy().tolist()

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

    return input_points, input_labels, input_boxes







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[Any]		= self.image_processor.model_input_names
    return list(dict.fromkeys(snake_case_					)					)







  def    lowercase_  (							self   ,    *snake_case_   ,    **snake_case_					):

    '''simple docstring'''







    return self.image_processor.post_process_masks(*snake_case_   ,    **snake_case_					)






'''simple docstring'''






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import PoolFormerImageProcessor




class    a (       unittest.TestCase				):



  """simple docstring"""







  def __init__(							self   ,    snake_case_   ,    snake_case_=7   ,    snake_case_=3   ,    snake_case_=30   ,    snake_case_=400   ,    snake_case_=True   ,    snake_case_=None   ,    snake_case_=0.9   ,    snake_case_=None   ,    snake_case_=True   ,    snake_case_=[0.5, 0.5, 0.5]   ,    snake_case_=[0.5, 0.5, 0.5]   ,    ):

    '''simple docstring'''







    __UpperCAmelCase:					List[Any]		= size if size is not None else {"""shortest_edge""": 30}
    __UpperCAmelCase:					str		= crop_size if crop_size is not None else {"""height""": 30, """width""": 30}
    __UpperCAmelCase:					Dict		= parent
    __UpperCAmelCase:					Union[str, Any]		= batch_size
    __UpperCAmelCase:					List[Any]		= num_channels
    __UpperCAmelCase:					List[str]		= min_resolution
    __UpperCAmelCase:					List[str]		= max_resolution
    __UpperCAmelCase:					Tuple		= do_resize_and_center_crop
    __UpperCAmelCase:					Union[str, Any]		= size
    __UpperCAmelCase:					str		= crop_pct
    __UpperCAmelCase:					List[Any]		= crop_size
    __UpperCAmelCase:					str		= do_normalize
    __UpperCAmelCase:					Union[str, Any]		= image_mean
    __UpperCAmelCase:					List[str]		= image_std







  def    lowercase_  (							self					):

    '''simple docstring'''







    return {
        "size": self.size,
        "do_resize_and_center_crop": self.do_resize_and_center_crop,
        "crop_pct": self.crop_pct,
        "crop_size": self.crop_size,
        "do_normalize": self.do_normalize,
        "image_mean": self.image_mean,
        "image_std": self.image_std,
    }




@require_torch
@require_vision
class    a (       __lowerCAmelCase						,  unittest.TestCase				):



  """simple docstring"""
  __lowerCAmelCase				      =					PoolFormerImageProcessor if is_vision_available() else None







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= PoolFormerImageProcessingTester(self					)







  @property
  def    lowercase_  (							self					):

    '''simple docstring'''







    return self.image_processor_tester.prepare_image_processor_dict()







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[Any]		= self.image_processing_class(**self.image_processor_dict					)
    self.assertTrue(hasattr(snake_case_   ,    """do_resize_and_center_crop"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """size"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """crop_pct"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """do_normalize"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """image_mean"""					)					)
    self.assertTrue(hasattr(snake_case_   ,    """image_std"""					)					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[str]		= self.image_processing_class.from_dict(self.image_processor_dict					)
    self.assertEqual(image_processor.size   ,    {"""shortest_edge""": 30}					)
    self.assertEqual(image_processor.crop_size   ,    {"""height""": 30, """width""": 30}					)

    __UpperCAmelCase:					Dict		= self.image_processing_class.from_dict(self.image_processor_dict   ,    size=42   ,    crop_size=84					)
    self.assertEqual(image_processor.size   ,    {"""shortest_edge""": 42}					)
    self.assertEqual(image_processor.crop_size   ,    {"""height""": 84, """width""": 84}					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    pass







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= self.image_processing_class(**self.image_processor_dict					)
    # create random PIL images
    __UpperCAmelCase:					Optional[Any]		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    Image.Image					)

    # Test not batched input
    __UpperCAmelCase:					Optional[int]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values

    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					Any		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[Any]		= self.image_processing_class(**self.image_processor_dict					)
    # create random numpy tensors
    __UpperCAmelCase:					Union[str, Any]		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_   ,    numpify=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    np.ndarray					)

    # Test not batched input
    __UpperCAmelCase:					Union[str, Any]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					str		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Any		= self.image_processing_class(**self.image_processor_dict					)
    # create random PyTorch tensors
    __UpperCAmelCase:					Dict		= prepare_image_inputs(self.image_processor_tester   ,    equal_resolution=snake_case_   ,    torchify=snake_case_					)
    for image in image_inputs:
      self.assertIsInstance(snake_case_   ,    torch.Tensor					)

    # Test not batched input
    __UpperCAmelCase:					Optional[int]		= image_processing(image_inputs[0]   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            1,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )

    # Test batched
    __UpperCAmelCase:					Optional[int]		= image_processing(snake_case_   ,    return_tensors="""pt"""					).pixel_values
    self.assertEqual(
        encoded_images.shape   ,    (
            self.image_processor_tester.batch_size,
            self.image_processor_tester.num_channels,
            self.image_processor_tester.crop_size["""height"""],
            self.image_processor_tester.crop_size["""width"""],
        )   ,    )