






'''simple docstring'''
from jiwer import compute_measures

import datasets


a_					= '\\n@inproceedings{inproceedings,\n    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n    year = {2004},\n    month = {01},\n    pages = {},\n    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n'

a_					= '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n'

a_					= '\nCompute WER score of transcribed segments against references.\n\nArgs:\n    references: List of references for each speech input.\n    predictions: List of transcriptions to score.\n    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n    (float): the word error rate\n\nExamples:\n\n    >>> predictions = ["this is the prediction", "there is an other sample"]\n    >>> references = ["this is the reference", "there is another one"]\n    >>> wer = datasets.load_metric("wer")\n    >>> wer_score = wer.compute(predictions=predictions, references=references)\n    >>> print(wer_score)\n    0.5\n'






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




 def      __magic_name__	(      self	:							List[str]      )	->						Union[str, Any]:
       return datasets.MetricInfo(
           description=_DESCRIPTION					,      citation=_CITATION					,      inputs_description=_KWARGS_DESCRIPTION					,      features=datasets.Features(
               {
                   '''predictions''': datasets.Value('''string'''					,      id='''sequence'''      ),
                   '''references''': datasets.Value('''string'''					,      id='''sequence'''      ),
               }      )					,      codebase_urls=['''https://github.com/jitsi/jiwer/''']					,      reference_urls=[
               '''https://en.wikipedia.org/wiki/Word_error_rate''',
           ]					,      )




 def      __magic_name__	(      self	:							Tuple					,      __lowercase	:							List[Any]=None					,      __lowercase	:							Optional[Any]=None					,      __lowercase	:							Any=False      )	->						Optional[int]:
       if concatenate_texts:
             return compute_measures(__lowercase					,      __lowercase      )["wer"]
       else:
             SCREAMING_SNAKE_CASE__     :				int									=0
             SCREAMING_SNAKE_CASE__     :				List[Any]									=0
             for prediction, reference in zip(__lowercase					,      __lowercase      ):
                   SCREAMING_SNAKE_CASE__     :				Optional[int]									=compute_measures(__lowercase					,      __lowercase      )
                   incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
                   total += measures["substitutions"] + measures["deletions"] + measures["hits"]
             return incorrect / total







'''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      __SCREAMING_SNAKE_CASE      :




 def __init__(      self	:							Optional[int]					,      __lowercase	:							Optional[int]					,      __lowercase	:							str=13					,      __lowercase	:							int=10					,      __lowercase	:							List[Any]=3					,      __lowercase	:							List[str]=2					,      __lowercase	:							int=2					,      __lowercase	:							Dict=True					,      __lowercase	:							Optional[Any]=True					,      __lowercase	:							int=32					,      __lowercase	:							List[Any]=5					,      __lowercase	:							Union[str, Any]=4					,      __lowercase	:							Any=37					,      __lowercase	:							Optional[Any]="gelu"					,      __lowercase	:							Union[str, Any]=0.1					,      __lowercase	:							Tuple=0.1					,      __lowercase	:							Dict=10					,      __lowercase	:							int=0.02					,      __lowercase	:							str="divided_space_time"					,      __lowercase	:							Union[str, Any]=None					,      )	->						Optional[Any]:
       SCREAMING_SNAKE_CASE__     :				int									=parent
       SCREAMING_SNAKE_CASE__     :				List[str]									=batch_size
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=image_size
       SCREAMING_SNAKE_CASE__     :				List[Any]									=num_channels
       SCREAMING_SNAKE_CASE__     :				int									=patch_size
       SCREAMING_SNAKE_CASE__     :				Tuple									=num_frames
       SCREAMING_SNAKE_CASE__     :				List[Any]									=is_training
       SCREAMING_SNAKE_CASE__     :				List[str]									=use_labels
       SCREAMING_SNAKE_CASE__     :				Optional[Any]									=hidden_size
       SCREAMING_SNAKE_CASE__     :				str									=num_hidden_layers
       SCREAMING_SNAKE_CASE__     :				int									=num_attention_heads
       SCREAMING_SNAKE_CASE__     :				Tuple									=intermediate_size
       SCREAMING_SNAKE_CASE__     :				List[str]									=hidden_act
       SCREAMING_SNAKE_CASE__     :				Dict									=hidden_dropout_prob
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE__     :				List[Any]									=attention_type
       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=initializer_range
       SCREAMING_SNAKE_CASE__     :				Any									=scope
       SCREAMING_SNAKE_CASE__     :				int									=num_labels

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




 def      __magic_name__	(      self	:							Optional[int]      )	->						Tuple:
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=floats_tensor(
           [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size]      )

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

       SCREAMING_SNAKE_CASE__     :				int									=self.get_config()

       return config, pixel_values, labels




 def      __magic_name__	(      self	:							int      )	->						Any:
       SCREAMING_SNAKE_CASE__     :				Union[str, 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					,      )
       SCREAMING_SNAKE_CASE__     :				List[Any]									=self.num_labels
       return config




 def      __magic_name__	(      self	:							int					,      __lowercase	:							Optional[int]					,      __lowercase	:							Dict					,      __lowercase	:							List[Any]      )	->						int:
       SCREAMING_SNAKE_CASE__     :				Tuple									=TimesformerModel(config=__lowercase      )
       model.to(__lowercase      )
       model.eval()
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=model(__lowercase      )
       self.parent.assertEqual(result.last_hidden_state.shape					,      (self.batch_size, self.seq_length, self.hidden_size)      )




 def      __magic_name__	(      self	:							List[str]					,      __lowercase	:							str					,      __lowercase	:							Tuple					,      __lowercase	:							List[Any]      )	->						List[Any]:
       SCREAMING_SNAKE_CASE__     :				str									=TimesformerForVideoClassification(__lowercase      )
       model.to(__lowercase      )
       model.eval()

       SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=model(__lowercase      )

       # verify the logits shape
       SCREAMING_SNAKE_CASE__     :				Tuple									=torch.Size((self.batch_size, self.num_labels)      )
       self.parent.assertEqual(result.logits.shape					,      __lowercase      )




 def      __magic_name__	(      self	:							Any      )	->						List[Any]:
       SCREAMING_SNAKE_CASE__     :				int									=self.prepare_config_and_inputs()
       SCREAMING_SNAKE_CASE__		,	SCREAMING_SNAKE_CASE__		,	SCREAMING_SNAKE_CASE__     :				str									=config_and_inputs
       SCREAMING_SNAKE_CASE__     :				Any									={'''pixel_values''': pixel_values}
       return config, inputs_dict






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

 snake_case_  							=							False
 snake_case_  							=							False
 snake_case_  							=							False
 snake_case_  							=							False




 def      __magic_name__	(      self	:							str      )	->						Optional[int]:
       SCREAMING_SNAKE_CASE__     :				Dict									=TimesformerModelTester(self      )
       SCREAMING_SNAKE_CASE__     :				List[Any]									=ConfigTester(
           self					,      config_class=__lowercase					,      has_text_modality=__lowercase					,      hidden_size=37      )




 def      __magic_name__	(      self	:							str					,      __lowercase	:							Dict					,      __lowercase	:							str					,      __lowercase	:							Optional[int]=False      )	->						int:
       SCREAMING_SNAKE_CASE__     :				str									=copy.deepcopy(__lowercase      )

       if return_labels:
             if model_class in get_values(__lowercase      ):
                   SCREAMING_SNAKE_CASE__     :				Any									=torch.zeros(
                       self.model_tester.batch_size					,      dtype=torch.long					,      device=__lowercase      )

       return inputs_dict




 def      __magic_name__	(      self	:							List[Any]      )	->						Any:
       self.config_tester.run_common_tests()




 @unittest.skip(reason='''TimeSformer does not use inputs_embeds'''      )
 def      __magic_name__	(      self	:							List[Any]      )	->						Optional[int]:
       pass




 def      __magic_name__	(      self	:							str      )	->						Tuple:
       SCREAMING_SNAKE_CASE__		,	SCREAMING_SNAKE_CASE__     :				List[Any]									=self.model_tester.prepare_config_and_inputs_for_common()

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




 def      __magic_name__	(      self	:							Any      )	->						Any:
       SCREAMING_SNAKE_CASE__		,	SCREAMING_SNAKE_CASE__     :				str									=self.model_tester.prepare_config_and_inputs_for_common()

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

             SCREAMING_SNAKE_CASE__     :				Dict									=['''pixel_values''']
             self.assertListEqual(arg_names[:1]					,      __lowercase      )




 def      __magic_name__	(      self	:							int      )	->						Dict:
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowercase      )




 def      __magic_name__	(      self	:							List[str]      )	->						Optional[int]:
       SCREAMING_SNAKE_CASE__     :				Optional[int]									=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_video_classification(*__lowercase      )




 @slow
 def      __magic_name__	(      self	:							Optional[int]      )	->						Optional[Any]:
       for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=TimesformerModel.from_pretrained(__lowercase      )
             self.assertIsNotNone(__lowercase      )




 def      __magic_name__	(      self	:							Union[str, Any]      )	->						List[str]:
       if not self.has_attentions:
             pass

       else:
             SCREAMING_SNAKE_CASE__		,	SCREAMING_SNAKE_CASE__     :				Any									=self.model_tester.prepare_config_and_inputs_for_common()
             SCREAMING_SNAKE_CASE__     :				List[Any]									=True

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

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

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

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

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

                   SCREAMING_SNAKE_CASE__     :				List[str]									=outputs.attentions

                   self.assertEqual(len(__lowercase      )					,      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      __magic_name__	(      self	:							Tuple      )	->						List[Any]:
       def check_hidden_states_output(__lowercase	:							Tuple					,      __lowercase	:							Dict					,      __lowercase	:							Optional[int]      ):
             SCREAMING_SNAKE_CASE__     :				List[Any]									=model_class(__lowercase      )
             model.to(__lowercase      )
             model.eval()

             with torch.no_grad():
                   SCREAMING_SNAKE_CASE__     :				int									=model(**self._prepare_for_class(__lowercase					,      __lowercase      )      )

             SCREAMING_SNAKE_CASE__     :				List[Any]									=outputs.hidden_states
             SCREAMING_SNAKE_CASE__     :				Tuple									=self.model_tester.num_hidden_layers + 1
             self.assertEqual(len(__lowercase      )					,      __lowercase      )

             SCREAMING_SNAKE_CASE__     :				int									=self.model_tester.seq_length

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

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

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__     :				Tuple									=True
             check_hidden_states_output(__lowercase					,      __lowercase					,      __lowercase      )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             SCREAMING_SNAKE_CASE__     :				List[str]									=True

             check_hidden_states_output(__lowercase					,      __lowercase					,      __lowercase      )





def  _a(  ):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__     :				Union[str, Any]									=hf_hub_download(
          repo_id='''hf-internal-testing/spaghetti-video''',	filename='''eating_spaghetti.npy''',	repo_type='''dataset'''							)
      SCREAMING_SNAKE_CASE__     :				Any									=np.load(UpperCamelCase__							)
      return list(UpperCamelCase__							)







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




 @cached_property
 def      __magic_name__	(      self	:							Any      )	->						List[str]:
       # logits were tested with a different mean and std, so we use the same here
       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      __magic_name__	(      self	:							Any      )	->						Optional[Any]:
       SCREAMING_SNAKE_CASE__     :				int									=TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400'''      ).to(
           __lowercase      )

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

       # forward pass
       with torch.no_grad():
             SCREAMING_SNAKE_CASE__     :				Optional[int]									=model(**__lowercase      )

       # verify the logits
       SCREAMING_SNAKE_CASE__     :				List[str]									=torch.Size((1, 4_00)      )
       self.assertEqual(outputs.logits.shape					,      __lowercase      )

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

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