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



  """simple docstring"""






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




    '''simple docstring'''




    __UpperCAmelCase						    =       parent
    __UpperCAmelCase						    =       batch_size
    __UpperCAmelCase						    =       image_size
    __UpperCAmelCase						    =       num_channels
    __UpperCAmelCase						    =       patch_size
    __UpperCAmelCase						    =       num_frames
    __UpperCAmelCase						    =       is_training
    __UpperCAmelCase						    =       use_labels
    __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						    =       attention_type
    __UpperCAmelCase						    =       initializer_range
    __UpperCAmelCase						    =       scope
    __UpperCAmelCase						    =       num_labels

    # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token
    __UpperCAmelCase						    =       (image_size // patch_size) ** 2
    __UpperCAmelCase						    =       (num_frames) * self.num_patches_per_frame + 1






  def 	_UpperCAmelCase				(				self:			List[Any]   ) -> Dict:




    '''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 	_UpperCAmelCase				(				self:			Tuple   ) -> List[str]:




    '''simple docstring'''




    __UpperCAmelCase						    =       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						    =       self.num_labels
    return config






  def 	_UpperCAmelCase				(				self:			Dict				,				__lowerCAmelCase:			int				,				__lowerCAmelCase:			Tuple				,				__lowerCAmelCase:			Union[str, Any]   ) -> str:




    '''simple docstring'''




    __UpperCAmelCase						    =       TimesformerModel(config=__lowerCAmelCase   )
    model.to(__lowerCAmelCase   )
    model.eval()
    __UpperCAmelCase						    =       model(__lowerCAmelCase   )
    self.parent.assertEqual(result.last_hidden_state.shape				,				(self.batch_size, self.seq_length, self.hidden_size)   )






  def 	_UpperCAmelCase				(				self:			str				,				__lowerCAmelCase:			Union[str, Any]				,				__lowerCAmelCase:			Dict				,				__lowerCAmelCase:			Dict   ) -> Optional[int]:




    '''simple docstring'''




    __UpperCAmelCase						    =       TimesformerForVideoClassification(__lowerCAmelCase   )
    model.to(__lowerCAmelCase   )
    model.eval()

    __UpperCAmelCase						    =       model(__lowerCAmelCase   )

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






  def 	_UpperCAmelCase				(				self:			Tuple   ) -> Optional[int]:




    '''simple docstring'''




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






@require_torch
class 			UpperCAmelCase__    (		snake_case		,	snake_case		,	unittest.TestCase					):



  """simple docstring"""






  lowerCAmelCase__		:	List[Any]    		= (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
  lowerCAmelCase__		:	List[str]    		= (
      {'feature-extraction': TimesformerModel, 'video-classification': TimesformerForVideoClassification}
      if is_torch_available()
      else {}
  )

  lowerCAmelCase__		:	List[str]    		= False
  lowerCAmelCase__		:	Dict    		= False
  lowerCAmelCase__		:	Tuple    		= False
  lowerCAmelCase__		:	Union[str, Any]    		= False






  def 	_UpperCAmelCase				(				self:			int   ) -> Tuple:




    '''simple docstring'''




    __UpperCAmelCase						    =       TimesformerModelTester(self   )
    __UpperCAmelCase						    =       ConfigTester(
        self				,				config_class=__lowerCAmelCase				,				has_text_modality=__lowerCAmelCase				,				hidden_size=37   )






  def 	_UpperCAmelCase				(				self:			List[Any]				,				__lowerCAmelCase:			List[str]				,				__lowerCAmelCase:			List[str]				,				__lowerCAmelCase:			Optional[int]=False   ) -> List[Any]:




    '''simple docstring'''




    __UpperCAmelCase						    =       copy.deepcopy(__lowerCAmelCase   )

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

    return inputs_dict






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




    '''simple docstring'''




    self.config_tester.run_common_tests()






  @unittest.skip(reason="TimeSformer does not use inputs_embeds"   )
  def 	_UpperCAmelCase				(				self:			Dict   ) -> Union[str, Any]:




    '''simple docstring'''




    pass






  def 	_UpperCAmelCase				(				self:			Tuple   ) -> List[Any]:




    '''simple docstring'''




    __UpperCAmelCase    ,		__UpperCAmelCase						    =       self.model_tester.prepare_config_and_inputs_for_common()

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






  def 	_UpperCAmelCase				(				self:			List[Any]   ) -> str:




    '''simple docstring'''




    __UpperCAmelCase    ,		__UpperCAmelCase						    =       self.model_tester.prepare_config_and_inputs_for_common()

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

      __UpperCAmelCase						    =       ["pixel_values"]
      self.assertListEqual(arg_names[:1]				,				__lowerCAmelCase   )






  def 	_UpperCAmelCase				(				self:			Tuple   ) -> Dict:




    '''simple docstring'''




    __UpperCAmelCase						    =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowerCAmelCase   )






  def 	_UpperCAmelCase				(				self:			Tuple   ) -> Tuple:




    '''simple docstring'''




    __UpperCAmelCase						    =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_video_classification(*__lowerCAmelCase   )






  @slow
  def 	_UpperCAmelCase				(				self:			List[Any]   ) -> Any:




    '''simple docstring'''




    for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      __UpperCAmelCase						    =       TimesformerModel.from_pretrained(__lowerCAmelCase   )
      self.assertIsNotNone(__lowerCAmelCase   )






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




    '''simple docstring'''




    if not self.has_attentions:
      pass

    else:
      __UpperCAmelCase    ,		__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						    =       self.model_tester.num_frames

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

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

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

        __UpperCAmelCase						    =       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 	_UpperCAmelCase				(				self:			Dict   ) -> Optional[Any]:




    '''simple docstring'''




    def check_hidden_states_output(__lowerCAmelCase:			Tuple				,				__lowerCAmelCase:			Tuple				,				__lowerCAmelCase:			str   ):
      __UpperCAmelCase						    =       model_class(__lowerCAmelCase   )
      model.to(__lowerCAmelCase   )
      model.eval()

      with torch.no_grad():
        __UpperCAmelCase						    =       model(**self._prepare_for_class(__lowerCAmelCase				,				__lowerCAmelCase   )   )

      __UpperCAmelCase						    =       outputs.hidden_states
      __UpperCAmelCase						    =       self.model_tester.num_hidden_layers + 1
      self.assertEqual(len(__lowerCAmelCase   )				,				__lowerCAmelCase   )

      __UpperCAmelCase						    =       self.model_tester.seq_length

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

    __UpperCAmelCase    ,		__UpperCAmelCase						    =       self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      __UpperCAmelCase						    =       True
      check_hidden_states_output(__lowerCAmelCase				,				__lowerCAmelCase				,				__lowerCAmelCase   )

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

      check_hidden_states_output(__lowerCAmelCase				,				__lowerCAmelCase				,				__lowerCAmelCase   )






def       __lowerCAmelCase      (						)    ->  List[str]:
  __UpperCAmelCase						    =       hf_hub_download(
      repo_id="hf-internal-testing/spaghetti-video"						,	filename="eating_spaghetti.npy"						,	repo_type="dataset"					)
  __UpperCAmelCase						    =       np.load(A_					)
  return list(A_					)





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



  """simple docstring"""






  @cached_property
  def 	_UpperCAmelCase				(				self:			Tuple   ) -> Any:




    '''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 	_UpperCAmelCase				(				self:			Optional[Any]   ) -> Tuple:




    '''simple docstring'''




    __UpperCAmelCase						    =       TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400"   ).to(
        __lowerCAmelCase   )

    __UpperCAmelCase						    =       self.default_image_processor
    __UpperCAmelCase						    =       prepare_video()
    __UpperCAmelCase						    =       image_processor(video[:8]				,				return_tensors="pt"   ).to(__lowerCAmelCase   )

    # forward pass
    with torch.no_grad():
      __UpperCAmelCase						    =       model(**__lowerCAmelCase   )

    # verify the logits
    __UpperCAmelCase						    =       torch.Size((1, 400)   )
    self.assertEqual(outputs.logits.shape				,				__lowerCAmelCase   )

    __UpperCAmelCase						    =       torch.tensor([-0.3016, -0.7713, -0.4205]   ).to(__lowerCAmelCase   )

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




from sklearn.metrics import fa_score

import datasets


a_							=      """
The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:
F1 = 2 * (precision * recall) / (precision + recall)
"""


a_							=      """
Args:
    predictions (`list` of `int`): Predicted labels.
    references (`list` of `int`): Ground truth labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.

        - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.
        - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.
        - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.

Returns:
    f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.

Examples:

    Example 1-A simple binary example
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {'f1': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results['f1'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> f1_metric = datasets.load_metric(\"f1\")
        >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])
        >>> print(round(results['f1'], 2))
        0.35

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")
        >>> print(round(results['f1'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")
        >>> print(round(results['f1'], 2))
        0.33
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")
        >>> print(round(results['f1'], 2))
        0.27
        >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'f1': array([0.8, 0. , 0. ])}
"""


a_							=      """
@article{scikit-learn,
    title={Scikit-learn: Machine Learning in {P}ython},
    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
           and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
           and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
           Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
    journal={Journal of Machine Learning Research},
    volume={12},
    pages={2825--2830},
    year={2011}
}
"""


@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION		,	_KWARGS_DESCRIPTION					)
class 			UpperCAmelCase__    (		datasets.Metric					):



  """simple docstring"""






  def 	_UpperCAmelCase				(				self:			int   ) -> Dict:




    '''simple docstring'''




    return datasets.MetricInfo(
        description=_DESCRIPTION				,				citation=_CITATION				,				inputs_description=_KWARGS_DESCRIPTION				,				features=datasets.Features(
            {
                "predictions": datasets.Sequence(datasets.Value("int32"   )   ),
                "references": datasets.Sequence(datasets.Value("int32"   )   ),
            }
            if self.config_name == "multilabel"
            else {
                "predictions": datasets.Value("int32"   ),
                "references": datasets.Value("int32"   ),
            }   )				,				reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html"]				,				)






  def 	_UpperCAmelCase				(				self:			Any				,				__lowerCAmelCase:			Tuple				,				__lowerCAmelCase:			Any				,				__lowerCAmelCase:			List[Any]=None				,				__lowerCAmelCase:			Optional[Any]=1				,				__lowerCAmelCase:			List[Any]="binary"				,				__lowerCAmelCase:			List[Any]=None   ) -> Optional[int]:




    '''simple docstring'''




    __UpperCAmelCase						    =       fa_score(
        __lowerCAmelCase				,				__lowerCAmelCase				,				labels=__lowerCAmelCase				,				pos_label=__lowerCAmelCase				,				average=__lowerCAmelCase				,				sample_weight=__lowerCAmelCase   )
    return {"f1": float(__lowerCAmelCase   ) if score.size == 1 else score}



