
'''simple docstring'''





import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import VivitConfig
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


if is_torch_available():
 import torch
 from torch import nn

 from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VivitForVideoClassification, VivitModel
 from transformers.models.vivit.modeling_vivit import VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from transformers import VivitImageProcessor


class 	UpperCamelCase__					:






 def __init__(     self					:Union[str, Any]		,			_A					:Dict		,			_A					:Optional[Any]=2		,			_A					:Optional[Any]=True		,			_A					:Optional[Any]=True		,			_A					:Optional[Any]=10		,			_A					:Tuple=10		,			_A					:List[str]=8		,			_A					:int=[2, 4, 4]		,			_A					:int=3		,			_A					:Union[str, Any]=768		,			_A					:Optional[Any]=5		,			_A					:Any=4		,			_A					:Optional[Any]=37		,			_A					:int="gelu_fast"		,			_A					:str=0.0		,			_A					:Union[str, Any]=0.0		,			_A					:Optional[int]=0.02		,			_A					:Optional[Any]=1E-06		,			_A					:Tuple=True		,			_A					:int=None		,			)			->     List[str]:







       '''simple docstring'''



       __A    		=     parent
       __A    		=     batch_size
       __A    		=     is_training
       __A    		=     use_labels
       __A    		=     num_labels
       __A    		=     image_size
       __A    		=     num_frames
       __A    		=     tubelet_size
       __A    		=     num_channels
       __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    		=     initializer_range
       __A    		=     layer_norm_eps
       __A    		=     qkv_bias
       __A    		=     scope

       __A    		=     (
           (self.image_size // self.tubelet_size[2])
           * (self.image_size // self.tubelet_size[1])
           * (self.num_frames // self.tubelet_size[0])
       ) + 1  # CLS token






 def 		lowercase_  (     self					:List[str]     )			->     Any:







       '''simple docstring'''



       __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.num_labels     )

       __A    		=     self.get_config()

       return config, pixel_values, labels






 def 		lowercase_  (     self					:List[str]     )			->     Optional[int]:







       '''simple docstring'''



       __A    		=     VivitConfig(
           num_frames=self.num_frames		,			image_size=self.image_size		,			tubelet_size=self.tubelet_size		,			num_channels=self.num_channels		,			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		,			initializer_range=self.initializer_range		,			layer_norm_eps=self.layer_norm_eps		,			qkv_bias=self.qkv_bias		,			)
       __A    		=     self.num_labels
       return config






 def 		lowercase_  (     self					:List[Any]		,			_A					:Any		,			_A					:List[Any]		,			_A					:Any     )			->     Any:







       '''simple docstring'''



       __A    		=     VivitModel(config=_A     )
       model.to(_A     )
       model.eval()
       __A    		=     model(_A     )
       self.parent.assertEqual(result.last_hidden_state.shape		,			(self.batch_size, self.seq_length, self.hidden_size)     )






 def 		lowercase_  (     self					:Dict		,			_A					:List[str]		,			_A					:List[Any]		,			_A					:str     )			->     Optional[Any]:







       '''simple docstring'''



       __A    		=     VivitForVideoClassification(_A     )
       model.to(_A     )
       model.eval()

       __A    		=     model(_A     )

       # verify the logits shape
       __A    		=     torch.Size((self.batch_size, self.num_labels)     )
       self.parent.assertEqual(result.logits.shape		,			_A     )






 def 		lowercase_  (     self					:List[Any]     )			->     Dict:







       '''simple docstring'''



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


@require_torch
class 	UpperCamelCase__					(      SCREAMING_SNAKE_CASE ,       unittest.TestCase):
 UpperCAmelCase__      :      Optional[int]  			=   (VivitModel, VivitForVideoClassification) if is_torch_available() else ()

 UpperCAmelCase__      :      List[str]  			=   False
 UpperCAmelCase__      :      Optional[Any]  			=   False
 UpperCAmelCase__      :      Optional[Any]  			=   False
 UpperCAmelCase__      :      Optional[int]  			=   False






 def 		lowercase_  (     self					:Optional[int]     )			->     Optional[int]:







       '''simple docstring'''



       __A    		=     VivitModelTester(self     )
       __A    		=     ConfigTester(self		,			config_class=_A		,			has_text_modality=_A		,			hidden_size=37     )






 def 		lowercase_  (     self					:Union[str, Any]		,			_A					:Optional[Any]		,			_A					:Dict		,			_A					:Dict=False     )			->     int:







       '''simple docstring'''



       __A    		=     copy.deepcopy(_A     )

       if return_labels:
             if model_class in get_values(_A     ):
                   __A    		=     torch.zeros(
                       self.model_tester.batch_size		,			dtype=torch.long		,			device=_A     )

       return inputs_dict






 def 		lowercase_  (     self					:List[str]     )			->     Optional[Any]:







       '''simple docstring'''



       self.config_tester.run_common_tests()






 @unittest.skip(reason='Vivit does not use inputs_embeds'     )
 def 		lowercase_  (     self					:Optional[Any]     )			->     int:







       '''simple docstring'''



       pass






 def 		lowercase_  (     self					:Union[str, Any]     )			->     Any:







       '''simple docstring'''



       __A		, __A    		=     self.model_tester.prepare_config_and_inputs_for_common()

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






 def 		lowercase_  (     self					:str     )			->     Tuple:







       '''simple docstring'''



       __A		, __A    		=     self.model_tester.prepare_config_and_inputs_for_common()

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

             __A    		=     ['pixel_values', 'head_mask']
             self.assertListEqual(arg_names[:2]		,			_A     )






 def 		lowercase_  (     self					:int     )			->     Optional[int]:







       '''simple docstring'''



       __A    		=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_A     )






 def 		lowercase_  (     self					:List[str]     )			->     Tuple:







       '''simple docstring'''



       __A    		=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_video_classification(*_A     )






 @slow
 def 		lowercase_  (     self					:str     )			->     Any:







       '''simple docstring'''



       for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __A    		=     VivitModel.from_pretrained(_A     )
             self.assertIsNotNone(_A     )






 def 		lowercase_  (     self					:Dict     )			->     List[str]:







       '''simple docstring'''



       __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

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

             # check that output_attentions also work using config
             del inputs_dict["output_attentions"]
             __A    		=     True
             __A    		=     model_class(_A     )
             model.to(_A     )
             model.eval()
             with torch.no_grad():
                   __A    		=     model(**self._prepare_for_class(_A		,			_A     )     )
             __A    		=     outputs.attentions
             self.assertEqual(len(_A     )		,			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(_A     )

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

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

             __A    		=     outputs.attentions

             self.assertEqual(len(_A     )		,			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 		lowercase_  (     self					:List[Any]     )			->     Union[str, Any]:







       '''simple docstring'''



       def check_hidden_states_output(_A					:Union[str, Any]		,			_A					:int		,			_A					:str     ):
             __A    		=     model_class(_A     )
             model.to(_A     )
             model.eval()

             with torch.no_grad():
                   __A    		=     model(**self._prepare_for_class(_A		,			_A     )     )

             __A    		=     outputs.hidden_states
             __A    		=     self.model_tester.num_hidden_layers + 1
             self.assertEqual(len(_A     )		,			_A     )

             __A    		=     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(_A		,			_A		,			_A     )

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

             check_hidden_states_output(_A		,			_A		,			_A     )






 @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'     )
 def 		lowercase_  (     self					:Optional[int]     )			->     Dict:







       '''simple docstring'''



       pass





def     snake_case							(						)->     int:







      """simple docstring"""
      __A    		=     hf_hub_download(
          repo_id='hf-internal-testing/spaghetti-video' ,					filename='eating_spaghetti_32_frames.npy' ,					repo_type='dataset'		)
      __A    		=     np.load(UpperCAmelCase		)
      return list(UpperCAmelCase		)


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






 @cached_property
 def 		lowercase_  (     self					:Optional[int]     )			->     str:







       '''simple docstring'''



       return VivitImageProcessor() if is_vision_available() else None






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







       '''simple docstring'''



       __A    		=     VivitForVideoClassification.from_pretrained('google/vivit-b-16x2-kinetics400'     ).to(_A     )

       __A    		=     self.default_image_processor
       __A    		=     prepare_video()
       __A    		=     image_processor(_A		,			return_tensors='pt'     ).to(_A     )

       # forward pass
       with torch.no_grad():
             __A    		=     model(**_A     )

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

       # taken from original model
       __A    		=     torch.tensor([-1.0_543, 2.0_764, -0.2_104, 0.4_439, -0.9_658]     ).to(_A     )

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








'''simple docstring'''





import math
import os

import cva
import numpy as np

a__						:				List[Any]           =    255.0





def     snake_case							(						UpperCAmelCase ,					UpperCAmelCase		)->     float:







      """simple docstring"""
      __A    		=     np.mean((original - contrast) ** 2		)
      if mse == 0:
            return 1_0_0

      return 2_0 * math.logaa(PIXEL_MAX / math.sqrt(UpperCAmelCase		)		)





def     snake_case							(						)->     None:







      """simple docstring"""
      __A    		=     os.path.dirname(os.path.realpath(UpperCAmelCase		)		)
      # Loading images (original image and compressed image)
      __A    		=     cva.imread(os.path.join(UpperCAmelCase ,					'image_data/original_image.png'		)		)
      __A    		=     cva.imread(os.path.join(UpperCAmelCase ,					'image_data/compressed_image.png'		) ,					1		)

      __A    		=     cva.imread(os.path.join(UpperCAmelCase ,					'image_data/PSNR-example-base.png'		)		)
      __A    		=     cva.imread(
          os.path.join(UpperCAmelCase ,					'image_data/PSNR-example-comp-10.jpg'		) ,					1		)

      # Value expected: 29.73dB
      print('-- First Test --'		)
      print(f'PSNR value is {peak_signal_to_noise_ratio(UpperCAmelCase ,					UpperCAmelCase		)} dB'		)

      # # Value expected: 31.53dB (Wikipedia Example)
      print('\n-- Second Test --'		)
      print(f'PSNR value is {peak_signal_to_noise_ratio(UpperCAmelCase ,					UpperCAmelCase		)} dB'		)


if __name__ == "__main__":
 main()






