





"""simple docstring"""



import itertools
import random
import unittest

import numpy as np

from transformers import is_speech_available
from transformers.testing_utils import require_torch, require_torchaudio

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
       from transformers import SpeechaTextFeatureExtractor

a_			=      random.Random()







def 		__lowercase					(       snake_case_  :  Dict    ,snake_case_  :  List[Any]=1.0    ,snake_case_  :  Tuple=None    ,snake_case_  :  List[Any]=None						)       ->Union[str, Any]:



    '''simple docstring'''







    if rng is None:
        __A   :						Tuple									=					global_rng

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

    return values






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





 """simple docstring"""


 def __init__(   self ,						__lowerCamelCase ,						__lowerCamelCase=7 ,						__lowerCamelCase=400 ,						__lowerCamelCase=2000 ,						__lowerCamelCase=24 ,						__lowerCamelCase=24 ,						__lowerCamelCase=0.0 ,						__lowerCamelCase=1_6000 ,						__lowerCamelCase=True ,						__lowerCamelCase=True ,						):



     '''simple docstring'''




     __A   :						Tuple									=					parent
     __A   :						Union[str, Any]									=					batch_size
     __A   :						Optional[Any]									=					min_seq_length
     __A   :						Any									=					max_seq_length
     __A   :						List[str]									=					(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
     __A   :						Optional[int]									=					feature_size
     __A   :						str									=					num_mel_bins
     __A   :						str									=					padding_value
     __A   :						Any									=					sampling_rate
     __A   :						int									=					return_attention_mask
     __A   :						Optional[int]									=					do_normalize

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




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







 def  UpperCamelCase__(   self ,						__lowerCamelCase=False ,						__lowerCamelCase=False  ):



     '''simple docstring'''




     def _flatten(__lowerCamelCase  ):
         return list(itertools.chain(*__lowerCamelCase  )  )

     if equal_length:
         __A   :						Optional[Any]									=					[floats_list((self.max_seq_length, self.feature_size)  ) for _ in range(self.batch_size  )]
     else:
         # make sure that inputs increase in size
         __A   :						str									=					[
             floats_list((x, self.feature_size)  )
             for x in range(self.min_seq_length ,						self.max_seq_length ,						self.seq_length_diff  )
         ]
     if numpify:
         __A   :						Optional[Any]									=					[np.asarray(__lowerCamelCase  ) for x in speech_inputs]
     return speech_inputs






@require_torch
@require_torchaudio
class 		__snake_case (		SCREAMING_SNAKE_CASE__							,							unittest.TestCase					):





 """simple docstring"""


 _lowerCamelCase				=					SpeechaTextFeatureExtractor if is_speech_available() else None

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[Any]									=					SpeechaTextFeatureExtractionTester(self  )

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




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

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						str									=					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     # create three inputs of length 800, 1000, and 1200
     __A   :						Tuple									=					[floats_list((1, x)  )[0] for x in range(800 ,						1400 ,						200  )]
     __A   :						int									=					[np.asarray(__lowerCamelCase  ) for speech_input in speech_inputs]

     # Test feature size
     __A   :						str									=					feature_extractor(__lowerCamelCase ,						padding=__lowerCamelCase ,						return_tensors='''np'''  ).input_features
     self.assertTrue(input_features.ndim == 3  )
     self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size  )

     # Test not batched input
     __A   :						str									=					feature_extractor(speech_inputs[0] ,						return_tensors='''np'''  ).input_features
     __A   :						List[Any]									=					feature_extractor(np_speech_inputs[0] ,						return_tensors='''np'''  ).input_features
     self.assertTrue(np.allclose(__lowerCamelCase ,						__lowerCamelCase ,						atol=1e-3  )  )

     # Test batched
     __A   :						Optional[Any]									=					feature_extractor(__lowerCamelCase ,						return_tensors='''np'''  ).input_features
     __A   :						Tuple									=					feature_extractor(__lowerCamelCase ,						return_tensors='''np'''  ).input_features
     for enc_seq_a, enc_seq_a in zip(__lowerCamelCase ,						__lowerCamelCase  ):
         self.assertTrue(np.allclose(__lowerCamelCase ,						__lowerCamelCase ,						atol=1e-3  )  )

     # Test 2-D numpy arrays are batched.
     __A   :						Union[str, Any]									=					[floats_list((1, x)  )[0] for x in (800, 800, 800)]
     __A   :						List[Any]									=					np.asarray(__lowerCamelCase  )
     __A   :						Union[str, Any]									=					feature_extractor(__lowerCamelCase ,						return_tensors='''np'''  ).input_features
     __A   :						Union[str, Any]									=					feature_extractor(__lowerCamelCase ,						return_tensors='''np'''  ).input_features
     for enc_seq_a, enc_seq_a in zip(__lowerCamelCase ,						__lowerCamelCase  ):
         self.assertTrue(np.allclose(__lowerCamelCase ,						__lowerCamelCase ,						atol=1e-3  )  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Tuple									=					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     __A   :						Optional[int]									=					[floats_list((1, x)  )[0] for x in range(800 ,						1400 ,						200  )]

     __A   :						Any									=					['''longest''', '''max_length''', '''do_not_pad''']
     __A   :						Optional[Any]									=					[None, 16, None]
     for max_length, padding in zip(__lowerCamelCase ,						__lowerCamelCase  ):
         __A   :						Dict									=					feature_extractor(
             __lowerCamelCase ,						padding=__lowerCamelCase ,						max_length=__lowerCamelCase ,						return_attention_mask=__lowerCamelCase  )
         __A   :						Dict									=					inputs.input_features
         __A   :						List[str]									=					inputs.attention_mask
         __A   :						Any									=					[np.sum(__lowerCamelCase  ) for x in attention_mask]

         self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]  )
         self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]  )
         self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[str]									=					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     __A   :						Dict									=					[floats_list((1, x)  )[0] for x in range(800 ,						1400 ,						200  )]

     __A   :						Optional[Any]									=					['''longest''', '''max_length''', '''do_not_pad''']
     __A   :						str									=					[None, 16, None]
     for max_length, padding in zip(__lowerCamelCase ,						__lowerCamelCase  ):
         __A   :						Union[str, Any]									=					feature_extractor(
             __lowerCamelCase ,						max_length=__lowerCamelCase ,						padding=__lowerCamelCase ,						return_tensors='''np''' ,						return_attention_mask=__lowerCamelCase  )
         __A   :						str									=					inputs.input_features
         __A   :						List[Any]									=					inputs.attention_mask
         __A   :						Dict									=					[np.sum(__lowerCamelCase  ) for x in attention_mask]

         self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]  )
         self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6  )
         self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]  )
         self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6  )
         self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[str]									=					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     __A   :						Optional[int]									=					[floats_list((1, x)  )[0] for x in range(800 ,						1400 ,						200  )]
     __A   :						Optional[int]									=					feature_extractor(
         __lowerCamelCase ,						padding='''max_length''' ,						max_length=4 ,						truncation=__lowerCamelCase ,						return_tensors='''np''' ,						return_attention_mask=__lowerCamelCase ,						)
     __A   :						List[Any]									=					inputs.input_features
     __A   :						Optional[int]									=					inputs.attention_mask
     __A   :						List[str]									=					np.sum(attention_mask == 1 ,						axis=1  )

     self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]  )
     self._check_zero_mean_unit_variance(input_features[1]  )
     self._check_zero_mean_unit_variance(input_features[2]  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						int									=					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     __A   :						Tuple									=					[floats_list((1, x)  )[0] for x in range(800 ,						1400 ,						200  )]
     __A   :						Any									=					feature_extractor(
         __lowerCamelCase ,						padding='''longest''' ,						max_length=4 ,						truncation=__lowerCamelCase ,						return_tensors='''np''' ,						return_attention_mask=__lowerCamelCase ,						)
     __A   :						Optional[int]									=					inputs.input_features
     __A   :						List[Any]									=					inputs.attention_mask
     __A   :						Optional[Any]									=					np.sum(attention_mask == 1 ,						axis=1  )

     self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]  )
     self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]  )
     self._check_zero_mean_unit_variance(input_features[2]  )

     # make sure that if max_length < longest -> then pad to max_length
     self.assertEqual(input_features.shape ,						(3, 4, 24)  )

     __A   :						Optional[Any]									=					[floats_list((1, x)  )[0] for x in range(800 ,						1400 ,						200  )]
     __A   :						Tuple									=					feature_extractor(
         __lowerCamelCase ,						padding='''longest''' ,						max_length=16 ,						truncation=__lowerCamelCase ,						return_tensors='''np''' ,						return_attention_mask=__lowerCamelCase ,						)
     __A   :						Union[str, Any]									=					inputs.input_features
     __A   :						List[str]									=					inputs.attention_mask
     __A   :						Optional[Any]									=					np.sum(attention_mask == 1 ,						axis=1  )

     self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]  )
     self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]  )
     self._check_zero_mean_unit_variance(input_features[2]  )

     # make sure that if max_length < longest -> then pad to max_length
     self.assertEqual(input_features.shape ,						(3, 6, 24)  )

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     import torch

     __A   :						Optional[int]									=					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     __A   :						Optional[int]									=					np.random.rand(100 ,						32  ).astype(np.floataa  )
     __A   :						Union[str, Any]									=					np_speech_inputs.tolist()

     for inputs in [py_speech_inputs, np_speech_inputs]:
         __A   :						Tuple									=					feature_extractor.pad([{'''input_features''': inputs}] ,						return_tensors='''np'''  )
         self.assertTrue(np_processed.input_features.dtype == np.floataa  )
         __A   :						Optional[Any]									=					feature_extractor.pad([{'''input_features''': inputs}] ,						return_tensors='''pt'''  )
         self.assertTrue(pt_processed.input_features.dtype == torch.floataa  )

 def  UpperCamelCase__(   self ,						__lowerCamelCase  ):



     '''simple docstring'''




     from datasets import load_dataset

     __A   :						Optional[int]									=					load_dataset('''hf-internal-testing/librispeech_asr_dummy''' ,						'''clean''' ,						split='''validation'''  )
     # automatic decoding with librispeech
     __A   :						Optional[int]									=					ds.sort('''id'''  ).select(range(__lowerCamelCase  )  )[:num_samples]['''audio''']

     return [x["array"] for x in speech_samples]







 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Optional[Any]									=					np.array([
         -1.5_7_4_5, -1.7_7_1_3, -1.7_0_2_0, -1.6_0_6_9, -1.2_2_5_0, -1.1_1_0_5, -0.9_0_7_2, -0.8_2_4_1,
         -1.2_3_1_0, -0.8_0_9_8, -0.3_3_2_0, -0.4_1_0_1, -0.7_9_8_5, -0.4_9_9_6, -0.8_2_1_3, -0.9_1_2_8,
         -1.0_4_2_0, -1.1_2_8_6, -1.0_4_4_0, -0.7_9_9_9, -0.8_4_0_5, -1.2_2_7_5, -1.5_4_4_3, -1.4_6_2_5,
     ]  )
     # fmt: on

     __A   :						Dict									=					self._load_datasamples(1  )
     __A   :						str									=					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
     __A   :						Dict									=					feature_extractor(__lowerCamelCase ,						return_tensors='''pt'''  ).input_features
     self.assertEquals(input_features.shape ,						(1, 584, 24)  )
     self.assertTrue(np.allclose(input_features[0, 0, :30] ,						__lowerCamelCase ,						atol=1e-4  )  )











"""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


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


try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       a_			=      [
           """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

       a_			=      _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




