

'''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     lowercase_		:

		'''simple docstring'''





		def __init__(       self				,	a_				,	a_=2				,	a_=True				,	a_=True				,	a_=1_0				,	a_=1_0				,	a_=8				,	a_=[2, 4, 4]				,	a_=3				,	a_=7_6_8				,	a_=5				,	a_=4				,	a_=3_7				,	a_="gelu_fast"				,	a_=0.0				,	a_=0.0				,	a_=0.02				,	a_=1E-06				,	a_=True				,	a_=None				,	)							->			int:


				"""simple docstring"""
				UpperCAmelCase  							=		parent
				UpperCAmelCase  							=		batch_size
				UpperCAmelCase  							=		is_training
				UpperCAmelCase  							=		use_labels
				UpperCAmelCase  							=		num_labels
				UpperCAmelCase  							=		image_size
				UpperCAmelCase  							=		num_frames
				UpperCAmelCase  							=		tubelet_size
				UpperCAmelCase  							=		num_channels
				UpperCAmelCase  							=		hidden_size
				UpperCAmelCase  							=		num_hidden_layers
				UpperCAmelCase  							=		num_attention_heads
				UpperCAmelCase  							=		intermediate_size
				UpperCAmelCase  							=		hidden_act
				UpperCAmelCase  							=		hidden_dropout_prob
				UpperCAmelCase  							=		attention_probs_dropout_prob
				UpperCAmelCase  							=		initializer_range
				UpperCAmelCase  							=		layer_norm_eps
				UpperCAmelCase  							=		qkv_bias
				UpperCAmelCase  							=		scope

				UpperCAmelCase  							=		(
				    (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   snake_case_     (       self       )							->			Any:


				"""simple docstring"""
				UpperCAmelCase  							=		floats_tensor(
				    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]       )

				UpperCAmelCase  							=		None
				if self.use_labels:
						UpperCAmelCase  							=		ids_tensor([self.batch_size]				,	self.num_labels       )

				UpperCAmelCase  							=		self.get_config()

				return config, pixel_values, labels
		def   snake_case_     (       self       )							->			Optional[int]:


				"""simple docstring"""
				UpperCAmelCase  							=		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				,	)
				UpperCAmelCase  							=		self.num_labels
				return config
		def   snake_case_     (       self				,	a_				,	a_				,	a_       )							->			List[str]:


				"""simple docstring"""
				UpperCAmelCase  							=		VivitModel(config=a_       )
				model.to(a_       )
				model.eval()
				UpperCAmelCase  							=		model(a_       )
				self.parent.assertEqual(result.last_hidden_state.shape				,	(self.batch_size, self.seq_length, self.hidden_size)       )
		def   snake_case_     (       self				,	a_				,	a_				,	a_       )							->			Any:


				"""simple docstring"""
				UpperCAmelCase  							=		VivitForVideoClassification(a_       )
				model.to(a_       )
				model.eval()

				UpperCAmelCase  							=		model(a_       )

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





		def   snake_case_     (       self       )							->			Optional[Any]:


				"""simple docstring"""
				UpperCAmelCase  							=		self.prepare_config_and_inputs()
				UpperCAmelCase  							=		config_and_inputs
				UpperCAmelCase  							=		{"pixel_values": pixel_values}
				return config, inputs_dict




@require_torch
class     lowercase_		(						lowerCamelCase_	,    unittest.TestCase	):

		'''simple docstring'''





		__lowerCAmelCase   :	List[str]      					=				(VivitModel, VivitForVideoClassification) if is_torch_available() else ()

		__lowerCAmelCase   :	Any      					=				False
		__lowerCAmelCase   :	Any      					=				False
		__lowerCAmelCase   :	Optional[int]      					=				False
		__lowerCAmelCase   :	Optional[int]      					=				False
		def   snake_case_     (       self       )							->			Optional[int]:


				"""simple docstring"""
				UpperCAmelCase  							=		VivitModelTester(self       )
				UpperCAmelCase  							=		ConfigTester(self				,	config_class=a_				,	has_text_modality=a_				,	hidden_size=3_7       )
		def   snake_case_     (       self				,	a_				,	a_				,	a_=False       )							->			Dict:


				"""simple docstring"""
				UpperCAmelCase  							=		copy.deepcopy(a_       )

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

				return inputs_dict
		def   snake_case_     (       self       )							->			List[str]:


				"""simple docstring"""
				self.config_tester.run_common_tests()
		@unittest.skip(reason='Vivit does not use inputs_embeds'       )
		def   snake_case_     (       self       )							->			str:


				"""simple docstring"""
				pass
		def   snake_case_     (       self       )							->			List[str]:


				"""simple docstring"""
				UpperCAmelCase  							=		self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						UpperCAmelCase  							=		model_class(a_       )
						self.assertIsInstance(model.get_input_embeddings()				,	(nn.Module)       )
						UpperCAmelCase  							=		model.get_output_embeddings()
						self.assertTrue(x is None or isinstance(a_				,	nn.Linear       )       )
		def   snake_case_     (       self       )							->			List[Any]:


				"""simple docstring"""
				UpperCAmelCase  							=		self.model_tester.prepare_config_and_inputs_for_common()

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

						UpperCAmelCase  							=		["pixel_values", "head_mask"]
						self.assertListEqual(arg_names[:2]				,	a_       )
		def   snake_case_     (       self       )							->			str:


				"""simple docstring"""
				UpperCAmelCase  							=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*a_       )
		def   snake_case_     (       self       )							->			Any:


				"""simple docstring"""
				UpperCAmelCase  							=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_video_classification(*a_       )
		@slow
		def   snake_case_     (       self       )							->			str:


				"""simple docstring"""







				for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						UpperCAmelCase  							=		VivitModel.from_pretrained(a_       )
						self.assertIsNotNone(a_       )
		def   snake_case_     (       self       )							->			Optional[Any]:


				"""simple docstring"""
				UpperCAmelCase  							=		self.model_tester.prepare_config_and_inputs_for_common()
				UpperCAmelCase  							=		True

				for model_class in self.all_model_classes:
						UpperCAmelCase  							=		self.model_tester.seq_length

						UpperCAmelCase  							=		True
						UpperCAmelCase  							=		False
						UpperCAmelCase  							=		True
						UpperCAmelCase  							=		model_class(a_       )
						model.to(a_       )
						model.eval()
						with torch.no_grad():
								UpperCAmelCase  							=		model(**self._prepare_for_class(a_				,	a_       )       )
						UpperCAmelCase  							=		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"]
						UpperCAmelCase  							=		True
						UpperCAmelCase  							=		model_class(a_       )
						model.to(a_       )
						model.eval()
						with torch.no_grad():
								UpperCAmelCase  							=		model(**self._prepare_for_class(a_				,	a_       )       )
						UpperCAmelCase  							=		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]				,	)
						UpperCAmelCase  							=		len(a_       )

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

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

						UpperCAmelCase  							=		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   snake_case_     (       self       )							->			Union[str, Any]:


				"""simple docstring"""







				def check_hidden_states_output(a_				,	a_				,	a_       ):
						UpperCAmelCase  							=		model_class(a_       )
						model.to(a_       )
						model.eval()

						with torch.no_grad():
								UpperCAmelCase  							=		model(**self._prepare_for_class(a_				,	a_       )       )

						UpperCAmelCase  							=		outputs.hidden_states
						UpperCAmelCase  							=		self.model_tester.num_hidden_layers + 1
						self.assertEqual(len(a_       )				,	a_       )

						UpperCAmelCase  							=		self.model_tester.seq_length

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

				UpperCAmelCase  							=		self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						UpperCAmelCase  							=		True
						check_hidden_states_output(a_				,	a_				,	a_       )

						# check that output_hidden_states also work using config
						del inputs_dict["output_hidden_states"]
						UpperCAmelCase  							=		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   snake_case_     (       self       )							->			List[str]:


				"""simple docstring"""
				pass




def  lowerCamelCase__						(  ):
		UpperCAmelCase  							=		hf_hub_download(
		    repo_id='hf-internal-testing/spaghetti-video'    ,				filename='eating_spaghetti_32_frames.npy'    ,				repo_type='dataset'  )
		UpperCAmelCase  							=		np.load(lowercase__  )
		return list(lowercase__  )



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

		'''simple docstring'''





		@cached_property
		def   snake_case_     (       self       )							->			List[str]:


				"""simple docstring"""
				return VivitImageProcessor() if is_vision_available() else None





		@slow
		def   snake_case_     (       self       )							->			Union[str, Any]:


				"""simple docstring"""
				UpperCAmelCase  							=		VivitForVideoClassification.from_pretrained('google/vivit-b-16x2-kinetics400'       ).to(a_       )

				UpperCAmelCase  							=		self.default_image_processor
				UpperCAmelCase  							=		prepare_video()
				UpperCAmelCase  							=		image_processor(a_				,	return_tensors='pt'       ).to(a_       )

				# forward pass
				with torch.no_grad():
						UpperCAmelCase  							=		model(**a_       )

				# verify the logits
				UpperCAmelCase  							=		torch.Size((1, 4_0_0)       )
				self.assertEqual(outputs.logits.shape				,	a_       )

				# taken from original model
				UpperCAmelCase  							=		torch.tensor([-1.0543, 2.0764, -0.2104, 0.4439, -0.9658]       ).to(a_       )

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





'''simple docstring'''




from collections import namedtuple

_a			:	int								=  namedtuple('from_to', 'from_ to')

_a			:	Dict								=  {
    'atm': from_to(1, 1),
    'pascal': from_to(0.0000098, 101_325),
    'bar': from_to(0.986923, 1.01325),
    'kilopascal': from_to(0.00986923, 101.325),
    'megapascal': from_to(9.86923, 0.101325),
    'psi': from_to(0.068046, 14.6959),
    'inHg': from_to(0.0334211, 29.9213),
    'torr': from_to(0.00131579, 760),
}


def  lowerCamelCase__						(  SCREAMING_SNAKE_CASE :				float    ,				SCREAMING_SNAKE_CASE :				str    ,				SCREAMING_SNAKE_CASE :				str  ):
  if from_type not in PRESSURE_CONVERSION:
    raise ValueError(
        f'''Invalid \'from_type\' value: {from_type!r}  Supported values are:\n'''
        + ', '.join(SCREAMING_SNAKE_CASE  )  )
  if to_type not in PRESSURE_CONVERSION:
    raise ValueError(
        f'''Invalid \'to_type\' value: {to_type!r}.  Supported values are:\n'''
        + ', '.join(SCREAMING_SNAKE_CASE  )  )
  return (
      value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to
  )


if __name__ == "__main__":
  import doctest

  doctest.testmod()


