


'''simple docstring'''

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      ,  UpperCamelCase      ,  UpperCamelCase=2      ,  UpperCamelCase=True      ,  UpperCamelCase=True      ,  UpperCamelCase=10      ,  UpperCamelCase=10      ,  UpperCamelCase=8      ,  UpperCamelCase=[2, 4, 4]      ,  UpperCamelCase=3      ,  UpperCamelCase=768      ,  UpperCamelCase=5      ,  UpperCamelCase=4      ,  UpperCamelCase=37      ,  UpperCamelCase="gelu_fast"      ,  UpperCamelCase=0.0      ,  UpperCamelCase=0.0      ,  UpperCamelCase=0.02      ,  UpperCamelCase=1e-06      ,  UpperCamelCase=True      ,  UpperCamelCase=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   snake_case		(   self					):







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







   """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   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  VivitModel(config=UpperCamelCase					)
   model.to(UpperCamelCase					)
   model.eval()
   lowerCamelCase_								=  model(UpperCamelCase					)
   self.parent.assertEqual(result.last_hidden_state.shape      ,  (self.batch_size, self.seq_length, self.hidden_size)					)






  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase					):







   """simple docstring"""
   lowerCamelCase_								=  VivitForVideoClassification(UpperCamelCase					)
   model.to(UpperCamelCase					)
   model.eval()

   lowerCamelCase_								=  model(UpperCamelCase					)

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







  def   snake_case		(   self					):







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





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





  """simple docstring"""




  _lowerCamelCase		   =  (VivitModel, VivitForVideoClassification) if is_torch_available() else ()

  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  False
  _lowerCamelCase		   =  False






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_								=  VivitModelTester(self					)
   lowerCamelCase_								=  ConfigTester(self      ,  config_class=UpperCamelCase      ,  has_text_modality=UpperCamelCase      ,  hidden_size=37					)






  def   snake_case		(   self      ,  UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase=False					):







   """simple docstring"""
   lowerCamelCase_								=  copy.deepcopy(UpperCamelCase					)

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

   return inputs_dict






  def   snake_case		(   self					):







   """simple docstring"""
   self.config_tester.run_common_tests()






  @unittest.skip(reason="Vivit does not use inputs_embeds"					)
  def   snake_case		(   self					):







   """simple docstring"""
   pass






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_			,lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs_for_common()

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






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_			,lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
    lowerCamelCase_								=  model_class(UpperCamelCase					)
    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]      ,  UpperCamelCase					)






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCamelCase					)






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_video_classification(*UpperCamelCase					)






  @slow
  def   snake_case		(   self					):







   """simple docstring"""
   for model_name in VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    lowerCamelCase_								=  VivitModel.from_pretrained(UpperCamelCase					)
    self.assertIsNotNone(UpperCamelCase					)






  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_			,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(UpperCamelCase					)
    model.to(UpperCamelCase					)
    model.eval()
    with torch.no_grad():
     lowerCamelCase_								=  model(**self._prepare_for_class(UpperCamelCase      ,  UpperCamelCase					)					)
    lowerCamelCase_								=  outputs.attentions
    self.assertEqual(len(UpperCamelCase					)      ,  self.model_tester.num_hidden_layers					)

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

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

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

    lowerCamelCase_								=  outputs.attentions

    self.assertEqual(len(UpperCamelCase					)      ,  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   snake_case		(   self					):







   """simple docstring"""
   def check_hidden_states_output(UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase					):
    lowerCamelCase_								=  model_class(UpperCamelCase					)
    model.to(UpperCamelCase					)
    model.eval()

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

    lowerCamelCase_								=  outputs.hidden_states
    lowerCamelCase_								=  self.model_tester.num_hidden_layers + 1
    self.assertEqual(len(UpperCamelCase					)      ,  UpperCamelCase					)

    lowerCamelCase_								=  self.model_tester.seq_length

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

   lowerCamelCase_			,lowerCamelCase_								=  self.model_tester.prepare_config_and_inputs_for_common()

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

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

    check_hidden_states_output(UpperCamelCase      ,  UpperCamelCase      ,  UpperCamelCase					)







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







   """simple docstring"""
   pass





def __snake_case (				):
 lowerCamelCase_								=  hf_hub_download(
     repo_id="hf-internal-testing/spaghetti-video" ,    filename="eating_spaghetti_32_frames.npy" ,    repo_type="dataset"		)
 lowerCamelCase_								=  np.load(UpperCAmelCase_		)
 return list(UpperCAmelCase_		)







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





  """simple docstring"""




  @cached_property
  def   snake_case		(   self					):







   """simple docstring"""
   return VivitImageProcessor() if is_vision_available() else None







  @slow
  def   snake_case		(   self					):







   """simple docstring"""
   lowerCamelCase_								=  VivitForVideoClassification.from_pretrained("google/vivit-b-16x2-kinetics400"					).to(UpperCamelCase					)

   lowerCamelCase_								=  self.default_image_processor
   lowerCamelCase_								=  prepare_video()
   lowerCamelCase_								=  image_processor(UpperCamelCase      ,  return_tensors="pt"					).to(UpperCamelCase					)

   # forward pass
   with torch.no_grad():
    lowerCamelCase_								=  model(**UpperCamelCase					)

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

   # taken from original model
   lowerCamelCase_								=  torch.tensor([-1.0_543, 2.0_764, -0.2_104, 0.4_439, -0.9_658]					).to(UpperCamelCase					)

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







'''simple docstring'''

import argparse
import json
import re
import string
import sys
from collections import Counter





def __snake_case (				UpperCAmelCase_						:						str		):

 def remove_articles(UpperCAmelCase_						:						Optional[Any]		):
  return re.sub(r"\b(a|an|the)\b" ,    " " ,    UpperCAmelCase_		)

 def white_space_fix(UpperCAmelCase_						:						List[str]		):
  return " ".join(text.split()		)

 def remove_punc(UpperCAmelCase_						:						Any		):
  lowerCamelCase_								=  set(string.punctuation		)
  return "".join(ch for ch in text if ch not in exclude		)

 def lower(UpperCAmelCase_						:						List[str]		):
  return text.lower()

 return white_space_fix(remove_articles(remove_punc(lower(UpperCAmelCase_		)		)		)		)





def __snake_case (				UpperCAmelCase_						:						Tuple ,    UpperCAmelCase_						:						int		):
 lowerCamelCase_								=  normalize_answer(UpperCAmelCase_		).split()
 lowerCamelCase_								=  normalize_answer(UpperCAmelCase_		).split()
 lowerCamelCase_								=  Counter(UpperCAmelCase_		) & Counter(UpperCAmelCase_		)
 lowerCamelCase_								=  sum(common.values()		)
 if num_same == 0:
  return 0
 lowerCamelCase_								=  1.0 * num_same / len(UpperCAmelCase_		)
 lowerCamelCase_								=  1.0 * num_same / len(UpperCAmelCase_		)
 lowerCamelCase_								=  (2 * precision * recall) / (precision + recall)
 return fa





def __snake_case (				UpperCAmelCase_						:						Tuple ,    UpperCAmelCase_						:						List[Any]		):
 return normalize_answer(UpperCAmelCase_		) == normalize_answer(UpperCAmelCase_		)





def __snake_case (				UpperCAmelCase_						:						Any ,    UpperCAmelCase_						:						Dict ,    UpperCAmelCase_						:						Union[str, Any]		):
 lowerCamelCase_								=  []
 for ground_truth in ground_truths:
  lowerCamelCase_								=  metric_fn(UpperCAmelCase_ ,    UpperCAmelCase_		)
  scores_for_ground_truths.append(UpperCAmelCase_		)
 return max(UpperCAmelCase_		)





def __snake_case (				UpperCAmelCase_						:						Optional[int] ,    UpperCAmelCase_						:						Dict		):
 lowerCamelCase_								=  lowerCamelCase_								=  lowerCamelCase_								=  0
 lowerCamelCase_								=  []
 for passage in dataset:
  for qa in passage["qas"]:
   total += 1
   if qa["id"] not in predictions:
    lowerCamelCase_								=  F'''Unanswered question {qa["id"]} will receive score 0.'''
    print(UpperCAmelCase_ ,    file=sys.stderr		)
    continue

   lowerCamelCase_								=  [x["text"] for x in qa["answers"]]
   lowerCamelCase_								=  predictions[qa["id"]]

   lowerCamelCase_								=  metric_max_over_ground_truths(UpperCAmelCase_ ,    UpperCAmelCase_ ,    UpperCAmelCase_		)
   if int(_exact_match		) == 1:
    correct_ids.append(qa["id"]		)
   exact_match += _exact_match

   fa += metric_max_over_ground_truths(UpperCAmelCase_ ,    UpperCAmelCase_ ,    UpperCAmelCase_		)

 lowerCamelCase_								=  exact_match / total
 lowerCamelCase_								=  fa / total

 return {"exact_match": exact_match, "f1": fa}, correct_ids


if __name__ == "__main__":
     a_  :    Optional[int]      =			"""1.0"""
     a_  :    Dict      =			argparse.ArgumentParser("""Official evaluation script for ReCoRD v1.0.""")
     parser.add_argument("""data_file""", help="""The dataset file in JSON format.""")
     parser.add_argument("""pred_file""", help="""The model prediction file in JSON format.""")
     parser.add_argument("""--output_correct_ids""", action="""store_true""", help="""Output the correctly answered query IDs.""")
     a_  :    Optional[int]      =			parser.parse_args()

     with open(args.data_file) as data_file:
          a_  :    Any      =			json.load(data_file)
          if dataset_json["version"] != expected_version:
               print(
                   f'''Evaluation expects v-{expected_version}, but got dataset with v-{dataset_json['version']}''',
                   file=sys.stderr,
               )
          a_  :    Any      =			dataset_json["""data"""]

     with open(args.pred_file) as pred_file:
          a_  :    List[str]      =			json.load(pred_file)

     a_     ,       a_  :    int      =			evaluate(dataset, predictions)

     if args.output_correct_ids:
          print(f'''Output {len(correct_ids)} correctly answered question IDs.''')
          with open("""correct_ids.json""", """w""") as f:
               json.dump(correct_ids, f)



