




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        snake_case__				:
				"""simple docstring"""



				def __init__( self							:	Union[str, Any]   , __lowerCamelCase							:	Optional[int]   , __lowerCamelCase							:	List[str]=2   , __lowerCamelCase							:	Optional[Any]=True   , __lowerCamelCase							:	Union[str, Any]=True   , __lowerCamelCase							:	List[Any]=10   , __lowerCamelCase							:	Optional[Any]=10   , __lowerCamelCase							:	Any=8   , __lowerCamelCase							:	Optional[int]=[2, 4, 4]   , __lowerCamelCase							:	List[str]=3   , __lowerCamelCase							:	Tuple=7_68   , __lowerCamelCase							:	Optional[int]=5   , __lowerCamelCase							:	Optional[Any]=4   , __lowerCamelCase							:	Union[str, Any]=37   , __lowerCamelCase							:	List[Any]="gelu_fast"   , __lowerCamelCase							:	int=0.0   , __lowerCamelCase							:	Any=0.0   , __lowerCamelCase							:	int=0.02   , __lowerCamelCase							:	Optional[Any]=1e-06   , __lowerCamelCase							:	str=True   , __lowerCamelCase							:	Optional[Any]=None   , )   ->	Dict:
							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 				__UpperCAmelCase				( self							:	List[Any]				)   ->	Tuple:
							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 				__UpperCAmelCase				( self							:	List[str]				)   ->	int:
							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 				__UpperCAmelCase				( self							:	Optional[int]   , __lowerCamelCase							:	Optional[int]   , __lowerCamelCase							:	Any   , __lowerCamelCase							:	str				)   ->	int:
							a       =     VivitModel(config=UpperCamelCase_				)
							model.to(UpperCamelCase_				)
							model.eval()
							a       =     model(UpperCamelCase_				)
							self.parent.assertEqual(result.last_hidden_state.shape   , (self.batch_size, self.seq_length, self.hidden_size)				)





				def 				__UpperCAmelCase				( self							:	Any   , __lowerCamelCase							:	List[str]   , __lowerCamelCase							:	List[str]   , __lowerCamelCase							:	Any				)   ->	Optional[int]:
							a       =     VivitForVideoClassification(UpperCamelCase_				)
							model.to(UpperCamelCase_				)
							model.eval()

							a       =     model(UpperCamelCase_				)

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





				def 				__UpperCAmelCase				( self							:	Union[str, Any]				)   ->	Union[str, Any]:
							a       =     self.prepare_config_and_inputs()
							a       =     config_and_inputs
							a       =     {'pixel_values': pixel_values}
							return config, inputs_dict




@require_torch
class        snake_case__				(_UpperCamelCase       ,			unittest.TestCase  ):
				"""simple docstring"""



				SCREAMING_SNAKE_CASE_			:				Tuple									=   (VivitModel, VivitForVideoClassification) if is_torch_available() else ()

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





				def 				__UpperCAmelCase				( self							:	Dict				)   ->	Optional[int]:
							a       =     VivitModelTester(self				)
							a       =     ConfigTester(self   , config_class=UpperCamelCase_   , has_text_modality=UpperCamelCase_   , hidden_size=37				)





				def 				__UpperCAmelCase				( self							:	Union[str, Any]   , __lowerCamelCase							:	Optional[int]   , __lowerCamelCase							:	List[Any]   , __lowerCamelCase							:	List[Any]=False				)   ->	str:
							a       =     copy.deepcopy(UpperCamelCase_				)

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

							return inputs_dict





				def 				__UpperCAmelCase				( self							:	int				)   ->	List[Any]:
							self.config_tester.run_common_tests()





				@unittest.skip(reason="Vivit does not use inputs_embeds"				)
				def 				__UpperCAmelCase				( self							:	Dict				)   ->	Dict:
							pass





				def 				__UpperCAmelCase				( self							:	Any				)   ->	Union[str, Any]:
							a       =     self.model_tester.prepare_config_and_inputs_for_common()

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





				def 				__UpperCAmelCase				( self							:	int				)   ->	Any:
							a       =     self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										a       =     model_class(UpperCamelCase_				)
										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]   , UpperCamelCase_				)





				def 				__UpperCAmelCase				( self							:	Optional[Any]				)   ->	Any:
							a       =     self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCamelCase_				)





				def 				__UpperCAmelCase				( self							:	Tuple				)   ->	Union[str, Any]:
							a       =     self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_video_classification(*UpperCamelCase_				)





				@slow
				def 				__UpperCAmelCase				( self							:	Union[str, Any]				)   ->	Any:
							for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										a       =     VivitModel.from_pretrained(UpperCamelCase_				)
										self.assertIsNotNone(UpperCamelCase_				)





				def 				__UpperCAmelCase				( self							:	List[Any]				)   ->	str:
							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(UpperCamelCase_				)
										model.to(UpperCamelCase_				)
										model.eval()
										with torch.no_grad():
													a       =     model(**self._prepare_for_class(UpperCamelCase_   , UpperCamelCase_				)				)
										a       =     outputs.attentions
										self.assertEqual(len(UpperCamelCase_				)   , self.model_tester.num_hidden_layers				)

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

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

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

										a       =     outputs.attentions

										self.assertEqual(len(UpperCamelCase_				)   , 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							:	List[str]				)   ->	Optional[int]:
							def check_hidden_states_output(__lowerCamelCase							:	str   , __lowerCamelCase							:	List[str]   , __lowerCamelCase							:	Optional[int]				):
										a       =     model_class(UpperCamelCase_				)
										model.to(UpperCamelCase_				)
										model.eval()

										with torch.no_grad():
													a       =     model(**self._prepare_for_class(UpperCamelCase_   , UpperCamelCase_				)				)

										a       =     outputs.hidden_states
										a       =     self.model_tester.num_hidden_layers + 1
										self.assertEqual(len(UpperCamelCase_				)   , UpperCamelCase_				)

										a       =     self.model_tester.seq_length

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

							a       =     self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
										a       =     True
										check_hidden_states_output(UpperCamelCase_   , UpperCamelCase_   , UpperCamelCase_				)

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

										check_hidden_states_output(UpperCamelCase_   , UpperCamelCase_   , UpperCamelCase_				)





				@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."				)
				def 				__UpperCAmelCase				( self							:	Union[str, Any]				)   ->	List[Any]:
							pass




def      __magic_name__							(					):






			'''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(A  )
			return list(A  )






@require_torch
@require_vision
class        snake_case__				(unittest.TestCase  ):
				"""simple docstring"""



				@cached_property
				def 				__UpperCAmelCase				( self							:	Dict				)   ->	int:
							return VivitImageProcessor() if is_vision_available() else None





				@slow
				def 				__UpperCAmelCase				( self							:	Any				)   ->	str:
							a       =     VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics400"				).to(UpperCamelCase_				)

							a       =     self.default_image_processor
							a       =     prepare_video()
							a       =     image_processor(UpperCamelCase_   , return_tensors="pt"				).to(UpperCamelCase_				)

							# forward pass
							with torch.no_grad():
										a       =     model(**UpperCamelCase_				)

							# verify the logits
							a       =     torch.Size((1, 4_00)				)
							self.assertEqual(outputs.logits.shape   , UpperCamelCase_				)

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

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












import random
import sys

UpperCAmelCase__    :							str       		=     'ABCDEFGHIJKLMNOPQRSTUVWXYZ'


def 		_lowerCamelCase					(       )      ->		None:





  """simple docstring"""





  _lowercase:			Any      =     input('Enter message: '				)
  _lowercase:			List[str]      =     'LFWOAYUISVKMNXPBDCRJTQEGHZ'
  _lowercase:			Tuple      =     input('Encrypt/Decrypt [e/d]: '				)

  check_valid_key(UpperCamelCase				)

  if resp.lower().startswith('e'				):
    _lowercase:			int      =     'encrypt'
    _lowercase:			Optional[int]      =     encrypt_message(UpperCamelCase       ,  UpperCamelCase				)
  elif resp.lower().startswith('d'				):
    _lowercase:			str      =     'decrypt'
    _lowercase:			Dict      =     decrypt_message(UpperCamelCase       ,  UpperCamelCase				)

  print(F'\n{mode.title()}ion: \n{translated}'				)


def 		_lowerCamelCase					(       UpperCamelCase				)      ->		None:





  """simple docstring"""





  _lowercase:			List[Any]      =     list(UpperCamelCase				)
  _lowercase:			Union[str, Any]      =     list(UpperCamelCase				)
  key_list.sort()
  letters_list.sort()

  if key_list != letters_list:
    sys.exit('Error in the key or symbol set.'				)


def 		_lowerCamelCase					(       UpperCamelCase       ,  UpperCamelCase				)      ->		str:





  """simple docstring"""





  return translate_message(UpperCamelCase       ,  UpperCamelCase       ,  'encrypt'				)


def 		_lowerCamelCase					(       UpperCamelCase       ,  UpperCamelCase				)      ->		str:





  """simple docstring"""





  return translate_message(UpperCamelCase       ,  UpperCamelCase       ,  'decrypt'				)


def 		_lowerCamelCase					(       UpperCamelCase       ,  UpperCamelCase       ,  UpperCamelCase				)      ->		str:





  """simple docstring"""





  _lowercase:			Optional[int]      =     ''
  _lowercase:			Any      =     LETTERS
  _lowercase:			Tuple      =     key

  if mode == "decrypt":
    _lowercase  ,       _lowercase:			Tuple      =     chars_b, chars_a

  for symbol in message:
    if symbol.upper() in chars_a:
      _lowercase:			int      =     chars_a.find(symbol.upper()				)
      if symbol.isupper():
        translated += chars_b[sym_index].upper()
      else:
        translated += chars_b[sym_index].lower()
    else:
      translated += symbol

  return translated


def 		_lowerCamelCase					(       )      ->		str:





  """simple docstring"""





  _lowercase:			Union[str, Any]      =     list(UpperCamelCase				)
  random.shuffle(UpperCamelCase				)
  return "".join(UpperCamelCase				)


if __name__ == "__main__":
   main()
