






import copy
import inspect
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers import TimesformerConfig
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,
	    TimesformerForVideoClassification,
	    TimesformerModel,
	)
	from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from transformers import VideoMAEImageProcessor

class     _SCREAMING_SNAKE_CASE       :





	def __init__(		self				:					int ,  __lowerCamelCase				:					Optional[int] ,  __lowerCamelCase				:					List[str]=13 ,  __lowerCamelCase				:					List[Any]=10 ,  __lowerCamelCase				:					str=3 ,  __lowerCamelCase				:					Optional[Any]=2 ,  __lowerCamelCase				:					List[str]=2 ,  __lowerCamelCase				:					Optional[int]=True ,  __lowerCamelCase				:					Optional[int]=True ,  __lowerCamelCase				:					int=32 ,  __lowerCamelCase				:					Any=5 ,  __lowerCamelCase				:					Union[str, Any]=4 ,  __lowerCamelCase				:					Optional[int]=37 ,  __lowerCamelCase				:					int="gelu" ,  __lowerCamelCase				:					int=0.1 ,  __lowerCamelCase				:					Optional[int]=0.1 ,  __lowerCamelCase				:					Union[str, Any]=10 ,  __lowerCamelCase				:					Tuple=0.02 ,  __lowerCamelCase				:					Tuple="divided_space_time" ,  __lowerCamelCase				:					Union[str, Any]=None ,  ):
		UpperCamelCase     :Union[str, Any]          =	parent
		UpperCamelCase     :List[str]          =	batch_size
		UpperCamelCase     :Any          =	image_size
		UpperCamelCase     :Optional[Any]          =	num_channels
		UpperCamelCase     :int          =	patch_size
		UpperCamelCase     :List[Any]          =	num_frames
		UpperCamelCase     :Optional[Any]          =	is_training
		UpperCamelCase     :Tuple          =	use_labels
		UpperCamelCase     :Optional[int]          =	hidden_size
		UpperCamelCase     :int          =	num_hidden_layers
		UpperCamelCase     :Union[str, Any]          =	num_attention_heads
		UpperCamelCase     :Tuple          =	intermediate_size
		UpperCamelCase     :List[Any]          =	hidden_act
		UpperCamelCase     :List[Any]          =	hidden_dropout_prob
		UpperCamelCase     :str          =	attention_probs_dropout_prob
		UpperCamelCase     :List[Any]          =	attention_type
		UpperCamelCase     :Union[str, Any]          =	initializer_range
		UpperCamelCase     :Dict          =	scope
		UpperCamelCase     :List[Any]          =	num_labels

		# in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
		UpperCamelCase     :List[str]          =	(image_size // patch_size) ** 2
		UpperCamelCase     :Any          =	(num_frames) * self.num_patches_per_frame + 1





	def 						_A (		self				:					List[Any]	):
		UpperCamelCase     :Tuple          =	floats_tensor(
		    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]	)

		UpperCamelCase     :List[str]          =	None
		if self.use_labels:
			UpperCamelCase     :Dict          =	ids_tensor([self.batch_size] ,  self.num_labels	)

		UpperCamelCase     :Optional[int]          =	self.get_config()

		return config, pixel_values, labels





	def 						_A (		self				:					Optional[Any]	):
		UpperCamelCase     :Optional[int]          =	TimesformerConfig(
		    image_size=self.image_size ,  patch_size=self.patch_size ,  num_channels=self.num_channels ,  num_frames=self.num_frames ,  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 ,  attention_type=self.attention_type ,  )
		UpperCamelCase     :Any          =	self.num_labels
		return config





	def 						_A (		self				:					List[Any] ,  __lowerCamelCase				:					List[str] ,  __lowerCamelCase				:					Optional[int] ,  __lowerCamelCase				:					Dict	):
		UpperCamelCase     :str          =	TimesformerModel(config=__lowerCamelCase	)
		model.to(__lowerCamelCase	)
		model.eval()
		UpperCamelCase     :List[str]          =	model(__lowerCamelCase	)
		self.parent.assertEqual(result.last_hidden_state.shape ,  (self.batch_size, self.seq_length, self.hidden_size)	)





	def 						_A (		self				:					Optional[int] ,  __lowerCamelCase				:					Dict ,  __lowerCamelCase				:					Any ,  __lowerCamelCase				:					Tuple	):
		UpperCamelCase     :Tuple          =	TimesformerForVideoClassification(__lowerCamelCase	)
		model.to(__lowerCamelCase	)
		model.eval()

		UpperCamelCase     :Dict          =	model(__lowerCamelCase	)

		# verify the logits shape
		UpperCamelCase     :List[str]          =	torch.Size((self.batch_size, self.num_labels)	)
		self.parent.assertEqual(result.logits.shape ,  __lowerCamelCase	)





	def 						_A (		self				:					int	):
		UpperCamelCase     :Dict          =	self.prepare_config_and_inputs()
		UpperCamelCase     ,      UpperCamelCase     ,      UpperCamelCase     :Optional[int]          =	config_and_inputs
		UpperCamelCase     :Optional[int]          =	{"""pixel_values""": pixel_values}
		return config, inputs_dict

@require_torch
class     _SCREAMING_SNAKE_CASE       (			_a		,   _a		,   unittest.TestCase      ):
	snake_case__							:     Optional[Any]     	=  (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
	snake_case__							:     List[str]     	=  (
	    {"""feature-extraction""": TimesformerModel, """video-classification""": TimesformerForVideoClassification}
	    if is_torch_available()
	    else {}
	)

	snake_case__							:     Union[str, Any]     	=  False
	snake_case__							:     Tuple     	=  False
	snake_case__							:     Optional[Any]     	=  False
	snake_case__							:     Optional[int]     	=  False





	def 						_A (		self				:					Dict	):
		UpperCamelCase     :int          =	TimesformerModelTester(self	)
		UpperCamelCase     :Union[str, Any]          =	ConfigTester(
		    self ,  config_class=__lowerCamelCase ,  has_text_modality=__lowerCamelCase ,  hidden_size=37	)





	def 						_A (		self				:					Any ,  __lowerCamelCase				:					Union[str, Any] ,  __lowerCamelCase				:					Union[str, Any] ,  __lowerCamelCase				:					Any=False	):
		UpperCamelCase     :List[Any]          =	copy.deepcopy(__lowerCamelCase	)

		if return_labels:
			if model_class in get_values(__lowerCamelCase	):
				UpperCamelCase     :Union[str, Any]          =	torch.zeros(
				    self.model_tester.batch_size ,  dtype=torch.long ,  device=__lowerCamelCase	)

		return inputs_dict





	def 						_A (		self				:					Dict	):
		self.config_tester.run_common_tests()





	@unittest.skip(reason="""TimeSformer does not use inputs_embeds"""	)
	def 						_A (		self				:					List[str]	):
		pass





	def 						_A (		self				:					Tuple	):
		UpperCamelCase     ,      UpperCamelCase     :str          =	self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in self.all_model_classes:
			UpperCamelCase     :Tuple          =	model_class(__lowerCamelCase	)
			self.assertIsInstance(model.get_input_embeddings() ,  (nn.Module)	)
			UpperCamelCase     :List[Any]          =	model.get_output_embeddings()
			self.assertTrue(x is None or isinstance(__lowerCamelCase ,  nn.Linear	)	)





	def 						_A (		self				:					List[Any]	):
		UpperCamelCase     ,      UpperCamelCase     :Optional[int]          =	self.model_tester.prepare_config_and_inputs_for_common()

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

			UpperCamelCase     :int          =	["""pixel_values"""]
			self.assertListEqual(arg_names[:1] ,  __lowerCamelCase	)





	def 						_A (		self				:					str	):
		UpperCamelCase     :List[Any]          =	self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_model(*__lowerCamelCase	)





	def 						_A (		self				:					int	):
		UpperCamelCase     :Optional[Any]          =	self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_video_classification(*__lowerCamelCase	)





	@slow
	def 						_A (		self				:					str	):
		for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			UpperCamelCase     :Any          =	TimesformerModel.from_pretrained(__lowerCamelCase	)
			self.assertIsNotNone(__lowerCamelCase	)





	def 						_A (		self				:					List[Any]	):
		if not self.has_attentions:
			pass

		else:
			UpperCamelCase     ,      UpperCamelCase     :Optional[int]          =	self.model_tester.prepare_config_and_inputs_for_common()
			UpperCamelCase     :Optional[int]          =	True

			for model_class in self.all_model_classes:
				UpperCamelCase     :str          =	self.model_tester.seq_length
				UpperCamelCase     :Optional[int]          =	self.model_tester.num_frames

				UpperCamelCase     :Union[str, Any]          =	True
				UpperCamelCase     :Optional[int]          =	False
				UpperCamelCase     :List[str]          =	True
				UpperCamelCase     :str          =	model_class(__lowerCamelCase	)
				model.to(__lowerCamelCase	)
				model.eval()
				with torch.no_grad():
					UpperCamelCase     :Union[str, Any]          =	model(**self._prepare_for_class(__lowerCamelCase ,  __lowerCamelCase	)	)
				UpperCamelCase     :str          =	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"]
				UpperCamelCase     :Dict          =	True
				UpperCamelCase     :Union[str, Any]          =	model_class(__lowerCamelCase	)
				model.to(__lowerCamelCase	)
				model.eval()
				with torch.no_grad():
					UpperCamelCase     :int          =	model(**self._prepare_for_class(__lowerCamelCase ,  __lowerCamelCase	)	)
				UpperCamelCase     :Union[str, Any]          =	outputs.attentions
				self.assertEqual(len(__lowerCamelCase	) ,  self.model_tester.num_hidden_layers	)

				# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
				self.assertListEqual(
				    list(attentions[0].shape[-3:]	) ,  [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] ,  )
				UpperCamelCase     :Dict          =	len(__lowerCamelCase	)

				# Check attention is always last and order is fine
				UpperCamelCase     :Union[str, Any]          =	True
				UpperCamelCase     :int          =	True
				UpperCamelCase     :Optional[int]          =	model_class(__lowerCamelCase	)
				model.to(__lowerCamelCase	)
				model.eval()
				with torch.no_grad():
					UpperCamelCase     :Union[str, Any]          =	model(**self._prepare_for_class(__lowerCamelCase ,  __lowerCamelCase	)	)

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

				UpperCamelCase     :str          =	outputs.attentions

				self.assertEqual(len(__lowerCamelCase	) ,  self.model_tester.num_hidden_layers	)

				# attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1)
				self.assertListEqual(
				    list(self_attentions[0].shape[-3:]	) ,  [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] ,  )





	def 						_A (		self				:					Tuple	):
		def check_hidden_states_output(__lowerCamelCase				:					List[str] ,  __lowerCamelCase				:					Any ,  __lowerCamelCase				:					Optional[Any]	):
			UpperCamelCase     :int          =	model_class(__lowerCamelCase	)
			model.to(__lowerCamelCase	)
			model.eval()

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

			UpperCamelCase     :Optional[Any]          =	outputs.hidden_states
			UpperCamelCase     :Tuple          =	self.model_tester.num_hidden_layers + 1
			self.assertEqual(len(__lowerCamelCase	) ,  __lowerCamelCase	)

			UpperCamelCase     :Tuple          =	self.model_tester.seq_length

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

		UpperCamelCase     ,      UpperCamelCase     :Dict          =	self.model_tester.prepare_config_and_inputs_for_common()

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

			# check that output_hidden_states also work using config
			del inputs_dict["output_hidden_states"]
			UpperCamelCase     :Union[str, Any]          =	True

			check_hidden_states_output(__lowerCamelCase ,  __lowerCamelCase ,  __lowerCamelCase	)

def    SCREAMING_SNAKE_CASE_							(							)		->			List[Any]:






	"""simple docstring"""



	UpperCamelCase     :Dict          =	hf_hub_download(
	    repo_id="""hf-internal-testing/spaghetti-video"""	,			filename="""eating_spaghetti.npy"""	,			repo_type="""dataset"""					)
	UpperCamelCase     :Optional[int]          =	np.load(__magic_name__					)
	return list(__magic_name__					)

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





	@cached_property
	def 						_A (		self				:					Tuple	):
		# 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 						_A (		self				:					Union[str, Any]	):
		UpperCamelCase     :int          =	TimesformerForVideoClassification.from_pretrained("""facebook/timesformer-base-finetuned-k400"""	).to(
		    __lowerCamelCase	)

		UpperCamelCase     :Dict          =	self.default_image_processor
		UpperCamelCase     :int          =	prepare_video()
		UpperCamelCase     :Any          =	image_processor(video[:8] ,  return_tensors="""pt"""	).to(__lowerCamelCase	)

		# forward pass
		with torch.no_grad():
			UpperCamelCase     :Optional[int]          =	model(**__lowerCamelCase	)

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

		UpperCamelCase     :str          =	torch.tensor([-0.3016, -0.7713, -0.4205]	).to(__lowerCamelCase	)

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








from ...utils import (
    OptionalDependencyNotAvailable,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)


try:
	if not (is_transformers_available() and is_torch_available()):
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline
else:
	from .camera import create_pan_cameras
	from .pipeline_shap_e import ShapEPipeline
	from .pipeline_shap_e_img2img import ShapEImgaImgPipeline
	from .renderer import (
	    BoundingBoxVolume,
	    ImportanceRaySampler,
	    MLPNeRFModelOutput,
	    MLPNeRSTFModel,
	    ShapEParamsProjModel,
	    ShapERenderer,
	    StratifiedRaySampler,
	    VoidNeRFModel,
	)
