


import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


__lowercase											=      random.Random()

if is_torch_available():
    import torch



def lowerCamelCase						(     SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE=1.0						,    SCREAMING_SNAKE_CASE=None						,    SCREAMING_SNAKE_CASE=None			):
    '''simple docstring'''







    if rng is None:
        __UpperCamelCase  :int    						=	global_rng

    __UpperCamelCase  :List[str]    						=	[]
    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				,				__lowercase				,				__lowercase=7				,				__lowercase=400				,				__lowercase=2_000				,				__lowercase=1				,				__lowercase=0.0				,				__lowercase=16_000				,				__lowercase=True				,				__lowercase=True				,				) ->			Dict:
        __UpperCamelCase  :str    						=	parent
        __UpperCamelCase  :int    						=	batch_size
        __UpperCamelCase  :str    						=	min_seq_length
        __UpperCamelCase  :List[Any]    						=	max_seq_length
        __UpperCamelCase  :Optional[Any]    						=	(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
        __UpperCamelCase  :int    						=	feature_size
        __UpperCamelCase  :List[Any]    						=	padding_value
        __UpperCamelCase  :Dict    						=	sampling_rate
        __UpperCamelCase  :str    						=	return_attention_mask
        __UpperCamelCase  :Tuple    						=	do_normalize







    def     UpperCamelCase__     (			self) ->			Tuple:
        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     UpperCamelCase__     (			self				,				__lowercase=False				,				__lowercase=False) ->			Tuple:
        def _flatten(__lowercase):
            return list(itertools.chain(*__lowercase))

        if equal_length:
            __UpperCamelCase  :Any    						=	floats_list((self.batch_size, self.max_seq_length))
        else:
            # make sure that inputs increase in size
            __UpperCamelCase  :int    						=	[
                _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:
            __UpperCamelCase  :Dict    						=	[np.asarray(__lowercase) for x in speech_inputs]

        return speech_inputs


@require_torch
@require_torchaudio
class 			lowerCamelCase_  (     UpperCAmelCase_		,			unittest.TestCase				):






    '''simple docstring'''






    a__			:		Tuple      			=   ASTFeatureExtractor







    def     UpperCamelCase__     (			self) ->			Dict:
        __UpperCamelCase  :Dict    						=	ASTFeatureExtractionTester(self)







    def     UpperCamelCase__     (			self) ->			Any:
        # Tests that all call wrap to encode_plus and batch_encode_plus
        __UpperCamelCase  :int    						=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
        # create three inputs of length 800, 1000, and 1200
        __UpperCamelCase  :Any    						=	[floats_list((1, x))[0] for x in range(800				,				1_400				,				200)]
        __UpperCamelCase  :Optional[int]    						=	[np.asarray(__lowercase) for speech_input in speech_inputs]

        # Test not batched input
        __UpperCamelCase  :Optional[int]    						=	feat_extract(speech_inputs[0]				,				return_tensors='''np''').input_values
        __UpperCamelCase  :Union[str, Any]    						=	feat_extract(np_speech_inputs[0]				,				return_tensors='''np''').input_values
        self.assertTrue(np.allclose(__lowercase				,				__lowercase				,				atol=1E-3))

        # Test batched
        __UpperCamelCase  :Optional[int]    						=	feat_extract(__lowercase				,				padding=__lowercase				,				return_tensors='''np''').input_values
        __UpperCamelCase  :Any    						=	feat_extract(__lowercase				,				padding=__lowercase				,				return_tensors='''np''').input_values
        for enc_seq_a, enc_seq_a in zip(__lowercase				,				__lowercase):
            self.assertTrue(np.allclose(__lowercase				,				__lowercase				,				atol=1E-3))

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







    @require_torch
    def     UpperCamelCase__     (			self) ->			Any:
        import torch

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

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







    def     UpperCamelCase__     (			self				,				__lowercase) ->			Optional[Any]:
        from datasets import load_dataset

        __UpperCamelCase  :Tuple    						=	load_dataset('''hf-internal-testing/librispeech_asr_dummy'''				,				'''clean'''				,				split='''validation''')
        # automatic decoding with librispeech
        __UpperCamelCase  :Union[str, Any]    						=	ds.sort('''id''').select(range(__lowercase))[:num_samples]['''audio''']

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







    @require_torch
    def     UpperCamelCase__     (			self) ->			Dict:
        # fmt: off
        __UpperCamelCase  :Tuple    						=	torch.tensor(
            [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76,
             -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33,
             -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36,
             -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69])
        # fmt: on

        __UpperCamelCase  :int    						=	self._load_datasamples(1)
        __UpperCamelCase  :Tuple    						=	ASTFeatureExtractor()
        __UpperCamelCase  :Tuple    						=	feature_extractor(__lowercase				,				return_tensors='''pt''').input_values
        self.assertEquals(input_values.shape				,				(1, 1_024, 128))
        self.assertTrue(torch.allclose(input_values[0, 0, :30]				,				__lowercase				,				atol=1E-4))






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available


__lowercase											=      {
    '''configuration_audio_spectrogram_transformer''': [
        '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''ASTConfig''',
    ]
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowercase											=      [
        '''AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
        '''ASTForAudioClassification''',
        '''ASTModel''',
        '''ASTPreTrainedModel''',
    ]

try:
    if not is_speech_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowercase											=      ['''ASTFeatureExtractor''']

if TYPE_CHECKING:
    from .configuration_audio_spectrogram_transformer import (
        AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
        ASTConfig,
    )

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_audio_spectrogram_transformer import (
            AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
            ASTForAudioClassification,
            ASTModel,
            ASTPreTrainedModel,
        )

    try:
        if not is_speech_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor


else:
    import sys

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





