




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 		__A      :

						def __init__(		self   :Tuple    , __snake_case   :Optional[int]    , __snake_case   :Union[str, Any]=13    , __snake_case   :Tuple=10    , __snake_case   :Tuple=3    , __snake_case   :Optional[Any]=2    , __snake_case   :Tuple=2    , __snake_case   :List[str]=True    , __snake_case   :Optional[int]=True    , __snake_case   :List[Any]=32    , __snake_case   :Tuple=5    , __snake_case   :Optional[Any]=4    , __snake_case   :List[Any]=37    , __snake_case   :Optional[Any]="gelu"    , __snake_case   :List[str]=0.1    , __snake_case   :Union[str, Any]=0.1    , __snake_case   :Optional[Any]=10    , __snake_case   :List[str]=0.02    , __snake_case   :Dict="divided_space_time"    , __snake_case   :Any=None    , ):
										'''simple docstring'''

										__magic_name__	:	Any								=parent
										__magic_name__	:	Any								=batch_size
										__magic_name__	:	Union[str, Any]								=image_size
										__magic_name__	:	Any								=num_channels
										__magic_name__	:	Optional[int]								=patch_size
										__magic_name__	:	Tuple								=num_frames
										__magic_name__	:	Union[str, Any]								=is_training
										__magic_name__	:	Optional[int]								=use_labels
										__magic_name__	:	Tuple								=hidden_size
										__magic_name__	:	Union[str, Any]								=num_hidden_layers
										__magic_name__	:	Tuple								=num_attention_heads
										__magic_name__	:	int								=intermediate_size
										__magic_name__	:	str								=hidden_act
										__magic_name__	:	str								=hidden_dropout_prob
										__magic_name__	:	Optional[Any]								=attention_probs_dropout_prob
										__magic_name__	:	int								=attention_type
										__magic_name__	:	Union[str, Any]								=initializer_range
										__magic_name__	:	List[str]								=scope
										__magic_name__	:	List[Any]								=num_labels

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

						def     A__						(		self   :Optional[int] ):
										'''simple docstring'''

										__magic_name__	:	Optional[int]								=floats_tensor(
										    [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] )

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

										__magic_name__	:	Dict								=self.get_config()

										return config, pixel_values, labels

						def     A__						(		self   :Optional[int] ):
										'''simple docstring'''

										__magic_name__	:	List[Any]								=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    , )
										__magic_name__	:	Optional[int]								=self.num_labels
										return config

						def     A__						(		self   :int    , __snake_case   :Tuple    , __snake_case   :Optional[Any]    , __snake_case   :str ):
										'''simple docstring'''

										__magic_name__	:	Dict								=TimesformerModel(config=__snake_case )
										model.to(__snake_case )
										model.eval()
										__magic_name__	:	List[Any]								=model(__snake_case )
										self.parent.assertEqual(result.last_hidden_state.shape    , (self.batch_size, self.seq_length, self.hidden_size) )

						def     A__						(		self   :Any    , __snake_case   :Any    , __snake_case   :Optional[int]    , __snake_case   :Dict ):
										'''simple docstring'''

										__magic_name__	:	int								=TimesformerForVideoClassification(__snake_case )
										model.to(__snake_case )
										model.eval()

										__magic_name__	:	Optional[int]								=model(__snake_case )

										# verify the logits shape
										__magic_name__	:	int								=torch.Size((self.batch_size, self.num_labels) )
										self.parent.assertEqual(result.logits.shape    , __snake_case )


						def     A__						(		self   :str ):
										'''simple docstring'''

										__magic_name__	:	Union[str, Any]								=self.prepare_config_and_inputs()
										__magic_name__				, __magic_name__				, __magic_name__	:	Union[str, Any]								=config_and_inputs
										__magic_name__	:	Any								={"""pixel_values""": pixel_values}
										return config, inputs_dict




@require_torch
class 		__A      (			UpperCamelCase__					,						UpperCamelCase__					,						unittest.TestCase			):
						UpperCamelCase     						=					(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
						UpperCamelCase     						=					(
						    {"""feature-extraction""": TimesformerModel, """video-classification""": TimesformerForVideoClassification}
						    if is_torch_available()
						    else {}
						)

						UpperCamelCase     						=					False
						UpperCamelCase     						=					False
						UpperCamelCase     						=					False
						UpperCamelCase     						=					False

						def     A__						(		self   :List[Any] ):
										'''simple docstring'''

										__magic_name__	:	Dict								=TimesformerModelTester(self )
										__magic_name__	:	Union[str, Any]								=ConfigTester(
										    self    , config_class=__snake_case    , has_text_modality=__snake_case    , hidden_size=37 )

						def     A__						(		self   :List[str]    , __snake_case   :List[str]    , __snake_case   :Tuple    , __snake_case   :Dict=False ):
										'''simple docstring'''

										__magic_name__	:	Dict								=copy.deepcopy(__snake_case )

										if return_labels:
														if model_class in get_values(__snake_case ):
																		__magic_name__	:	Tuple								=torch.zeros(
																		    self.model_tester.batch_size    , dtype=torch.long    , device=__snake_case )

										return inputs_dict

						def     A__						(		self   :Optional[int] ):
										'''simple docstring'''

										self.config_tester.run_common_tests()

						@unittest.skip(reason="""TimeSformer does not use inputs_embeds""" )
						def     A__						(		self   :Tuple ):
										'''simple docstring'''

										pass

						def     A__						(		self   :Any ):
										'''simple docstring'''

										__magic_name__				, __magic_name__	:	Any								=self.model_tester.prepare_config_and_inputs_for_common()

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

						def     A__						(		self   :Any ):
										'''simple docstring'''

										__magic_name__				, __magic_name__	:	List[Any]								=self.model_tester.prepare_config_and_inputs_for_common()

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

														__magic_name__	:	int								=["""pixel_values"""]
														self.assertListEqual(arg_names[:1]    , __snake_case )

						def     A__						(		self   :Optional[Any] ):
										'''simple docstring'''

										__magic_name__	:	List[str]								=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__snake_case )

						def     A__						(		self   :Union[str, Any] ):
										'''simple docstring'''

										__magic_name__	:	Any								=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_video_classification(*__snake_case )

						@slow
						def     A__						(		self   :Any ):
										'''simple docstring'''

										for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														__magic_name__	:	Dict								=TimesformerModel.from_pretrained(__snake_case )
														self.assertIsNotNone(__snake_case )

						def     A__						(		self   :str ):
										'''simple docstring'''

										if not self.has_attentions:
														pass

										else:
														__magic_name__				, __magic_name__	:	Any								=self.model_tester.prepare_config_and_inputs_for_common()
														__magic_name__	:	str								=True

														for model_class in self.all_model_classes:
																		__magic_name__	:	Union[str, Any]								=self.model_tester.seq_length
																		__magic_name__	:	str								=self.model_tester.num_frames

																		__magic_name__	:	Tuple								=True
																		__magic_name__	:	str								=False
																		__magic_name__	:	List[Any]								=True
																		__magic_name__	:	List[str]								=model_class(__snake_case )
																		model.to(__snake_case )
																		model.eval()
																		with torch.no_grad():
																						__magic_name__	:	Any								=model(**self._prepare_for_class(__snake_case    , __snake_case ) )
																		__magic_name__	:	Optional[Any]								=outputs.attentions
																		self.assertEqual(len(__snake_case )    , self.model_tester.num_hidden_layers )

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

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

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

																		__magic_name__	:	List[str]								=outputs.attentions

																		self.assertEqual(len(__snake_case )    , 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   :List[Any] ):
										'''simple docstring'''

										def check_hidden_states_output(__snake_case   :Optional[int]    , __snake_case   :Optional[Any]    , __snake_case   :Any ):
														__magic_name__	:	int								=model_class(__snake_case )
														model.to(__snake_case )
														model.eval()

														with torch.no_grad():
																		__magic_name__	:	List[Any]								=model(**self._prepare_for_class(__snake_case    , __snake_case ) )

														__magic_name__	:	List[Any]								=outputs.hidden_states
														__magic_name__	:	Union[str, Any]								=self.model_tester.num_hidden_layers + 1
														self.assertEqual(len(__snake_case )    , __snake_case )

														__magic_name__	:	Any								=self.model_tester.seq_length

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

										__magic_name__				, __magic_name__	:	Any								=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														__magic_name__	:	str								=True
														check_hidden_states_output(__snake_case    , __snake_case    , __snake_case )

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														__magic_name__	:	Optional[int]								=True

														check_hidden_states_output(__snake_case    , __snake_case    , __snake_case )




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




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

						@cached_property
						def     A__						(		self   :int ):
										'''simple docstring'''

										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   :int ):
										'''simple docstring'''

										__magic_name__	:	Union[str, Any]								=TimesformerForVideoClassification.from_pretrained("""facebook/timesformer-base-finetuned-k400""" ).to(
										    __snake_case )

										__magic_name__	:	List[Any]								=self.default_image_processor
										__magic_name__	:	Any								=prepare_video()
										__magic_name__	:	List[str]								=image_processor(video[:8]    , return_tensors="""pt""" ).to(__snake_case )

										# forward pass
										with torch.no_grad():
														__magic_name__	:	Dict								=model(**__snake_case )

										# verify the logits
										__magic_name__	:	Tuple								=torch.Size((1, 4_00) )
										self.assertEqual(outputs.logits.shape    , __snake_case )

										__magic_name__	:	List[Any]								=torch.tensor([-0.3016, -0.7713, -0.4205] ).to(__snake_case )

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










from math import atan, cos, radians, sin, tan

from .haversine_distance import haversine_distance

UpperCAmelCase_		:				Dict									=     637_8137.0
UpperCAmelCase_		:				List[Any]									=     635_6752.31_4245
UpperCAmelCase_		:				List[str]									=     6378137




def 		lowerCAmelCase_   (	lowerCamelCase	,     lowerCamelCase	,     lowerCamelCase	,     lowerCamelCase   ):
				__magic_name__	:	str								=(AXIS_A - AXIS_B) / AXIS_A
				# Parametric latitudes
				# https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude
				__magic_name__	:	str								=atan((1 - flattening) * tan(radians(lowerCamelCase   )   )   )
				__magic_name__	:	List[Any]								=atan((1 - flattening) * tan(radians(lowerCamelCase   )   )   )

				# Compute central angle between two points
				# using haversine theta. sigma =  haversine_distance / equatorial radius
				__magic_name__	:	List[Any]								=haversine_distance(lowerCamelCase	,     lowerCamelCase	,     lowerCamelCase	,     lowerCamelCase   ) / EQUATORIAL_RADIUS

				# Intermediate P and Q values
				__magic_name__	:	Tuple								=(b_lata + b_lata) / 2
				__magic_name__	:	int								=(b_lata - b_lata) / 2

				# Intermediate X value
				# X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2)
				__magic_name__	:	Optional[int]								=(sin(lowerCamelCase   ) ** 2) * (cos(lowerCamelCase   ) ** 2)
				__magic_name__	:	Any								=cos(sigma / 2   ) ** 2
				__magic_name__	:	List[Any]								=(sigma - sin(lowerCamelCase   )) * (x_numerator / x_demonimator)

				# Intermediate Y value
				# Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2)
				__magic_name__	:	Any								=(cos(lowerCamelCase   ) ** 2) * (sin(lowerCamelCase   ) ** 2)
				__magic_name__	:	Optional[Any]								=sin(sigma / 2   ) ** 2
				__magic_name__	:	str								=(sigma + sin(lowerCamelCase   )) * (y_numerator / y_denominator)

				return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value)))


if __name__ == "__main__":
							import doctest

							doctest.testmod()




