
"""simple docstring"""




import itertools
import random
import unittest

import numpy as np

from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor
from transformers.testing_utils import require_torch, slow

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


UpperCAmelCase__      :    Union[str, Any]    							= random.Random()

def lowercase_  (   _snake_case   ,_snake_case=1.0   ,_snake_case=None   ,_snake_case=None						):
							if rng is None:
														SCREAMING_SNAKE_CASE__						:       str           =   global_rng

							SCREAMING_SNAKE_CASE__						:       Optional[int]           =   []
							for batch_idx in range(shape[0]						):
														values.append([]						)
														for _ in range(shape[1]						):
																					values[-1].append(rng.random() * scale						)

							return values



class 	lowerCAmelCase_						(unittest.TestCase  ):


				"""simple docstring"""



				def __init__(self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__=7   ,       SCREAMING_SNAKE_CASE__=4_00   ,       SCREAMING_SNAKE_CASE__=20_00   ,       SCREAMING_SNAKE_CASE__=1   ,       SCREAMING_SNAKE_CASE__=0.0   ,       SCREAMING_SNAKE_CASE__=1_60_00   ,       SCREAMING_SNAKE_CASE__=True   ,       SCREAMING_SNAKE_CASE__=True   ,       )					->		Any:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   parent
											SCREAMING_SNAKE_CASE__						:       Tuple           =   batch_size
											SCREAMING_SNAKE_CASE__						:       str           =   min_seq_length
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   max_seq_length
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
											SCREAMING_SNAKE_CASE__						:       Dict           =   feature_size
											SCREAMING_SNAKE_CASE__						:       Any           =   padding_value
											SCREAMING_SNAKE_CASE__						:       int           =   sampling_rate
											SCREAMING_SNAKE_CASE__						:       str           =   return_attention_mask
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   do_normalize



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



											"""simple docstring"""




											return {
											    "feature_size": self.feature_size,
											    "padding_value": self.padding_value,
											    "sampling_rate": self.sampling_rate,
											    "return_attention_mask": self.return_attention_mask,
											    "do_normalize": self.do_normalize,
											}



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__=False   ,       SCREAMING_SNAKE_CASE__=False    )					->		Union[str, Any]:



											"""simple docstring"""




											def _flatten(SCREAMING_SNAKE_CASE__    ):
																		return list(itertools.chain(*_A    )    )

											if equal_length:
																		SCREAMING_SNAKE_CASE__						:       List[str]           =   floats_list((self.batch_size, self.max_seq_length)    )
											else:
																		# make sure that inputs increase in size
																		SCREAMING_SNAKE_CASE__						:       Any           =   [
																		    _flatten(floats_list((x, self.feature_size)    )    )
																		    for x in range(self.min_seq_length   ,       self.max_seq_length   ,       self.seq_length_diff    )
																		]

											if numpify:
																		SCREAMING_SNAKE_CASE__						:       List[str]           =   [np.asarray(_A    ) for x in speech_inputs]

											return speech_inputs






class 	lowerCAmelCase_						(__a ,					unittest.TestCase  ):


				"""simple docstring"""



				__UpperCamelCase      :						Tuple					       =   WavaVecaFeatureExtractor



				def 	__magic_name__    (self    )					->		Any:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   WavaVecaFeatureExtractionTester(self    )



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__    )					->		str:



											"""simple docstring"""




											self.assertTrue(np.all(np.mean(_A   ,       axis=0    ) < 1E-3    )    )
											self.assertTrue(np.all(np.abs(np.var(_A   ,       axis=0    ) - 1    ) < 1E-3    )    )



				def 	__magic_name__    (self    )					->		str:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
											# create three inputs of length 800, 1000, and 1200
											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   [floats_list((1, x)    )[0] for x in range(8_00   ,       14_00   ,       2_00    )]
											SCREAMING_SNAKE_CASE__						:       Any           =   [np.asarray(_A    ) for speech_input in speech_inputs]

											# Test not batched input
											SCREAMING_SNAKE_CASE__						:       List[Any]           =   feat_extract(speech_inputs[0]   ,       return_tensors="""np"""    ).input_values
											SCREAMING_SNAKE_CASE__						:       Any           =   feat_extract(np_speech_inputs[0]   ,       return_tensors="""np"""    ).input_values
											self.assertTrue(np.allclose(_A   ,       _A   ,       atol=1E-3    )    )

											# Test batched
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   feat_extract(_A   ,       return_tensors="""np"""    ).input_values
											SCREAMING_SNAKE_CASE__						:       Dict           =   feat_extract(_A   ,       return_tensors="""np"""    ).input_values
											for enc_seq_a, enc_seq_a in zip(_A   ,       _A    ):
																		self.assertTrue(np.allclose(_A   ,       _A   ,       atol=1E-3    )    )

											# Test 2-D numpy arrays are batched.
											SCREAMING_SNAKE_CASE__						:       str           =   [floats_list((1, x)    )[0] for x in (8_00, 8_00, 8_00)]
											SCREAMING_SNAKE_CASE__						:       int           =   np.asarray(_A    )
											SCREAMING_SNAKE_CASE__						:       str           =   feat_extract(_A   ,       return_tensors="""np"""    ).input_values
											SCREAMING_SNAKE_CASE__						:       List[str]           =   feat_extract(_A   ,       return_tensors="""np"""    ).input_values
											for enc_seq_a, enc_seq_a in zip(_A   ,       _A    ):
																		self.assertTrue(np.allclose(_A   ,       _A   ,       atol=1E-3    )    )



				def 	__magic_name__    (self    )					->		str:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Dict           =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
											SCREAMING_SNAKE_CASE__						:       int           =   [floats_list((1, x)    )[0] for x in range(8_00   ,       14_00   ,       2_00    )]

											SCREAMING_SNAKE_CASE__						:       str           =   ['''longest''', '''max_length''', '''do_not_pad''']
											SCREAMING_SNAKE_CASE__						:       str           =   [None, 16_00, None]
											for max_length, padding in zip(_A   ,       _A    ):
																		SCREAMING_SNAKE_CASE__						:       Any           =   feat_extract(_A   ,       padding=_A   ,       max_length=_A   ,       return_tensors="""np"""    )
																		SCREAMING_SNAKE_CASE__						:       Optional[int]           =   processed.input_values

																		self._check_zero_mean_unit_variance(input_values[0][:8_00]    )
																		self.assertTrue(input_values[0][8_00:].sum() < 1E-6    )
																		self._check_zero_mean_unit_variance(input_values[1][:10_00]    )
																		self.assertTrue(input_values[0][10_00:].sum() < 1E-6    )
																		self._check_zero_mean_unit_variance(input_values[2][:12_00]    )



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



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Dict           =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
											SCREAMING_SNAKE_CASE__						:       Tuple           =   range(8_00   ,       14_00   ,       2_00    )
											SCREAMING_SNAKE_CASE__						:       Tuple           =   [floats_list((1, x)    )[0] for x in lengths]

											SCREAMING_SNAKE_CASE__						:       Any           =   ['''longest''', '''max_length''', '''do_not_pad''']
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   [None, 16_00, None]

											for max_length, padding in zip(_A   ,       _A    ):
																		SCREAMING_SNAKE_CASE__						:       List[Any]           =   feat_extract(_A   ,       max_length=_A   ,       padding=_A    )
																		SCREAMING_SNAKE_CASE__						:       Any           =   processed.input_values

																		self._check_zero_mean_unit_variance(input_values[0][:8_00]    )
																		self._check_zero_mean_unit_variance(input_values[1][:10_00]    )
																		self._check_zero_mean_unit_variance(input_values[2][:12_00]    )



				def 	__magic_name__    (self    )					->		Any:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
											SCREAMING_SNAKE_CASE__						:       Any           =   [floats_list((1, x)    )[0] for x in range(8_00   ,       14_00   ,       2_00    )]
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   feat_extract(
											    _A   ,       truncation=_A   ,       max_length=10_00   ,       padding="""max_length"""   ,       return_tensors="""np"""    )
											SCREAMING_SNAKE_CASE__						:       str           =   processed.input_values

											self._check_zero_mean_unit_variance(input_values[0, :8_00]    )
											self._check_zero_mean_unit_variance(input_values[1]    )
											self._check_zero_mean_unit_variance(input_values[2]    )



				def 	__magic_name__    (self    )					->		str:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       List[str]           =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
											SCREAMING_SNAKE_CASE__						:       List[Any]           =   [floats_list((1, x)    )[0] for x in range(8_00   ,       14_00   ,       2_00    )]
											SCREAMING_SNAKE_CASE__						:       Dict           =   feat_extract(
											    _A   ,       truncation=_A   ,       max_length=10_00   ,       padding="""longest"""   ,       return_tensors="""np"""    )
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   processed.input_values

											self._check_zero_mean_unit_variance(input_values[0, :8_00]    )
											self._check_zero_mean_unit_variance(input_values[1, :10_00]    )
											self._check_zero_mean_unit_variance(input_values[2]    )

											# make sure that if max_length < longest -> then pad to max_length
											self.assertTrue(input_values.shape == (3, 10_00)    )

											SCREAMING_SNAKE_CASE__						:       List[Any]           =   [floats_list((1, x)    )[0] for x in range(8_00   ,       14_00   ,       2_00    )]
											SCREAMING_SNAKE_CASE__						:       Tuple           =   feat_extract(
											    _A   ,       truncation=_A   ,       max_length=20_00   ,       padding="""longest"""   ,       return_tensors="""np"""    )
											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   processed.input_values

											self._check_zero_mean_unit_variance(input_values[0, :8_00]    )
											self._check_zero_mean_unit_variance(input_values[1, :10_00]    )
											self._check_zero_mean_unit_variance(input_values[2]    )

											# make sure that if max_length > longest -> then pad to longest
											self.assertTrue(input_values.shape == (3, 12_00)    )



				@require_torch
				def 	__magic_name__    (self    )					->		Optional[Any]:



											"""simple docstring"""




											import torch

											SCREAMING_SNAKE_CASE__						:       int           =   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
											SCREAMING_SNAKE_CASE__						:       List[Any]           =   np.random.rand(1_00    ).astype(np.floataa    )
											SCREAMING_SNAKE_CASE__						:       Dict           =   np_speech_inputs.tolist()

											for inputs in [py_speech_inputs, np_speech_inputs]:
																		SCREAMING_SNAKE_CASE__						:       int           =   feature_extractor.pad([{"""input_values""": inputs}]   ,       return_tensors="""np"""    )
																		self.assertTrue(np_processed.input_values.dtype == np.floataa    )
																		SCREAMING_SNAKE_CASE__						:       List[str]           =   feature_extractor.pad([{"""input_values""": inputs}]   ,       return_tensors="""pt"""    )
																		self.assertTrue(pt_processed.input_values.dtype == torch.floataa    )



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



											"""simple docstring"""




											for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST:
																		SCREAMING_SNAKE_CASE__						:       Any           =   WavaVecaConfig.from_pretrained(_A    )
																		SCREAMING_SNAKE_CASE__						:       List[Any]           =   WavaVecaFeatureExtractor.from_pretrained(_A    )

																		# only "layer" feature extraction norm should make use of
																		# attention_mask
																		self.assertEqual(feat_extract.return_attention_mask   ,       config.feat_extract_norm == """layer"""    )








'''simple docstring'''
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


UpperCamelCase__    					=      {
    '''configuration_vivit''': ['''VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VivitConfig'''],
}
try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCamelCase__    					=      ['''VivitImageProcessor''']


try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCamelCase__    					=      [
      '''VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
      '''VivitModel''',
      '''VivitPreTrainedModel''',
      '''VivitForVideoClassification''',
  ]


if TYPE_CHECKING:
  from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .image_processing_vivit import VivitImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_vivit import (
        VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
        VivitForVideoClassification,
        VivitModel,
        VivitPreTrainedModel,
    )


else:
  import sys

  UpperCamelCase__    					=      _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
