


"""simple docstring"""


import warnings
from typing import Any, Dict, List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


A  :     Union[str, Any]    					=    logging.get_logger(__name__)
class 						_UpperCamelCase						(     lowerCAmelCase__	):
							'''simple docstring'''







							__UpperCAmelCase		:					int          =["""input_values""", """attention_mask"""]

							def __init__(  self					,     __a = 1					,     __a = 1_60_00					,     __a = 0.0					,     __a = False					,     __a = 80					,     __a = 16					,     __a = 64					,     __a = "hann_window"					,     __a = 1.0					,     __a = 80					,     __a = 76_00					,     __a = 1e-1_0					,     __a = 2					,     __a = True					,     **__a					,     ):
										super().__init__(feature_size=__a					,     sampling_rate=__a					,     padding_value=__a					,     **__a			)
										__lowerCAmelCase       					=    do_normalize
										__lowerCAmelCase       					=    return_attention_mask

										__lowerCAmelCase       					=    num_mel_bins
										__lowerCAmelCase       					=    hop_length
										__lowerCAmelCase       					=    win_length
										__lowerCAmelCase       					=    win_function
										__lowerCAmelCase       					=    frame_signal_scale
										__lowerCAmelCase       					=    fmin
										__lowerCAmelCase       					=    fmax
										__lowerCAmelCase       					=    mel_floor
										__lowerCAmelCase       					=    reduction_factor

										__lowerCAmelCase       					=    win_length * sampling_rate // 10_00
										__lowerCAmelCase       					=    hop_length * sampling_rate // 10_00
										__lowerCAmelCase       					=    optimal_fft_length(self.sample_size			)
										__lowerCAmelCase       					=    (self.n_fft // 2) + 1

										__lowerCAmelCase       					=    window_function(window_length=self.sample_size					,     name=self.win_function					,     periodic=__a			)

										__lowerCAmelCase       					=    mel_filter_bank(
										    num_frequency_bins=self.n_freqs					,     num_mel_filters=self.num_mel_bins					,     min_frequency=self.fmin					,     max_frequency=self.fmax					,     sampling_rate=self.sampling_rate					,     norm="slaney"					,     mel_scale="slaney"					,     )

										if frame_signal_scale != 1.0:
													warnings.warn(
													    "The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers"					,     __a					,     )
										if reduction_factor != 2.0:
													warnings.warn(
													    "The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers"					,     __a					,     )

							@staticmethod
							# Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
							def     snake_case       (  __a					,     __a					,     __a = 0.0			):
										if attention_mask is not None:
													__lowerCAmelCase       					=    np.array(__a					,     np.intaa			)
													__lowerCAmelCase       					=    []

													for vector, length in zip(__a					,     attention_mask.sum(-1			)			):
																__lowerCAmelCase       					=    (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7			)
																if length < normed_slice.shape[0]:
																			__lowerCAmelCase       					=    padding_value

																normed_input_values.append(__a			)
										else:
													__lowerCAmelCase       					=    [(x - x.mean()) / np.sqrt(x.var() + 1e-7			) for x in input_values]

										return normed_input_values

							def     snake_case       (  self					,     __a					,     ):
										__lowerCAmelCase       					=    spectrogram(
										    __a					,     window=self.window					,     frame_length=self.sample_size					,     hop_length=self.sample_stride					,     fft_length=self.n_fft					,     mel_filters=self.mel_filters					,     mel_floor=self.mel_floor					,     log_mel="log10"					,     )
										return log_mel_spec.T

							def __call__(  self					,     __a = None					,     __a = None					,     __a = False					,     __a = None					,     __a = False					,     __a = None					,     __a = None					,     __a = None					,     __a = None					,     **__a					,     ):
										if audio is None and audio_target is None:
													raise ValueError("You must provide either `audio` or `audio_target` values."			)

										if sampling_rate is not None:
													if sampling_rate != self.sampling_rate:
																raise ValueError(
																    f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
																    f" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"
																    f" {self.sampling_rate} and not {sampling_rate}."			)
										else:
													logger.warning(
													    "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
													    "Failing to do so can result in silent errors that might be hard to debug."			)

										if audio is not None:
													__lowerCAmelCase       					=    self._process_audio(
													    __a					,     __a					,     __a					,     __a					,     __a					,     __a					,     __a					,     __a					,     **__a					,     )
										else:
													__lowerCAmelCase       					=    None

										if audio_target is not None:
													__lowerCAmelCase       					=    self._process_audio(
													    __a					,     __a					,     __a					,     __a					,     __a					,     __a					,     __a					,     __a					,     **__a					,     )

													if inputs is None:
																return inputs_target
													else:
																__lowerCAmelCase       					=    inputs_target["input_values"]
																__lowerCAmelCase       					=    inputs_target.get("attention_mask"			)
																if decoder_attention_mask is not None:
																			__lowerCAmelCase       					=    decoder_attention_mask

										return inputs

							def     snake_case       (  self					,     __a					,     __a = False					,     __a = False					,     __a = None					,     __a = False					,     __a = None					,     __a = None					,     __a = None					,     **__a					,     ):
										__lowerCAmelCase       					=    isinstance(__a					,     np.ndarray			) and len(speech.shape			) > 1
										if is_batched_numpy and len(speech.shape			) > 2:
													raise ValueError(f"Only mono-channel audio is supported for input to {self}"			)
										__lowerCAmelCase       					=    is_batched_numpy or (
										    isinstance(__a					,     (list, tuple)			) and (isinstance(speech[0]					,     (np.ndarray, tuple, list)			))
										)

										if is_batched:
													__lowerCAmelCase       					=    [np.asarray(__a					,     dtype=np.floataa			) for speech in speech]
										elif not is_batched and not isinstance(__a					,     np.ndarray			):
													__lowerCAmelCase       					=    np.asarray(__a					,     dtype=np.floataa			)
										elif isinstance(__a					,     np.ndarray			) and speech.dtype is np.dtype(np.floataa			):
													__lowerCAmelCase       					=    speech.astype(np.floataa			)

										# always return batch
										if not is_batched:
													__lowerCAmelCase       					=    [speech]

										# needed to make pad() work on spectrogram inputs
										__lowerCAmelCase       					=    self.feature_size

										# convert into correct format for padding
										if is_target:
													__lowerCAmelCase       					=    [self._extract_mel_features(__a			) for waveform in speech]
													__lowerCAmelCase       					=    BatchFeature({"input_values": features}			)
													__lowerCAmelCase       					=    self.num_mel_bins
										else:
													__lowerCAmelCase       					=    BatchFeature({"input_values": speech}			)

										__lowerCAmelCase       					=    self.pad(
										    __a					,     padding=__a					,     max_length=__a					,     truncation=__a					,     pad_to_multiple_of=__a					,     return_attention_mask=__a					,     **__a					,     )

										__lowerCAmelCase       					=    feature_size_hack

										# convert input values to correct format
										__lowerCAmelCase       					=    padded_inputs["input_values"]
										if not isinstance(input_values[0]					,     np.ndarray			):
													__lowerCAmelCase       					=    [np.asarray(__a					,     dtype=np.floataa			) for array in input_values]
										elif (
										    not isinstance(__a					,     np.ndarray			)
										    and isinstance(input_values[0]					,     np.ndarray			)
										    and input_values[0].dtype is np.dtype(np.floataa			)
										):
													__lowerCAmelCase       					=    [array.astype(np.floataa			) for array in input_values]
										elif isinstance(__a					,     np.ndarray			) and input_values.dtype is np.dtype(np.floataa			):
													__lowerCAmelCase       					=    input_values.astype(np.floataa			)

										# convert attention_mask to correct format
										__lowerCAmelCase       					=    padded_inputs.get("attention_mask"			)
										if attention_mask is not None:
													__lowerCAmelCase       					=    [np.asarray(__a					,     dtype=np.intaa			) for array in attention_mask]

										# zero-mean and unit-variance normalization
										if not is_target and self.do_normalize:
													__lowerCAmelCase       					=    (
													    attention_mask
													    if self._get_padding_strategies(__a					,     max_length=__a			) is not PaddingStrategy.DO_NOT_PAD
													    else None
													)
													__lowerCAmelCase       					=    self.zero_mean_unit_var_norm(
													    padded_inputs["input_values"]					,     attention_mask=__a					,     padding_value=self.padding_value			)

										if return_tensors is not None:
													__lowerCAmelCase       					=    padded_inputs.convert_to_tensors(__a			)

										return padded_inputs



							def     snake_case       (  self			):
										__lowerCAmelCase       					=    super().to_dict()

										# Don't serialize these as they are derived from the other properties.
										__lowerCAmelCase       					=    ["window", "mel_filters", "sample_size", "sample_stride", "n_fft", "n_freqs"]
										for name in names:
													if name in output:
																del output[name]

										return output








"""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 						_UpperCamelCase						:
							'''simple docstring'''







							def __init__(  self					,     __a					,     __a=13					,     __a=10					,     __a=3					,     __a=2					,     __a=2					,     __a=True					,     __a=True					,     __a=32					,     __a=5					,     __a=4					,     __a=37					,     __a="gelu"					,     __a=0.1					,     __a=0.1					,     __a=10					,     __a=0.0_2					,     __a="divided_space_time"					,     __a=None					,     ):
										__lowerCAmelCase       					=    parent
										__lowerCAmelCase       					=    batch_size
										__lowerCAmelCase       					=    image_size
										__lowerCAmelCase       					=    num_channels
										__lowerCAmelCase       					=    patch_size
										__lowerCAmelCase       					=    num_frames
										__lowerCAmelCase       					=    is_training
										__lowerCAmelCase       					=    use_labels
										__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       					=    attention_type
										__lowerCAmelCase       					=    initializer_range
										__lowerCAmelCase       					=    scope
										__lowerCAmelCase       					=    num_labels

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

							def     snake_case       (  self			):
										__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			):
										__lowerCAmelCase       					=    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					,     )
										__lowerCAmelCase       					=    self.num_labels
										return config

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

							def     snake_case       (  self					,     __a					,     __a					,     __a			):
										__lowerCAmelCase       					=    TimesformerForVideoClassification(__a			)
										model.to(__a			)
										model.eval()

										__lowerCAmelCase       					=    model(__a			)

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



							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.prepare_config_and_inputs()
										__lowerCAmelCase					,			__lowerCAmelCase					,			__lowerCAmelCase       					=    config_and_inputs
										__lowerCAmelCase       					=    {"pixel_values": pixel_values}
										return config, inputs_dict
@require_torch
class 						_UpperCamelCase						(     lowerCAmelCase__ ,lowerCAmelCase__ ,unittest.TestCase	):
							'''simple docstring'''







							__UpperCAmelCase		:					Optional[int]          =(TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else ()
							__UpperCAmelCase		:					Tuple          =(
							    {"""feature-extraction""": TimesformerModel, """video-classification""": TimesformerForVideoClassification}
							    if is_torch_available()
							    else {}
							)

							__UpperCAmelCase		:					Any          =False
							__UpperCAmelCase		:					Optional[int]          =False
							__UpperCAmelCase		:					Union[str, Any]          =False
							__UpperCAmelCase		:					Any          =False

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    TimesformerModelTester(self			)
										__lowerCAmelCase       					=    ConfigTester(
										    self					,     config_class=__a					,     has_text_modality=__a					,     hidden_size=37			)

							def     snake_case       (  self					,     __a					,     __a					,     __a=False			):
										__lowerCAmelCase       					=    copy.deepcopy(__a			)

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

										return inputs_dict

							def     snake_case       (  self			):
										self.config_tester.run_common_tests()

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

							def     snake_case       (  self			):
										__lowerCAmelCase					,			__lowerCAmelCase       					=    self.model_tester.prepare_config_and_inputs_for_common()

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

							def     snake_case       (  self			):
										__lowerCAmelCase					,			__lowerCAmelCase       					=    self.model_tester.prepare_config_and_inputs_for_common()

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

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

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__a			)

							def     snake_case       (  self			):
										__lowerCAmelCase       					=    self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_video_classification(*__a			)

							@slow
							def     snake_case       (  self			):
										for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__lowerCAmelCase       					=    TimesformerModel.from_pretrained(__a			)
													self.assertIsNotNone(__a			)

							def     snake_case       (  self			):
										if not self.has_attentions:
													pass

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

																__lowerCAmelCase       					=    True
																__lowerCAmelCase       					=    False
																__lowerCAmelCase       					=    True
																__lowerCAmelCase       					=    model_class(__a			)
																model.to(__a			)
																model.eval()
																with torch.no_grad():
																			__lowerCAmelCase       					=    model(**self._prepare_for_class(__a					,     __a			)			)
																__lowerCAmelCase       					=    outputs.attentions
																self.assertEqual(len(__a			)					,     self.model_tester.num_hidden_layers			)

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

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

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

																__lowerCAmelCase       					=    outputs.attentions

																self.assertEqual(len(__a			)					,     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     snake_case       (  self			):
										def check_hidden_states_output(__a					,     __a					,     __a			):
													__lowerCAmelCase       					=    model_class(__a			)
													model.to(__a			)
													model.eval()

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

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

													__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(__a					,     __a					,     __a			)

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

													check_hidden_states_output(__a					,     __a					,     __a			)


def _lowerCamelCase			(	):

			'''simple docstring'''




			__lowerCAmelCase       					=    hf_hub_download(
			    repo_id="hf-internal-testing/spaghetti-video"					,				filename="eating_spaghetti.npy"					,				repo_type="dataset"   )
			__lowerCAmelCase       					=    np.load(_UpperCamelCase   )
			return list(_UpperCamelCase   )


@require_torch
@require_vision
class 						_UpperCamelCase						(     unittest.TestCase	):
							'''simple docstring'''







							@cached_property
							def     snake_case       (  self			):
										# 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     snake_case       (  self			):
										__lowerCAmelCase       					=    TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400"			).to(
										    __a			)

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

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

										# verify the logits
										__lowerCAmelCase       					=    torch.Size((1, 4_00)			)
										self.assertEqual(outputs.logits.shape					,     __a			)

										__lowerCAmelCase       					=    torch.tensor([-0.3_0_1_6, -0.7_7_1_3, -0.4_2_0_5]			).to(__a			)

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




