





import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VideoMAEConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch
       from torch import nn

       from transformers import (
           MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING,
           VideoMAEForPreTraining,
           VideoMAEForVideoClassification,
           VideoMAEModel,
       )
       from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from transformers import VideoMAEImageProcessor




class        SCREAMING_SNAKE_CASE__					:



 def __init__(				self,__lowerCamelCase,__lowerCamelCase=13,__lowerCamelCase=10,__lowerCamelCase=3,__lowerCamelCase=2,__lowerCamelCase=2,__lowerCamelCase=2,__lowerCamelCase=True,__lowerCamelCase=True,__lowerCamelCase=32,__lowerCamelCase=5,__lowerCamelCase=4,__lowerCamelCase=37,__lowerCamelCase="gelu",__lowerCamelCase=0.1,__lowerCamelCase=0.1,__lowerCamelCase=10,__lowerCamelCase=0.02,__lowerCamelCase=0.9,__lowerCamelCase=None,):
        A__		   =		parent
        A__		   =		batch_size
        A__		   =		image_size
        A__		   =		num_channels
        A__		   =		patch_size
        A__		   =		tubelet_size
        A__		   =		num_frames
        A__		   =		is_training
        A__		   =		use_labels
        A__		   =		hidden_size
        A__		   =		num_hidden_layers
        A__		   =		num_attention_heads
        A__		   =		intermediate_size
        A__		   =		hidden_act
        A__		   =		hidden_dropout_prob
        A__		   =		attention_probs_dropout_prob
        A__		   =		type_sequence_label_size
        A__		   =		initializer_range
        A__		   =		mask_ratio
        A__		   =		scope

        # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame
        A__		   =		(image_size // patch_size) ** 2
        A__		   =		(num_frames // tubelet_size) * self.num_patches_per_frame

        # use this variable to define bool_masked_pos
        A__		   =		int(mask_ratio * self.seq_length					)



 def 							UpperCamelCase     (				self					):
        A__		   =		floats_tensor(
            [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]					)

        A__		   =		None
        if self.use_labels:
               A__		   =		ids_tensor([self.batch_size],self.type_sequence_label_size					)

        A__		   =		self.get_config()

        return config, pixel_values, labels



 def 							UpperCamelCase     (				self					):
        return VideoMAEConfig(
            image_size=self.image_size,patch_size=self.patch_size,num_channels=self.num_channels,num_frames=self.num_frames,tubelet_size=self.tubelet_size,hidden_size=self.hidden_size,num_hidden_layers=self.num_hidden_layers,num_attention_heads=self.num_attention_heads,intermediate_size=self.intermediate_size,hidden_act=self.hidden_act,hidden_dropout_prob=self.hidden_dropout_prob,attention_probs_dropout_prob=self.attention_probs_dropout_prob,is_decoder=__lowerCamelCase,initializer_range=self.initializer_range,)



 def 							UpperCamelCase     (				self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase					):
        A__		   =		VideoMAEModel(config=__lowerCamelCase					)
        model.to(__lowerCamelCase					)
        model.eval()
        A__		   =		model(__lowerCamelCase					)
        self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, self.seq_length, self.hidden_size)					)



 def 							UpperCamelCase     (				self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase					):
        A__		   =		VideoMAEForPreTraining(__lowerCamelCase					)
        model.to(__lowerCamelCase					)
        model.eval()
        # important: each video needs to have the same number of masked patches
        # hence we define a single mask, which we then repeat for each example in the batch
        A__		   =		torch.ones((self.num_masks,)					)
        A__		   =		torch.cat([mask, torch.zeros(self.seq_length - mask.size(0					)					)]					)
        A__		   =		mask.expand(self.batch_size,-1					).bool()

        A__		   =		model(__lowerCamelCase,__lowerCamelCase					)
        # model only returns predictions for masked patches
        A__		   =		mask.sum().item()
        A__		   =		3 * self.tubelet_size * self.patch_size**2
        self.parent.assertEqual(result.logits.shape,(self.batch_size, num_masked_patches, decoder_num_labels)					)




 def 							UpperCamelCase     (				self					):
        A__		   =		self.prepare_config_and_inputs()
        A__   ,      A__   ,      A__		   =		config_and_inputs
        A__		   =		{'''pixel_values''': pixel_values}
        return config, inputs_dict




@require_torch
class        SCREAMING_SNAKE_CASE__					(		UpperCamelCase__							,   UpperCamelCase__							,   unittest.TestCase ):
 __SCREAMING_SNAKE_CASE							=      (
     (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else ()
 )
 __SCREAMING_SNAKE_CASE							=      (
     {'''feature-extraction''': VideoMAEModel, '''video-classification''': VideoMAEForVideoClassification}
     if is_torch_available()
     else {}
 )

 __SCREAMING_SNAKE_CASE							=      False
 __SCREAMING_SNAKE_CASE							=      False
 __SCREAMING_SNAKE_CASE							=      False
 __SCREAMING_SNAKE_CASE							=      False



 def 							UpperCamelCase     (				self					):
        A__		   =		VideoMAEModelTester(self					)
        A__		   =		ConfigTester(self,config_class=__lowerCamelCase,has_text_modality=__lowerCamelCase,hidden_size=37					)



 def 							UpperCamelCase     (				self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase=False					):
        A__		   =		copy.deepcopy(__lowerCamelCase					)

        if model_class == VideoMAEForPreTraining:
               # important: each video needs to have the same number of masked patches
               # hence we define a single mask, which we then repeat for each example in the batch
               A__		   =		torch.ones((self.model_tester.num_masks,)					)
               A__		   =		torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0					)					)]					)
               A__		   =		mask.expand(self.model_tester.batch_size,-1					).bool()
               A__		   =		bool_masked_pos.to(__lowerCamelCase					)

        if return_labels:
               if model_class in [
                   *get_values(__lowerCamelCase					),
               ]:
                      A__		   =		torch.zeros(
                          self.model_tester.batch_size,dtype=torch.long,device=__lowerCamelCase					)

        return inputs_dict



 def 							UpperCamelCase     (				self					):
        self.config_tester.run_common_tests()



 @unittest.skip(reason='''VideoMAE does not use inputs_embeds'''					)
 def 							UpperCamelCase     (				self					):
        pass



 def 							UpperCamelCase     (				self					):
        A__   ,      A__		   =		self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               A__		   =		model_class(__lowerCamelCase					)
               self.assertIsInstance(model.get_input_embeddings(),(nn.Module)					)
               A__		   =		model.get_output_embeddings()
               self.assertTrue(x is None or isinstance(__lowerCamelCase,nn.Linear					)					)



 def 							UpperCamelCase     (				self					):
        A__   ,      A__		   =		self.model_tester.prepare_config_and_inputs_for_common()

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

               A__		   =		['''pixel_values''']
               self.assertListEqual(arg_names[:1],__lowerCamelCase					)



 def 							UpperCamelCase     (				self					):
        A__		   =		self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowerCamelCase					)



 def 							UpperCamelCase     (				self					):
        A__		   =		self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_pretraining(*__lowerCamelCase					)



 @slow
 def 							UpperCamelCase     (				self					):
        for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               A__		   =		VideoMAEModel.from_pretrained(__lowerCamelCase					)
               self.assertIsNotNone(__lowerCamelCase					)



 def 							UpperCamelCase     (				self					):
        if not self.has_attentions:
               pass

        else:
               A__   ,      A__		   =		self.model_tester.prepare_config_and_inputs_for_common()
               A__		   =		True

               for model_class in self.all_model_classes:
                      A__		   =		self.model_tester.seq_length - self.model_tester.num_masks
                      A__		   =		(
                          num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length
                      )

                      A__		   =		True
                      A__		   =		False
                      A__		   =		True
                      A__		   =		model_class(__lowerCamelCase					)
                      model.to(__lowerCamelCase					)
                      model.eval()
                      with torch.no_grad():
                             A__		   =		model(**self._prepare_for_class(__lowerCamelCase,__lowerCamelCase					)					)
                      A__		   =		outputs.attentions
                      self.assertEqual(len(__lowerCamelCase					),self.model_tester.num_hidden_layers					)

                      # check that output_attentions also work using config
                      del inputs_dict["output_attentions"]
                      A__		   =		True
                      A__		   =		model_class(__lowerCamelCase					)
                      model.to(__lowerCamelCase					)
                      model.eval()
                      with torch.no_grad():
                             A__		   =		model(**self._prepare_for_class(__lowerCamelCase,__lowerCamelCase					)					)
                      A__		   =		outputs.attentions
                      self.assertEqual(len(__lowerCamelCase					),self.model_tester.num_hidden_layers					)

                      self.assertListEqual(
                          list(attentions[0].shape[-3:]					),[self.model_tester.num_attention_heads, seq_len, seq_len],)
                      A__		   =		len(__lowerCamelCase					)

                      # Check attention is always last and order is fine
                      A__		   =		True
                      A__		   =		True
                      A__		   =		model_class(__lowerCamelCase					)
                      model.to(__lowerCamelCase					)
                      model.eval()
                      with torch.no_grad():
                             A__		   =		model(**self._prepare_for_class(__lowerCamelCase,__lowerCamelCase					)					)

                      self.assertEqual(out_len + 1,len(__lowerCamelCase					)					)

                      A__		   =		outputs.attentions

                      self.assertEqual(len(__lowerCamelCase					),self.model_tester.num_hidden_layers					)
                      self.assertListEqual(
                          list(self_attentions[0].shape[-3:]					),[self.model_tester.num_attention_heads, seq_len, seq_len],)



 def 							UpperCamelCase     (				self					):
        def check_hidden_states_output(__lowerCamelCase,__lowerCamelCase,__lowerCamelCase					):
               A__		   =		model_class(__lowerCamelCase					)
               model.to(__lowerCamelCase					)
               model.eval()

               with torch.no_grad():
                      A__		   =		model(**self._prepare_for_class(__lowerCamelCase,__lowerCamelCase					)					)

               A__		   =		outputs.hidden_states
               A__		   =		self.model_tester.num_hidden_layers + 1
               self.assertEqual(len(__lowerCamelCase					),__lowerCamelCase					)

               A__		   =		self.model_tester.seq_length - self.model_tester.num_masks
               A__		   =		num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length

               self.assertListEqual(
                   list(hidden_states[0].shape[-2:]					),[seq_length, self.model_tester.hidden_size],)

        A__   ,      A__		   =		self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
               A__		   =		True
               check_hidden_states_output(__lowerCamelCase,__lowerCamelCase,__lowerCamelCase					)

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               A__		   =		True

               check_hidden_states_output(__lowerCamelCase,__lowerCamelCase,__lowerCamelCase					)




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


def       UpperCamelCase__(			)->Union[str, Any]:
       A__		   =		hf_hub_download(
           repo_id='''hf-internal-testing/spaghetti-video'''					,	filename='''eating_spaghetti.npy'''					,	repo_type='''dataset'''    )
       A__		   =		np.load(UpperCamelCase__    )
       return list(UpperCamelCase__    )




@require_torch
@require_vision
class        SCREAMING_SNAKE_CASE__					(		unittest.TestCase ):



 @cached_property
 def 							UpperCamelCase     (				self					):
        # logits were tested with a different mean and std, so we use the same here
        return (
            VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5],image_std=[0.5, 0.5, 0.5]					)
            if is_vision_available()
            else None
        )



 @slow
 def 							UpperCamelCase     (				self					):
        A__		   =		VideoMAEForVideoClassification.from_pretrained('''MCG-NJU/videomae-base-finetuned-kinetics'''					).to(
            __lowerCamelCase					)

        A__		   =		self.default_image_processor
        A__		   =		prepare_video()
        A__		   =		image_processor(__lowerCamelCase,return_tensors='''pt'''					).to(__lowerCamelCase					)

        # forward pass
        with torch.no_grad():
               A__		   =		model(**__lowerCamelCase					)

        # verify the logits
        A__		   =		torch.Size((1, 400)					)
        self.assertEqual(outputs.logits.shape,__lowerCamelCase					)

        A__		   =		torch.tensor([0.3669, -0.0688, -0.2421]					).to(__lowerCamelCase					)

        self.assertTrue(torch.allclose(outputs.logits[0, :3],__lowerCamelCase,atol=1E-4					)					)




 @slow
 def 							UpperCamelCase     (				self					):
        A__		   =		VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short'''					).to(__lowerCamelCase					)

        A__		   =		self.default_image_processor
        A__		   =		prepare_video()
        A__		   =		image_processor(__lowerCamelCase,return_tensors='''pt'''					).to(__lowerCamelCase					)

        # add boolean mask, indicating which patches to mask
        A__		   =		hf_hub_download(repo_id='''hf-internal-testing/bool-masked-pos''',filename='''bool_masked_pos.pt'''					)
        A__		   =		torch.load(__lowerCamelCase					)

        # forward pass
        with torch.no_grad():
               A__		   =		model(**__lowerCamelCase					)

        # verify the logits
        A__		   =		torch.Size([1, 1408, 1536]					)
        A__		   =		torch.tensor(
            [[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]],device=__lowerCamelCase					)
        self.assertEqual(outputs.logits.shape,__lowerCamelCase					)
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3],__lowerCamelCase,atol=1E-4					)					)

        # verify the loss (`config.norm_pix_loss` = `True`)
        A__		   =		torch.tensor([0.5142],device=__lowerCamelCase					)
        self.assertTrue(torch.allclose(outputs.loss,__lowerCamelCase,atol=1E-4					)					)

        # verify the loss (`config.norm_pix_loss` = `False`)
        A__		   =		VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short''',norm_pix_loss=__lowerCamelCase					).to(
            __lowerCamelCase					)

        with torch.no_grad():
               A__		   =		model(**__lowerCamelCase					)

        A__		   =		torch.tensor(torch.tensor([0.6469]					),device=__lowerCamelCase					)
        self.assertTrue(torch.allclose(outputs.loss,__lowerCamelCase,atol=1E-4					)					)












import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
       from PIL import Image

       from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
       import torch

if is_tf_available():
       import tensorflow as tf




@require_vision
@require_torchvision
class        SCREAMING_SNAKE_CASE__					(		unittest.TestCase ):



 def 							UpperCamelCase     (				self					):
        A__		   =		tempfile.mkdtemp()
        A__		   =		SamImageProcessor()
        A__		   =		SamProcessor(__lowerCamelCase					)
        processor.save_pretrained(self.tmpdirname					)



 def 							UpperCamelCase     (				self,**__lowerCamelCase					):
        return AutoProcessor.from_pretrained(self.tmpdirname,**__lowerCamelCase					).image_processor



 def 							UpperCamelCase     (				self					):
        shutil.rmtree(self.tmpdirname					)



 def 							UpperCamelCase     (				self					):
        A__		   =		[np.random.randint(255,size=(3, 30, 400),dtype=np.uinta					)]

        A__		   =		[Image.fromarray(np.moveaxis(__lowerCamelCase,0,-1					)					) for x in image_inputs]

        return image_inputs



 def 							UpperCamelCase     (				self					):
        A__		   =		SamProcessor(image_processor=self.get_image_processor()					)
        processor.save_pretrained(self.tmpdirname					)

        A__		   =		self.get_image_processor(do_normalize=__lowerCamelCase,padding_value=1.0					)

        A__		   =		SamProcessor.from_pretrained(self.tmpdirname,do_normalize=__lowerCamelCase,padding_value=1.0					)

        self.assertEqual(processor.image_processor.to_json_string(),image_processor_add_kwargs.to_json_string()					)
        self.assertIsInstance(processor.image_processor,__lowerCamelCase					)



 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)

        A__		   =		self.prepare_image_inputs()

        A__		   =		image_processor(__lowerCamelCase,return_tensors='''np'''					)
        A__		   =		processor(images=__lowerCamelCase,return_tensors='''np'''					)

        input_feat_extract.pop('''original_sizes'''					)  # pop original_sizes as it is popped in the processor
        input_feat_extract.pop('''reshaped_input_sizes'''					)  # pop original_sizes as it is popped in the processor

        for key in input_feat_extract.keys():
               self.assertAlmostEqual(input_feat_extract[key].sum(),input_processor[key].sum(),delta=1E-2					)




 @require_torch
 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)
        A__		   =		[torch.ones((1, 3, 5, 5)					)]

        A__		   =		[[1764, 2646]]

        A__		   =		[[683, 1024]]
        A__		   =		processor.post_process_masks(__lowerCamelCase,__lowerCamelCase,__lowerCamelCase					)
        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        A__		   =		processor.post_process_masks(
            __lowerCamelCase,torch.tensor(__lowerCamelCase					),torch.tensor(__lowerCamelCase					)					)
        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        # should also work with np
        A__		   =		[np.ones((1, 3, 5, 5)					)]
        A__		   =		processor.post_process_masks(__lowerCamelCase,np.array(__lowerCamelCase					),np.array(__lowerCamelCase					)					)

        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        A__		   =		[[1, 0], [0, 1]]
        with self.assertRaises(__lowerCamelCase					):
               A__		   =		processor.post_process_masks(__lowerCamelCase,np.array(__lowerCamelCase					),np.array(__lowerCamelCase					)					)




@require_vision
@require_tf
class        SCREAMING_SNAKE_CASE__					(		unittest.TestCase ):



 def 							UpperCamelCase     (				self					):
        A__		   =		tempfile.mkdtemp()
        A__		   =		SamImageProcessor()
        A__		   =		SamProcessor(__lowerCamelCase					)
        processor.save_pretrained(self.tmpdirname					)



 def 							UpperCamelCase     (				self,**__lowerCamelCase					):
        return AutoProcessor.from_pretrained(self.tmpdirname,**__lowerCamelCase					).image_processor



 def 							UpperCamelCase     (				self					):
        shutil.rmtree(self.tmpdirname					)



 def 							UpperCamelCase     (				self					):
        A__		   =		[np.random.randint(255,size=(3, 30, 400),dtype=np.uinta					)]

        A__		   =		[Image.fromarray(np.moveaxis(__lowerCamelCase,0,-1					)					) for x in image_inputs]

        return image_inputs



 def 							UpperCamelCase     (				self					):
        A__		   =		SamProcessor(image_processor=self.get_image_processor()					)
        processor.save_pretrained(self.tmpdirname					)

        A__		   =		self.get_image_processor(do_normalize=__lowerCamelCase,padding_value=1.0					)

        A__		   =		SamProcessor.from_pretrained(self.tmpdirname,do_normalize=__lowerCamelCase,padding_value=1.0					)

        self.assertEqual(processor.image_processor.to_json_string(),image_processor_add_kwargs.to_json_string()					)
        self.assertIsInstance(processor.image_processor,__lowerCamelCase					)



 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)

        A__		   =		self.prepare_image_inputs()

        A__		   =		image_processor(__lowerCamelCase,return_tensors='''np'''					)
        A__		   =		processor(images=__lowerCamelCase,return_tensors='''np'''					)

        input_feat_extract.pop('''original_sizes'''					)  # pop original_sizes as it is popped in the processor
        input_feat_extract.pop('''reshaped_input_sizes'''					)  # pop reshaped_input_sizes as it is popped in the processor

        for key in input_feat_extract.keys():
               self.assertAlmostEqual(input_feat_extract[key].sum(),input_processor[key].sum(),delta=1E-2					)




 @require_tf
 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)
        A__		   =		[tf.ones((1, 3, 5, 5)					)]

        A__		   =		[[1764, 2646]]

        A__		   =		[[683, 1024]]
        A__		   =		processor.post_process_masks(__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,return_tensors='''tf'''					)
        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        A__		   =		processor.post_process_masks(
            __lowerCamelCase,tf.convert_to_tensor(__lowerCamelCase					),tf.convert_to_tensor(__lowerCamelCase					),return_tensors='''tf''',)
        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        # should also work with np
        A__		   =		[np.ones((1, 3, 5, 5)					)]
        A__		   =		processor.post_process_masks(
            __lowerCamelCase,np.array(__lowerCamelCase					),np.array(__lowerCamelCase					),return_tensors='''tf'''					)

        self.assertEqual(masks[0].shape,(1, 3, 1764, 2646)					)

        A__		   =		[[1, 0], [0, 1]]
        with self.assertRaises(tf.errors.InvalidArgumentError					):
               A__		   =		processor.post_process_masks(
                   __lowerCamelCase,np.array(__lowerCamelCase					),np.array(__lowerCamelCase					),return_tensors='''tf'''					)




@require_vision
@require_torchvision
class        SCREAMING_SNAKE_CASE__					(		unittest.TestCase ):



 def 							UpperCamelCase     (				self					):
        A__		   =		tempfile.mkdtemp()
        A__		   =		SamImageProcessor()
        A__		   =		SamProcessor(__lowerCamelCase					)
        processor.save_pretrained(self.tmpdirname					)



 def 							UpperCamelCase     (				self,**__lowerCamelCase					):
        return AutoProcessor.from_pretrained(self.tmpdirname,**__lowerCamelCase					).image_processor



 def 							UpperCamelCase     (				self					):
        shutil.rmtree(self.tmpdirname					)



 def 							UpperCamelCase     (				self					):
        A__		   =		[np.random.randint(255,size=(3, 30, 400),dtype=np.uinta					)]

        A__		   =		[Image.fromarray(np.moveaxis(__lowerCamelCase,0,-1					)					) for x in image_inputs]

        return image_inputs



 @is_pt_tf_cross_test
 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)
        A__		   =		np.random.randint(0,2,size=(1, 3, 5, 5)					).astype(np.floataa					)
        A__		   =		[tf.convert_to_tensor(__lowerCamelCase					)]
        A__		   =		[torch.tensor(__lowerCamelCase					)]

        A__		   =		[[1764, 2646]]

        A__		   =		[[683, 1024]]
        A__		   =		processor.post_process_masks(
            __lowerCamelCase,__lowerCamelCase,__lowerCamelCase,return_tensors='''tf'''					)
        A__		   =		processor.post_process_masks(
            __lowerCamelCase,__lowerCamelCase,__lowerCamelCase,return_tensors='''pt'''					)

        self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()					)					)




 @is_pt_tf_cross_test
 def 							UpperCamelCase     (				self					):
        A__		   =		self.get_image_processor()

        A__		   =		SamProcessor(image_processor=__lowerCamelCase					)

        A__		   =		self.prepare_image_inputs()

        A__		   =		image_processor(__lowerCamelCase,return_tensors='''pt'''					)['''pixel_values'''].numpy()
        A__		   =		processor(images=__lowerCamelCase,return_tensors='''pt'''					)['''pixel_values'''].numpy()

        A__		   =		image_processor(__lowerCamelCase,return_tensors='''tf'''					)['''pixel_values'''].numpy()
        A__		   =		processor(images=__lowerCamelCase,return_tensors='''tf'''					)['''pixel_values'''].numpy()

        self.assertTrue(np.allclose(__lowerCamelCase,__lowerCamelCase					)					)
        self.assertTrue(np.allclose(__lowerCamelCase,__lowerCamelCase					)					)
        self.assertTrue(np.allclose(__lowerCamelCase,__lowerCamelCase					)					)





