
'''simple docstring'''




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		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE=13		,     SCREAMING_SNAKE_CASE=10		,     SCREAMING_SNAKE_CASE=3		,     SCREAMING_SNAKE_CASE=2		,     SCREAMING_SNAKE_CASE=2		,     SCREAMING_SNAKE_CASE=True		,     SCREAMING_SNAKE_CASE=True		,     SCREAMING_SNAKE_CASE=32		,     SCREAMING_SNAKE_CASE=5		,     SCREAMING_SNAKE_CASE=4		,     SCREAMING_SNAKE_CASE=37		,     SCREAMING_SNAKE_CASE="gelu"		,     SCREAMING_SNAKE_CASE=0.1		,     SCREAMING_SNAKE_CASE=0.1		,     SCREAMING_SNAKE_CASE=10		,     SCREAMING_SNAKE_CASE=0.02		,     SCREAMING_SNAKE_CASE="divided_space_time"		,     SCREAMING_SNAKE_CASE=None		,     )					->							List[Any]:






         """simple docstring"""






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

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





     def 							__lowerCAmelCase				(				self      )					->							Tuple:






         """simple docstring"""






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

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

         A			:  int   =		self.get_config()

         return config, pixel_values, labels





     def 							__lowerCAmelCase				(				self      )					->							str:






         """simple docstring"""






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





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )					->							Optional[Any]:






         """simple docstring"""






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





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )					->							Optional[Any]:






         """simple docstring"""






         A			:  str   =		TimesformerForVideoClassification(SCREAMING_SNAKE_CASE      )
         model.to(SCREAMING_SNAKE_CASE      )
         model.eval()

         A			:  str   =		model(SCREAMING_SNAKE_CASE      )

         # verify the logits shape
         A			:  str   =		torch.Size((self.batch_size, self.num_labels)      )
         self.parent.assertEqual(result.logits.shape		,     SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							List[str]:






         """simple docstring"""






         A			:  str   =		self.prepare_config_and_inputs()
         A,    A,    A			:  Optional[int]   =		config_and_inputs
         A			:  Optional[int]   =		{'''pixel_values''': pixel_values}
         return config, inputs_dict





@require_torch
class 					A							(				__snake_case       ,     __snake_case       ,     unittest.TestCase		):
     __magic_name__          =						(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
     __magic_name__          =						(
         {'''feature-extraction''': TimesformerModel, '''video-classification''': TimesformerForVideoClassification}
         if is_torch_available()
         else {}
     )

     __magic_name__          =						False
     __magic_name__          =						False
     __magic_name__          =						False
     __magic_name__          =						False





     def 							__lowerCAmelCase				(				self      )					->							Tuple:






         """simple docstring"""






         A			:  Dict   =		TimesformerModelTester(self      )
         A			:  List[Any]   =		ConfigTester(
             self		,     config_class=SCREAMING_SNAKE_CASE		,     has_text_modality=SCREAMING_SNAKE_CASE		,     hidden_size=37      )





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE=False      )					->							Optional[int]:






         """simple docstring"""






         A			:  int   =		copy.deepcopy(SCREAMING_SNAKE_CASE      )

         if return_labels:
             if model_class in get_values(SCREAMING_SNAKE_CASE      ):
                 A			:  int   =		torch.zeros(
                     self.model_tester.batch_size		,     dtype=torch.long		,     device=SCREAMING_SNAKE_CASE      )

         return inputs_dict





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






         """simple docstring"""






         self.config_tester.run_common_tests()





     @unittest.skip(reason='''TimeSformer does not use inputs_embeds'''      )
     def 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         pass





     def 							__lowerCAmelCase				(				self      )					->							List[str]:






         """simple docstring"""






         A,    A			:  int   =		self.model_tester.prepare_config_and_inputs_for_common()

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





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






         """simple docstring"""






         A,    A			:  Optional[Any]   =		self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             A			:  Tuple   =		model_class(SCREAMING_SNAKE_CASE      )
             A			:  List[str]   =		inspect.signature(model.forward      )
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             A			:  int   =		[*signature.parameters.keys()]

             A			:  str   =		['''pixel_values''']
             self.assertListEqual(arg_names[:1]		,     SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         A			:  Optional[Any]   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							Tuple:






         """simple docstring"""






         A			:  Optional[int]   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE      )





     @slow
     def 							__lowerCAmelCase				(				self      )					->							Dict:






         """simple docstring"""






         for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             A			:  str   =		TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE      )
             self.assertIsNotNone(SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							Dict:






         """simple docstring"""






         if not self.has_attentions:
             pass

         else:
             A,    A			:  str   =		self.model_tester.prepare_config_and_inputs_for_common()
             A			:  Optional[Any]   =		True

             for model_class in self.all_model_classes:
                 A			:  int   =		self.model_tester.seq_length
                 A			:  str   =		self.model_tester.num_frames

                 A			:  Union[str, Any]   =		True
                 A			:  int   =		False
                 A			:  int   =		True
                 A			:  Optional[int]   =		model_class(SCREAMING_SNAKE_CASE      )
                 model.to(SCREAMING_SNAKE_CASE      )
                 model.eval()
                 with torch.no_grad():
                     A			:  int   =		model(**self._prepare_for_class(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )      )
                 A			:  str   =		outputs.attentions
                 self.assertEqual(len(SCREAMING_SNAKE_CASE      )		,     self.model_tester.num_hidden_layers      )

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

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

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

                 A			:  Optional[int]   =		outputs.attentions

                 self.assertEqual(len(SCREAMING_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 							__lowerCAmelCase				(				self      )					->							int:






         """simple docstring"""






         def check_hidden_states_output(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      ):
             A			:  Optional[Any]   =		model_class(SCREAMING_SNAKE_CASE      )
             model.to(SCREAMING_SNAKE_CASE      )
             model.eval()

             with torch.no_grad():
                 A			:  Dict   =		model(**self._prepare_for_class(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )      )

             A			:  str   =		outputs.hidden_states
             A			:  Optional[Any]   =		self.model_tester.num_hidden_layers + 1
             self.assertEqual(len(SCREAMING_SNAKE_CASE      )		,     SCREAMING_SNAKE_CASE      )

             A			:  Union[str, Any]   =		self.model_tester.seq_length

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

         A,    A			:  Optional[Any]   =		self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             A			:  str   =		True
             check_hidden_states_output(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )

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

             check_hidden_states_output(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )







def 						lowerCAmelCase_							(  ):




    '''simple docstring'''



    A			:  Any   =		hf_hub_download(
        repo_id='''hf-internal-testing/spaghetti-video'''						,							filename='''eating_spaghetti.npy'''						,							repo_type='''dataset'''		)
    A			:  Tuple   =		np.load(snake_case__		)
    return list(snake_case__		)







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





     @cached_property
     def 							__lowerCAmelCase				(				self      )					->							str:






         """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 							__lowerCAmelCase				(				self      )					->							str:






         """simple docstring"""






         A			:  int   =		TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400'''      ).to(
             SCREAMING_SNAKE_CASE      )

         A			:  Tuple   =		self.default_image_processor
         A			:  List[Any]   =		prepare_video()
         A			:  List[str]   =		image_processor(video[:8]		,     return_tensors='''pt'''      ).to(SCREAMING_SNAKE_CASE      )

         # forward pass
         with torch.no_grad():
             A			:  str   =		model(**SCREAMING_SNAKE_CASE      )

         # verify the logits
         A			:  List[str]   =		torch.Size((1, 400)      )
         self.assertEqual(outputs.logits.shape		,     SCREAMING_SNAKE_CASE      )

         A			:  List[str]   =		torch.tensor([-0.3_016, -0.7_713, -0.4_205]      ).to(SCREAMING_SNAKE_CASE      )

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






'''simple docstring'''




lowercase     :							dict[str, float]       						=     {
    "joule": 1.0,
    "kilojoule": 10_00,
    "megajoule": 1_00_00_00,
    "gigajoule": 10_00_00_00_00,
    "wattsecond": 1.0,
    "watthour": 36_00,
    "kilowatthour": 3_60_00_00,
    "newtonmeter": 1.0,
    "calorie_nutr": 41_86.8,
    "kilocalorie_nutr": 4_18_68_00.00,
    "electronvolt": 1.6_02_17_66_34e-19,
    "britishthermalunit_it": 10_55.0_55_85,
    "footpound": 1.35_58_18,
}







def 						lowerCAmelCase_							(  snake_case__						,							snake_case__						,							snake_case__		):




    '''simple docstring'''



    if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION:
        A			:  int   =		(
            F'Incorrect \'from_type\' or \'to_type\' value: {from_type!r}, {to_type!r}\n'
            F'Valid values are: {", ".join(snake_case__		)}'
        )
        raise ValueError(snake_case__		)
    return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type]


if __name__ == "__main__":
      import doctest

      doctest.testmod()




