import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch

    from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

    if is_vision_available():
        from transformers import MaskaFormerImageProcessor

if is_vision_available():
    from PIL import Image
class     a_			:






 '''simple docstring'''






 def __init__(      self :  List[Any]      ,   lowercase__ :  str      ,   lowercase__ :  Dict=2      ,   lowercase__ :  str=True      ,   lowercase__ :  Tuple=False      ,   lowercase__ :  int=10      ,   lowercase__ :  Optional[int]=3      ,   lowercase__ :  Tuple=32 * 8      ,   lowercase__ :  List[Any]=32 * 8      ,   lowercase__ :  Optional[int]=4      ,   lowercase__ :  Optional[Any]=64      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = parent
        lowerCAmelCase__					     = batch_size
        lowerCAmelCase__					     = is_training
        lowerCAmelCase__					     = use_auxiliary_loss
        lowerCAmelCase__					     = num_queries
        lowerCAmelCase__					     = num_channels
        lowerCAmelCase__					     = min_size
        lowerCAmelCase__					     = max_size
        lowerCAmelCase__					     = num_labels
        lowerCAmelCase__					     = hidden_dim
        lowerCAmelCase__					     = hidden_dim




 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        lowerCAmelCase__					     = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to(
            lowercase__)

        lowerCAmelCase__					     = torch.ones([self.batch_size, self.min_size, self.max_size]      ,   device=lowercase__)

        lowerCAmelCase__					     = (
            torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]      ,   device=lowercase__) > 0.5
        ).float()
        lowerCAmelCase__					     = (torch.rand((self.batch_size, self.num_labels)      ,   device=lowercase__) > 0.5).long()

        lowerCAmelCase__					     = self.get_config()
        return config, pixel_values, pixel_mask, mask_labels, class_labels




 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerConfig(
            hidden_size=self.hidden_dim      ,   )
        lowerCAmelCase__					     = self.num_queries
        lowerCAmelCase__					     = self.num_labels

        lowerCAmelCase__					     = [1, 1, 1, 1]
        lowerCAmelCase__					     = self.num_channels

        lowerCAmelCase__					     = 64
        lowerCAmelCase__					     = 128
        lowerCAmelCase__					     = self.hidden_dim
        lowerCAmelCase__					     = self.hidden_dim
        lowerCAmelCase__					     = self.hidden_dim
        return config




 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = self.prepare_config_and_inputs()
        lowerCAmelCase__					     = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask}
        return config, inputs_dict




 def 		__snake_case						(      self :  int      ,   lowercase__ :  Any      ,   lowercase__ :  Union[str, Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = output.encoder_hidden_states
        lowerCAmelCase__					     = output.pixel_decoder_hidden_states
        lowerCAmelCase__					     = output.transformer_decoder_hidden_states

        self.parent.assertTrue(len(lowercase__)      ,   len(config.backbone_config.depths))
        self.parent.assertTrue(len(lowercase__)      ,   len(config.backbone_config.depths))
        self.parent.assertTrue(len(lowercase__)      ,   config.decoder_layers)




 def 		__snake_case						(      self :  List[Any]      ,   lowercase__ :  str      ,   lowercase__ :  Dict      ,   lowercase__ :  Optional[Any]      ,   lowercase__ :  Optional[int]=False):







        '''simple docstring'''



        with torch.no_grad():
               lowerCAmelCase__					     = MaskaFormerModel(config=lowercase__)
               model.to(lowercase__)
               model.eval()

               lowerCAmelCase__					     = model(pixel_values=lowercase__      ,   pixel_mask=lowercase__)
               lowerCAmelCase__					     = model(lowercase__      ,   output_hidden_states=lowercase__)

        self.parent.assertEqual(
            output.transformer_decoder_last_hidden_state.shape      ,   (self.batch_size, self.num_queries, self.hidden_dim)      ,   )
        # let's ensure the other two hidden state exists
        self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None)
        self.parent.assertTrue(output.encoder_last_hidden_state is not None)

        if output_hidden_states:
               self.check_output_hidden_state(lowercase__      ,   lowercase__)




 def 		__snake_case						(      self :  Optional[Any]      ,   lowercase__ :  List[Any]      ,   lowercase__ :  Tuple      ,   lowercase__ :  List[Any]      ,   lowercase__ :  Optional[int]      ,   lowercase__ :  Union[str, Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerForUniversalSegmentation(config=lowercase__)
        model.to(lowercase__)
        model.eval()

        def comm_check_on_output(lowercase__ :  str):
               # let's still check that all the required stuff is there
               self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None)
               self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None)
               self.parent.assertTrue(result.encoder_last_hidden_state is not None)
               # okay, now we need to check the logits shape
               # due to the encoder compression, masks have a //4 spatial size
               self.parent.assertEqual(
                   result.masks_queries_logits.shape      ,   (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)      ,   )
               # + 1 for null class
               self.parent.assertEqual(
                   result.class_queries_logits.shape      ,   (self.batch_size, self.num_queries, self.num_labels + 1))

        with torch.no_grad():
               lowerCAmelCase__					     = model(pixel_values=lowercase__      ,   pixel_mask=lowercase__)
               lowerCAmelCase__					     = model(lowercase__)

               comm_check_on_output(lowercase__)

               lowerCAmelCase__					     = model(
                   pixel_values=lowercase__      ,   pixel_mask=lowercase__      ,   mask_labels=lowercase__      ,   class_labels=lowercase__)

        comm_check_on_output(lowercase__)

        self.parent.assertTrue(result.loss is not None)
        self.parent.assertEqual(result.loss.shape      ,   torch.Size([1]))






@require_torch
class     a_			(						SCREAMING_SNAKE_CASE	,					SCREAMING_SNAKE_CASE	,					unittest.TestCase						):






 '''simple docstring'''






 UpperCAmelCase_     			= (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
 UpperCAmelCase_     			= {'feature-extraction': MaskaFormerModel} if is_torch_available() else {}

 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False
 UpperCAmelCase_     			= False




 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerModelTester(self)
        lowerCAmelCase__					     = ConfigTester(self      ,   config_class=lowercase__      ,   has_text_modality=lowercase__)




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        self.config_tester.run_common_tests()




 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskaformer_model(lowercase__      ,   **lowercase__      ,   output_hidden_states=lowercase__)




 def 		__snake_case						(      self :  Any):







        '''simple docstring'''



        lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*lowercase__)




 @unittest.skip(reason='Mask2Former does not use inputs_embeds')
 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        pass




 @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method')
 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        pass




 @unittest.skip(reason='Mask2Former is not a generative model')
 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        pass




 @unittest.skip(reason='Mask2Former does not use token embeddings')
 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        pass




 @require_torch_multi_gpu
 @unittest.skip(
     reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`')
 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        pass




 @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        pass




 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               lowerCAmelCase__					     = model_class(lowercase__)
               lowerCAmelCase__					     = inspect.signature(model.forward)
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               lowerCAmelCase__					     = [*signature.parameters.keys()]

               lowerCAmelCase__					     = ['pixel_values']
               self.assertListEqual(arg_names[:1]      ,   lowercase__)




 @slow
 def 		__snake_case						(      self :  int):







        '''simple docstring'''



        for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
               lowerCAmelCase__					     = MaskaFormerModel.from_pretrained(lowercase__)
               self.assertIsNotNone(lowercase__)




 def 		__snake_case						(      self :  Any):







        '''simple docstring'''



        lowerCAmelCase__					     = (self.model_tester.min_size,) * 2
        lowerCAmelCase__					     = {
            'pixel_values': torch.randn((2, 3, *size)      ,   device=lowercase__),
            'mask_labels': torch.randn((2, 10, *size)      ,   device=lowercase__),
            'class_labels': torch.zeros(2      ,   10      ,   device=lowercase__).long(),
        }
        lowerCAmelCase__					     = self.model_tester.get_config()

        lowerCAmelCase__					     = MaskaFormerForUniversalSegmentation(lowercase__).to(lowercase__)
        lowerCAmelCase__					     = model(**lowercase__)
        self.assertTrue(outputs.loss is not None)




 def 		__snake_case						(      self :  Optional[int]):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskaformer_model(lowercase__      ,   **lowercase__      ,   output_hidden_states=lowercase__)




 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               lowerCAmelCase__					     = model_class(lowercase__).to(lowercase__)
               lowerCAmelCase__					     = model(**lowercase__      ,   output_attentions=lowercase__)
               self.assertTrue(outputs.attentions is not None)




 def 		__snake_case						(      self :  Tuple):







        '''simple docstring'''



        if not self.model_tester.is_training:
               return

        lowerCAmelCase__					     = self.all_model_classes[1]
        lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()

        lowerCAmelCase__					     = model_class(lowercase__)
        model.to(lowercase__)
        model.train()

        lowerCAmelCase__					     = model(lowercase__      ,   mask_labels=lowercase__      ,   class_labels=lowercase__).loss
        loss.backward()




 def 		__snake_case						(      self :  Union[str, Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.all_model_classes[1]
        lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = self.model_tester.prepare_config_and_inputs()
        lowerCAmelCase__					     = True
        lowerCAmelCase__					     = True

        lowerCAmelCase__					     = model_class(lowercase__).to(lowercase__)
        model.train()

        lowerCAmelCase__					     = model(lowercase__      ,   mask_labels=lowercase__      ,   class_labels=lowercase__)

        lowerCAmelCase__					     = outputs.encoder_hidden_states[0]
        encoder_hidden_states.retain_grad()

        lowerCAmelCase__					     = outputs.pixel_decoder_hidden_states[0]
        pixel_decoder_hidden_states.retain_grad()

        lowerCAmelCase__					     = outputs.transformer_decoder_hidden_states[0]
        transformer_decoder_hidden_states.retain_grad()

        lowerCAmelCase__					     = outputs.attentions[0]
        attentions.retain_grad()

        outputs.loss.backward(retain_graph=lowercase__)

        self.assertIsNotNone(encoder_hidden_states.grad)
        self.assertIsNotNone(pixel_decoder_hidden_states.grad)
        self.assertIsNotNone(transformer_decoder_hidden_states.grad)
        self.assertIsNotNone(attentions.grad)






lowerCAmelCase__     						=			1e-4






def 				__lowerCamelCase		(						):
       lowerCAmelCase__					     = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
       return image



@require_vision
@slow
class     a_			(						unittest.TestCase						):






 '''simple docstring'''






 @cached_property
 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        return "facebook/mask2former-swin-small-coco-instance"




 @cached_property
 def 		__snake_case						(      self :  str):







        '''simple docstring'''



        return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None




 def 		__snake_case						(      self :  Dict):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerModel.from_pretrained(self.model_checkpoints).to(lowercase__)
        lowerCAmelCase__					     = self.default_image_processor
        lowerCAmelCase__					     = prepare_img()
        lowerCAmelCase__					     = image_processor(lowercase__      ,   return_tensors='pt').to(lowercase__)
        lowerCAmelCase__					     = inputs['pixel_values'].shape
        # check size is divisible by 32
        self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
        # check size
        self.assertEqual(lowercase__      ,   (1, 3, 384, 384))

        with torch.no_grad():
               lowerCAmelCase__					     = model(**lowercase__)

        lowerCAmelCase__					     = torch.tensor(
            [[-0.2_790, -1.0_717, -1.1_668], [-0.5_128, -0.3_128, -0.4_987], [-0.5_832, 0.1_971, -0.0_197]]).to(lowercase__)
        self.assertTrue(
            torch.allclose(
                outputs.encoder_last_hidden_state[0, 0, :3, :3]      ,   lowercase__      ,   atol=lowercase__))

        lowerCAmelCase__					     = torch.tensor(
            [[0.8_973, 1.1_847, 1.1_776], [1.1_934, 1.5_040, 1.5_128], [1.1_153, 1.4_486, 1.4_951]]).to(lowercase__)
        self.assertTrue(
            torch.allclose(
                outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]      ,   lowercase__      ,   atol=lowercase__))

        lowerCAmelCase__					     = torch.tensor(
            [[2.1_152, 1.7_000, -0.8_603], [1.5_808, 1.8_004, -0.9_353], [1.6_043, 1.7_495, -0.5_999]]).to(lowercase__)
        self.assertTrue(
            torch.allclose(
                outputs.transformer_decoder_last_hidden_state[0, :3, :3]      ,   lowercase__      ,   atol=lowercase__))




 def 		__snake_case						(      self :  Optional[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(lowercase__).eval()
        lowerCAmelCase__					     = self.default_image_processor
        lowerCAmelCase__					     = prepare_img()
        lowerCAmelCase__					     = image_processor(lowercase__      ,   return_tensors='pt').to(lowercase__)
        lowerCAmelCase__					     = inputs['pixel_values'].shape
        # check size is divisible by 32
        self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
        # check size
        self.assertEqual(lowercase__      ,   (1, 3, 384, 384))

        with torch.no_grad():
               lowerCAmelCase__					     = model(**lowercase__)
        # masks_queries_logits
        lowerCAmelCase__					     = outputs.masks_queries_logits
        self.assertEqual(
            masks_queries_logits.shape      ,   (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4))
        lowerCAmelCase__					     = [
            [-8.7_839, -9.0_056, -8.8_121],
            [-7.4_104, -7.0_313, -6.5_401],
            [-6.6_105, -6.3_427, -6.4_675],
        ]
        lowerCAmelCase__					     = torch.tensor(lowercase__).to(lowercase__)
        self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]      ,   lowercase__      ,   atol=lowercase__))
        # class_queries_logits
        lowerCAmelCase__					     = outputs.class_queries_logits
        self.assertEqual(class_queries_logits.shape      ,   (1, model.config.num_queries, model.config.num_labels + 1))
        lowerCAmelCase__					     = torch.tensor(
            [
                [1.8_324, -8.0_835, -4.1_922],
                [0.8_450, -9.0_050, -3.6_053],
                [0.3_045, -7.7_293, -3.0_275],
            ]).to(lowercase__)
        self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]      ,   lowercase__      ,   atol=lowercase__))




 def 		__snake_case						(      self :  List[str]):







        '''simple docstring'''



        lowerCAmelCase__					     = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(lowercase__).eval()
        lowerCAmelCase__					     = self.default_image_processor

        lowerCAmelCase__					     = image_processor(
            [np.zeros((3, 800, 1_333)), np.zeros((3, 800, 1_333))]      ,   segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)]      ,   return_tensors='pt'      ,   )

        lowerCAmelCase__					     = inputs['pixel_values'].to(lowercase__)
        lowerCAmelCase__					     = [el.to(lowercase__) for el in inputs['mask_labels']]
        lowerCAmelCase__					     = [el.to(lowercase__) for el in inputs['class_labels']]

        with torch.no_grad():
               lowerCAmelCase__					     = model(**lowercase__)

        self.assertTrue(outputs.loss is not None)

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_			(						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 UpperCAmelCase_     			= ['image_processor']
 UpperCAmelCase_     			= 'SamImageProcessor'




 def __init__(      self :  Tuple      ,   lowercase__ :  Dict):







        '''simple docstring'''



        super().__init__(lowercase__)
        lowerCAmelCase__					     = self.image_processor
        lowerCAmelCase__					     = -10
        lowerCAmelCase__					     = self.image_processor.size['longest_edge']




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







        '''simple docstring'''



        lowerCAmelCase__					     = self.image_processor(
            lowercase__      ,   return_tensors=lowercase__      ,   **lowercase__      ,   )

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

        if hasattr(lowercase__      ,   'numpy'):  # Checks if Torch or TF tensor
               lowerCAmelCase__					     = original_sizes.numpy()

        lowerCAmelCase__     , lowerCAmelCase__     , lowerCAmelCase__					     = self._check_and_preprocess_points(
            input_points=lowercase__      ,   input_labels=lowercase__      ,   input_boxes=lowercase__      ,   )

        lowerCAmelCase__					     = self._normalize_and_convert(
            lowercase__      ,   lowercase__      ,   input_points=lowercase__      ,   input_labels=lowercase__      ,   input_boxes=lowercase__      ,   return_tensors=lowercase__      ,   )

        return encoding_image_processor




 def 		__snake_case						(      self :  Optional[Any]      ,   lowercase__ :  List[str]      ,   lowercase__ :  List[str]      ,   lowercase__ :  str=None      ,   lowercase__ :  Optional[int]=None      ,   lowercase__ :  str=None      ,   lowercase__ :  Optional[Any]="pt"      ,   ):







        '''simple docstring'''



        if input_points is not None:
               if len(lowercase__) != len(lowercase__):
                      lowerCAmelCase__					     = [
                          self._normalize_coordinates(self.target_size      ,   lowercase__      ,   original_sizes[0]) for point in input_points
                      ]
               else:
                      lowerCAmelCase__					     = [
                          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:
                             lowerCAmelCase__     , lowerCAmelCase__					     = self._pad_points_and_labels(lowercase__      ,   lowercase__)

               lowerCAmelCase__					     = np.array(lowercase__)

        if input_labels is not None:
               lowerCAmelCase__					     = np.array(lowercase__)

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

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







        '''simple docstring'''



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




 def 		__snake_case						(      self :  Optional[Any]      ,   lowercase__ :  int      ,   lowercase__ :  np.ndarray      ,   lowercase__ :  int      ,   lowercase__ :  Optional[Any]=False):







        '''simple docstring'''



        lowerCAmelCase__     , lowerCAmelCase__					     = original_size
        lowerCAmelCase__     , lowerCAmelCase__					     = self.image_processor._get_preprocess_shape(lowercase__      ,   longest_edge=lowercase__)
        lowerCAmelCase__					     = deepcopy(lowercase__).astype(lowercase__)

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

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

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

        return coords




 def 		__snake_case						(      self :  Dict      ,   lowercase__ :  Optional[Any]=None      ,   lowercase__ :  Tuple=None      ,   lowercase__ :  int=None      ,   ):







        '''simple docstring'''



        if input_points is not None:
               if hasattr(lowercase__      ,   'numpy'):  # Checks for TF or Torch tensor
                      lowerCAmelCase__					     = 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.')
               lowerCAmelCase__					     = [np.array(lowercase__) for input_point in input_points]
        else:
               lowerCAmelCase__					     = None

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

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

        return input_points, input_labels, input_boxes




 @property
 def 		__snake_case						(      self :  List[Any]):







        '''simple docstring'''



        lowerCAmelCase__					     = self.image_processor.model_input_names
        return list(dict.fromkeys(lowercase__))




 def 		__snake_case						(      self :  int      ,   *lowercase__ :  int      ,   **lowercase__ :  int):







        '''simple docstring'''



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