





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






    '''simple docstring'''





    def __init__( self    :		Optional[int]      ,    snake_case    :		int      ,    snake_case    :		Any=2      ,    snake_case    :		Union[str, Any]=True      ,    snake_case    :		str=True      ,    snake_case    :		Dict=10      ,    snake_case    :		Union[str, Any]=10      ,    snake_case    :		int=8      ,    snake_case    :		Tuple=[2, 4, 4]      ,    snake_case    :		Optional[Any]=3      ,    snake_case    :		Optional[Any]=768      ,    snake_case    :		List[Any]=5      ,    snake_case    :		Union[str, Any]=4      ,    snake_case    :		Optional[Any]=37      ,    snake_case    :		Union[str, Any]="gelu_fast"      ,    snake_case    :		Union[str, Any]=0.0      ,    snake_case    :		Optional[Any]=0.0      ,    snake_case    :		Union[str, Any]=0.02      ,    snake_case    :		int=1e-06      ,    snake_case    :		Any=True      ,    snake_case    :		Optional[Any]=None      ,    ):

      """simple docstring"""





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

      __lowerCAmelCase								=					(
          (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 						A		( self    :		List[Any]				):

      """simple docstring"""





      __lowerCAmelCase								=					floats_tensor(
          [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]				)

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

      __lowerCAmelCase								=					self.get_config()

      return config, pixel_values, labels





    def 						A		( self    :		Optional[Any]				):

      """simple docstring"""





      __lowerCAmelCase								=					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      ,    )
      __lowerCAmelCase								=					self.num_labels
      return config





    def 						A		( self    :		str      ,    snake_case    :		str      ,    snake_case    :		Tuple      ,    snake_case    :		Optional[int]				):

      """simple docstring"""





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





    def 						A		( self    :		str      ,    snake_case    :		int      ,    snake_case    :		str      ,    snake_case    :		Dict				):

      """simple docstring"""





      __lowerCAmelCase								=					VivitForVideoClassification(lowerCAmelCase_				)
      model.to(lowerCAmelCase_				)
      model.eval()

      __lowerCAmelCase								=					model(lowerCAmelCase_				)

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





    def 						A		( self    :		Optional[int]				):

      """simple docstring"""





      __lowerCAmelCase								=					self.prepare_config_and_inputs()
      __lowerCAmelCase								=					config_and_inputs
      __lowerCAmelCase								=					{'''pixel_values''': pixel_values}
      return config, inputs_dict


@require_torch
class 	__snake_case					(      snake_case__							,					unittest.TestCase ):






    '''simple docstring'''
    _lowerCAmelCase  =						(VivitModel, VivitForVideoClassification) if is_torch_available() else ()

    _lowerCAmelCase  =						False
    _lowerCAmelCase  =						False
    _lowerCAmelCase  =						False
    _lowerCAmelCase  =						False





    def 						A		( self    :		Tuple				):

      """simple docstring"""





      __lowerCAmelCase								=					VivitModelTester(self				)
      __lowerCAmelCase								=					ConfigTester(self      ,    config_class=lowerCAmelCase_      ,    has_text_modality=lowerCAmelCase_      ,    hidden_size=37				)





    def 						A		( self    :		List[str]      ,    snake_case    :		Dict      ,    snake_case    :		str      ,    snake_case    :		int=False				):

      """simple docstring"""





      __lowerCAmelCase								=					copy.deepcopy(lowerCAmelCase_				)

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

      return inputs_dict





    def 						A		( self    :		int				):

      """simple docstring"""





      self.config_tester.run_common_tests()





    @unittest.skip(reason='''Vivit does not use inputs_embeds'''				)
    def 						A		( self    :		Optional[Any]				):

      """simple docstring"""





      pass





    def 						A		( self    :		Union[str, Any]				):

      """simple docstring"""





      __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs_for_common()

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





    def 						A		( self    :		Union[str, Any]				):

      """simple docstring"""





      __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowerCAmelCase								=					['''pixel_values''', '''head_mask''']
        self.assertListEqual(arg_names[:2]      ,    lowerCAmelCase_				)





    def 						A		( self    :		Optional[int]				):

      """simple docstring"""





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





    def 						A		( self    :		Union[str, Any]				):

      """simple docstring"""





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





    @slow
    def 						A		( self    :		Optional[Any]				):

      """simple docstring"""





      for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __lowerCAmelCase								=					VivitModel.from_pretrained(lowerCAmelCase_				)
        self.assertIsNotNone(lowerCAmelCase_				)





    def 						A		( self    :		Union[str, Any]				):

      """simple docstring"""





      __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs_for_common()
      __lowerCAmelCase								=					True

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

        __lowerCAmelCase								=					True
        __lowerCAmelCase								=					False
        __lowerCAmelCase								=					True
        __lowerCAmelCase								=					model_class(lowerCAmelCase_				)
        model.to(lowerCAmelCase_				)
        model.eval()
        with torch.no_grad():
          __lowerCAmelCase								=					model(**self._prepare_for_class(lowerCAmelCase_      ,    lowerCAmelCase_				)				)
        __lowerCAmelCase								=					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"]
        __lowerCAmelCase								=					True
        __lowerCAmelCase								=					model_class(lowerCAmelCase_				)
        model.to(lowerCAmelCase_				)
        model.eval()
        with torch.no_grad():
          __lowerCAmelCase								=					model(**self._prepare_for_class(lowerCAmelCase_      ,    lowerCAmelCase_				)				)
        __lowerCAmelCase								=					outputs.attentions
        self.assertEqual(len(lowerCAmelCase_				)      ,    self.model_tester.num_hidden_layers				)

        self.assertListEqual(
            list(attentions[0].shape[-3:]				)      ,    [self.model_tester.num_attention_heads, seq_len, seq_len]      ,    )
        __lowerCAmelCase								=					len(lowerCAmelCase_				)

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

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

        __lowerCAmelCase								=					outputs.attentions

        self.assertEqual(len(lowerCAmelCase_				)      ,    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 						A		( self    :		Optional[Any]				):

      """simple docstring"""





      def check_hidden_states_output(snake_case    :		Union[str, Any]      ,    snake_case    :		str      ,    snake_case    :		Optional[Any]				):
        __lowerCAmelCase								=					model_class(lowerCAmelCase_				)
        model.to(lowerCAmelCase_				)
        model.eval()

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

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

        __lowerCAmelCase								=					self.model_tester.seq_length

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

      __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs_for_common()

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

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

        check_hidden_states_output(lowerCAmelCase_      ,    lowerCAmelCase_      ,    lowerCAmelCase_				)





    @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''				)
    def 						A		( self    :		Tuple				):

      """simple docstring"""





      pass


def        __SCREAMING_SNAKE_CASE	(				):



  '''simple docstring'''






  __lowerCAmelCase								=					hf_hub_download(
      repo_id='''hf-internal-testing/spaghetti-video'''  ,				filename='''eating_spaghetti_32_frames.npy'''  ,				repo_type='''dataset''')
  __lowerCAmelCase								=					np.load(lowerCAmelCase_)
  return list(lowerCAmelCase_)




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






    '''simple docstring'''





    @cached_property
    def 						A		( self    :		str				):

      """simple docstring"""





      return VivitImageProcessor() if is_vision_available() else None





    @slow
    def 						A		( self    :		Dict				):

      """simple docstring"""





      __lowerCAmelCase								=					VivitForVideoClassification.from_pretrained('''google/vivit-b-16x2-kinetics400'''				).to(lowerCAmelCase_				)

      __lowerCAmelCase								=					self.default_image_processor
      __lowerCAmelCase								=					prepare_video()
      __lowerCAmelCase								=					image_processor(lowerCAmelCase_      ,    return_tensors='''pt'''				).to(lowerCAmelCase_				)

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

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

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

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

import re
import tempfile
import unittest
from pathlib import Path

from datasets.utils.metadata import DatasetMetadata







def 						UpperCAmelCase							(		lowerCAmelCase_							)						->						str:
     a	:     Optional[Any]						      =    min(re.search('''^ +'''    ,   lowerCAmelCase_							).end() if t.startswith(''' '''							) else 0 for t in string.splitlines()							)
     return "\n".join([line[indent_level:] for line in string.splitlines() if indent_level < len(lowerCAmelCase_							)]							)


UpperCAmelCase				 =   """\
---
language:
- zh
- en
task_ids:
- sentiment-classification
---
# Begin of markdown

Some cool dataset card
"""

UpperCAmelCase				 =   """\
---
---
# Begin of markdown

Some cool dataset card
"""


UpperCAmelCase				 =   """\
# Begin of markdown

Some cool dataset card
"""






class 				_SCREAMING_SNAKE_CASE( unittest.TestCase						):
   def _lowercase(     self     )						->List[str]:
        with tempfile.TemporaryDirectory() as tmp_dir:
             a	:     List[str]						      =    Path(lowerCAmelCase_     ) / '''README.md'''
             with open(lowerCAmelCase_				,  '''w+'''     ) as readme_file:
                  readme_file.write(lowerCAmelCase_     )
             a	:     Dict						      =    DatasetMetadata.from_readme(lowerCAmelCase_     )
             self.assertDictEqual(lowerCAmelCase_				,  {'''language''': ['''zh''', '''en'''], '''task_ids''': ['''sentiment-classification''']}     )

             with open(lowerCAmelCase_				,  '''w+'''     ) as readme_file:
                  readme_file.write(lowerCAmelCase_     )
             a	:     List[str]						      =    DatasetMetadata.from_readme(lowerCAmelCase_     )
             self.assertDictEqual(lowerCAmelCase_				,  {}     )

             with open(lowerCAmelCase_				,  '''w+'''     ) as readme_file:
                  readme_file.write(lowerCAmelCase_     )
             a	:     List[Any]						      =    DatasetMetadata.from_readme(lowerCAmelCase_     )
             self.assertEqual(lowerCAmelCase_				,  {}     )


   def _lowercase(     self     )						->Optional[Any]:
        a	:     Tuple						      =    _dedent(
            '''\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            '''     )
        assert DatasetMetadata.from_yaml_string(lowerCAmelCase_     )

        a	:     Dict						      =    _dedent(
            '''\
            annotations_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - question-answering
            task_ids:
            - open-domain-qa
            task_ids:
            - open-domain-qa
            '''     )
        with self.assertRaises(lowerCAmelCase_     ):
             DatasetMetadata.from_yaml_string(lowerCAmelCase_     )

        a	:     Optional[int]						      =    _dedent(
            '''\
            annotations_creators:
            - found
            language_creators:
            - found
            language:
            - en
            license:
            - unknown
            multilinguality:
            - monolingual
            pretty_name: Test Dataset
            size_categories:
            - 10K<n<100K
            source_datasets:
            - extended|other-yahoo-webscope-l6
            task_categories:
            - text-classification
            task_ids:
            - multi-class-classification
            paperswithcode_id:
            - squad
            configs:
            - en
            train-eval-index:
            - config: en
              task: text-classification
              task_id: multi_class_classification
              splits:
                train_split: train
                eval_split: test
              col_mapping:
                text: text
                label: target
              metrics:
                - type: accuracy
                  name: Accuracy
            extra_gated_prompt: |
              By clicking on “Access repository” below, you also agree to ImageNet Terms of Access:
              [RESEARCHER_FULLNAME] (the "Researcher") has requested permission to use the ImageNet database (the "Database") at Princeton University and Stanford University. In exchange for such permission, Researcher hereby agrees to the following terms and conditions:
              1. Researcher shall use the Database only for non-commercial research and educational purposes.
            extra_gated_fields:
              Company: text
              Country: text
              I agree to use this model for non-commerical use ONLY: checkbox
            '''     )
        assert DatasetMetadata.from_yaml_string(lowerCAmelCase_     )