





import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_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 ASTForAudioClassification, ASTModel
      from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
          AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
      )


if is_torchaudio_available():
      import torchaudio

      from transformers import ASTFeatureExtractor







class    __snake_case	:





       '''simple docstring'''







       def __init__(  self			:   Tuple							,    A			:   int							,    A			:   Union[str, Any]=13							,    A			:   Any=2							,    A			:   List[Any]=24							,    A			:   int=16							,    A			:   Dict=True							,    A			:   Tuple=True							,    A			:   Tuple=32							,    A			:   Optional[int]=5							,    A			:   Optional[int]=4							,    A			:   List[str]=37							,    A			:   Any="gelu"							,    A			:   Optional[Any]=0.1							,    A			:   List[str]=0.1							,    A			:   str=10							,    A			:   Optional[Any]=0.02							,    A			:   List[Any]=None							,    A			:   int=2							,    A			:   Optional[Any]=2							,    ):
         __snake_case:						Dict			  =						parent
         __snake_case:						str			  =						batch_size
         __snake_case:						Optional[int]			  =						patch_size
         __snake_case:						Optional[int]			  =						max_length
         __snake_case:						List[str]			  =						num_mel_bins
         __snake_case:						List[Any]			  =						is_training
         __snake_case:						Any			  =						use_labels
         __snake_case:						Dict			  =						hidden_size
         __snake_case:						str			  =						num_hidden_layers
         __snake_case:						Union[str, Any]			  =						num_attention_heads
         __snake_case:						Optional[int]			  =						intermediate_size
         __snake_case:						Any			  =						hidden_act
         __snake_case:						Any			  =						hidden_dropout_prob
         __snake_case:						Any			  =						attention_probs_dropout_prob
         __snake_case:						List[Any]			  =						type_sequence_label_size
         __snake_case:						List[str]			  =						initializer_range
         __snake_case:						int			  =						scope
         __snake_case:						str			  =						frequency_stride
         __snake_case:						Any			  =						time_stride

         # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
         __snake_case:						Optional[int]			  =						(self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
         __snake_case:						str			  =						(self.max_length - self.patch_size) // self.time_stride + 1
         __snake_case:						Optional[Any]			  =						frequency_out_dimension * time_out_dimension
         __snake_case:						int			  =						num_patches + 2




       def 							UpperCAmelCase__			(  self			:   str		):
         __snake_case:						Dict			  =						floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]		)

         __snake_case:						Optional[Any]			  =						None
         if self.use_labels:
           __snake_case:						Optional[int]			  =						ids_tensor([self.batch_size]							,    self.type_sequence_label_size		)

         __snake_case:						int			  =						self.get_config()

         return config, input_values, labels




       def 							UpperCAmelCase__			(  self			:   int		):
         return ASTConfig(
             patch_size=self.patch_size							,    max_length=self.max_length							,    num_mel_bins=self.num_mel_bins							,    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							,    is_decoder=A							,    initializer_range=self.initializer_range							,    frequency_stride=self.frequency_stride							,    time_stride=self.time_stride							,    )




       def 							UpperCAmelCase__			(  self			:   List[str]							,    A			:   Optional[Any]							,    A			:   Optional[Any]							,    A			:   List[Any]		):
         __snake_case:						Union[str, Any]			  =						ASTModel(config=A		)
         model.to(A		)
         model.eval()
         __snake_case:						Optional[int]			  =						model(A		)
         self.parent.assertEqual(result.last_hidden_state.shape							,    (self.batch_size, self.seq_length, self.hidden_size)		)






       def 							UpperCAmelCase__			(  self			:   Any		):
         __snake_case:						Union[str, Any]			  =						self.prepare_config_and_inputs()
         (
             (
             __snake_case
         )  ,       (
             __snake_case
         )  ,       (
             __snake_case
         )  ,       
         ):						Tuple			  =						config_and_inputs
         __snake_case:						Optional[Any]			  =						{"""input_values""": input_values}
         return config, inputs_dict







@require_torch
class    __snake_case	(							__lowerCamelCase       ,      __lowerCamelCase       ,      unittest.TestCase      ):





       '''simple docstring'''







       lowerCAmelCase__						=					(
           (
               ASTModel,
               ASTForAudioClassification,
           )
           if is_torch_available()
           else ()
       )
       lowerCAmelCase__						=					(
           {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
           if is_torch_available()
           else {}
       )
       lowerCAmelCase__						=					False
       lowerCAmelCase__						=					False
       lowerCAmelCase__						=					False
       lowerCAmelCase__						=					False




       def 							UpperCAmelCase__			(  self			:   int							,    A			:   Union[str, Any]							,    A			:   Optional[Any]							,    A			:   Tuple							,    A			:   Any							,    A			:   Optional[int]		):
         if pipeline_test_casse_name == "AudioClassificationPipelineTests":
           return True

         return False




       def 							UpperCAmelCase__			(  self			:   Union[str, Any]		):
         __snake_case:						Tuple			  =						ASTModelTester(self		)
         __snake_case:						str			  =						ConfigTester(self							,    config_class=A							,    has_text_modality=A							,    hidden_size=37		)




       def 							UpperCAmelCase__			(  self			:   List[str]		):
         self.config_tester.run_common_tests()




       @unittest.skip(reason="""AST does not use inputs_embeds"""		)
       def 							UpperCAmelCase__			(  self			:   Tuple		):
         pass




       def 							UpperCAmelCase__			(  self			:   Optional[int]		):
         __snake_case  ,       __snake_case:						int			  =						self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           __snake_case:						Any			  =						model_class(A		)
           self.assertIsInstance(model.get_input_embeddings()							,    (nn.Module)		)
           __snake_case:						Union[str, Any]			  =						model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(A							,    nn.Linear		)		)




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case  ,       __snake_case:						List[str]			  =						self.model_tester.prepare_config_and_inputs_for_common()

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

           __snake_case:						Union[str, Any]			  =						["""input_values"""]
           self.assertListEqual(arg_names[:1]							,    A		)




       def 							UpperCAmelCase__			(  self			:   List[str]		):
         __snake_case:						Any			  =						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*A		)






       @slow
       def 							UpperCAmelCase__			(  self			:   Union[str, Any]		):
         for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __snake_case:						int			  =						ASTModel.from_pretrained(A		)
           self.assertIsNotNone(A		)







def       A__							(   )       ->   Optional[Any]:
  __snake_case:						Union[str, Any]			  =						hf_hub_download(
      repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" , filename="""sample_audio.flac""" , repo_type="""dataset""")

  __snake_case  ,       __snake_case:						Union[str, Any]			  =						torchaudio.load(SCREAMING_SNAKE_CASE__)

  return audio, sampling_rate







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





       '''simple docstring'''







       @cached_property
       def 							UpperCAmelCase__			(  self			:   int		):
         return (
             ASTFeatureExtractor.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""		)
             if is_torchaudio_available()
             else None
         )






       @slow
       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         __snake_case:						List[str]			  =						self.default_feature_extractor
         __snake_case:						int			  =						ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""		).to(A		)

         __snake_case:						List[str]			  =						self.default_feature_extractor
         __snake_case  ,       __snake_case:						List[Any]			  =						prepare_audio()
         __snake_case:						str			  =						audio.squeeze().numpy()
         __snake_case:						int			  =						feature_extractor(A							,    sampling_rate=A							,    return_tensors="""pt"""		).to(A		)

         # forward pass
         with torch.no_grad():
           __snake_case:						Tuple			  =						model(**A		)

         # verify the logits
         __snake_case:						Optional[Any]			  =						torch.Size((1, 527)		)
         self.assertEqual(outputs.logits.shape							,    A		)

         __snake_case:						List[Any]			  =						torch.tensor([-0.8760, -7.0042, -8.6602]		).to(A		)

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













import itertools
import os
import random
import tempfile
import unittest

import numpy as np

from transformers import TvltFeatureExtractor, is_datasets_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
      import torch

if is_datasets_available():
      from datasets import load_dataset

__UpperCAmelCase	:       Any    	=							random.Random()







def       A__							(   SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=1.0 , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None)       ->   Any:
  if rng is None:
    __snake_case:						Dict			  =						global_rng

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

  return values







class    __snake_case	(							unittest.TestCase      ):





       '''simple docstring'''







       def __init__(  self			:   int							,    A			:   List[str]							,    A			:   List[Any]=7							,    A			:   Optional[int]=400							,    A			:   List[Any]=2_000							,    A			:   Dict=2_048							,    A			:   Tuple=128							,    A			:   List[Any]=1							,    A			:   Tuple=512							,    A			:   str=30							,    A			:   Optional[Any]=44_100							,    ):
         __snake_case:						Dict			  =						parent
         __snake_case:						Optional[Any]			  =						batch_size
         __snake_case:						Optional[int]			  =						min_seq_length
         __snake_case:						Optional[Any]			  =						max_seq_length
         __snake_case:						List[str]			  =						(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
         __snake_case:						Any			  =						spectrogram_length
         __snake_case:						Any			  =						feature_size
         __snake_case:						Union[str, Any]			  =						num_audio_channels
         __snake_case:						Any			  =						hop_length
         __snake_case:						List[str]			  =						chunk_length
         __snake_case:						Any			  =						sampling_rate




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         return {
             "spectrogram_length": self.spectrogram_length,
             "feature_size": self.feature_size,
             "num_audio_channels": self.num_audio_channels,
             "hop_length": self.hop_length,
             "chunk_length": self.chunk_length,
             "sampling_rate": self.sampling_rate,
         }






       def 							UpperCAmelCase__			(  self			:   List[str]							,    A			:   str=False							,    A			:   int=False		):
         def _flatten(A			:   Dict		):
           return list(itertools.chain(*A		)		)

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







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





       '''simple docstring'''







       lowerCAmelCase__						=					TvltFeatureExtractor




       def 							UpperCAmelCase__			(  self			:   Union[str, Any]		):
         __snake_case:						str			  =						TvltFeatureExtractionTester(self		)




       def 							UpperCAmelCase__			(  self			:   int		):
         __snake_case:						Tuple			  =						self.feature_extraction_class(**self.feat_extract_dict		)
         self.assertTrue(hasattr(A							,    """spectrogram_length"""		)		)
         self.assertTrue(hasattr(A							,    """feature_size"""		)		)
         self.assertTrue(hasattr(A							,    """num_audio_channels"""		)		)
         self.assertTrue(hasattr(A							,    """hop_length"""		)		)
         self.assertTrue(hasattr(A							,    """chunk_length"""		)		)
         self.assertTrue(hasattr(A							,    """sampling_rate"""		)		)




       def 							UpperCAmelCase__			(  self			:   Any		):
         __snake_case:						Optional[Any]			  =						self.feature_extraction_class(**self.feat_extract_dict		)

         with tempfile.TemporaryDirectory() as tmpdirname:
           __snake_case:						Tuple			  =						feat_extract_first.save_pretrained(A		)[0]
           check_json_file_has_correct_format(A		)
           __snake_case:						int			  =						self.feature_extraction_class.from_pretrained(A		)

         __snake_case:						List[str]			  =						feat_extract_first.to_dict()
         __snake_case:						str			  =						feat_extract_second.to_dict()
         __snake_case:						List[Any]			  =						dict_first.pop("""mel_filters"""		)
         __snake_case:						str			  =						dict_second.pop("""mel_filters"""		)
         self.assertTrue(np.allclose(A							,    A		)		)
         self.assertEqual(A							,    A		)




       def 							UpperCAmelCase__			(  self			:   Optional[Any]		):
         __snake_case:						str			  =						self.feature_extraction_class(**self.feat_extract_dict		)

         with tempfile.TemporaryDirectory() as tmpdirname:
           __snake_case:						str			  =						os.path.join(A							,    """feat_extract.json"""		)
           feat_extract_first.to_json_file(A		)
           __snake_case:						List[Any]			  =						self.feature_extraction_class.from_json_file(A		)

         __snake_case:						Dict			  =						feat_extract_first.to_dict()
         __snake_case:						Any			  =						feat_extract_second.to_dict()
         __snake_case:						int			  =						dict_first.pop("""mel_filters"""		)
         __snake_case:						int			  =						dict_second.pop("""mel_filters"""		)
         self.assertTrue(np.allclose(A							,    A		)		)
         self.assertEqual(A							,    A		)




       def 							UpperCAmelCase__			(  self			:   Any		):
         # Initialize feature_extractor
         __snake_case:						Union[str, Any]			  =						self.feature_extraction_class(**self.feat_extract_dict		)

         # create three inputs of length 800, 1000, and 1200
         __snake_case:						Dict			  =						[floats_list((1, x)		)[0] for x in range(800							,    1_400							,    200		)]
         __snake_case:						str			  =						[np.asarray(A		) for speech_input in speech_inputs]

         # Test not batched input
         __snake_case:						int			  =						feature_extractor(np_speech_inputs[0]							,    return_tensors="""np"""							,    sampling_rate=44_100		).audio_values

         self.assertTrue(encoded_audios.ndim == 4		)
         self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
         self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
         self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)

         # Test batched
         __snake_case:						Optional[int]			  =						feature_extractor(A							,    return_tensors="""np"""							,    sampling_rate=44_100		).audio_values

         self.assertTrue(encoded_audios.ndim == 4		)
         self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
         self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
         self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)

         # Test audio masking
         __snake_case:						Union[str, Any]			  =						feature_extractor(
             A							,    return_tensors="""np"""							,    sampling_rate=44_100							,    mask_audio=A		).audio_values

         self.assertTrue(encoded_audios.ndim == 4		)
         self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
         self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
         self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)

         # Test 2-D numpy arrays are batched.
         __snake_case:						Any			  =						[floats_list((1, x)		)[0] for x in (800, 800, 800)]
         __snake_case:						Union[str, Any]			  =						np.asarray(A		)
         __snake_case:						List[Any]			  =						feature_extractor(A							,    return_tensors="""np"""							,    sampling_rate=44_100		).audio_values
         self.assertTrue(encoded_audios.ndim == 4		)
         self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
         self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
         self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)




       def 							UpperCAmelCase__			(  self			:   Union[str, Any]							,    A			:   List[str]		):
         __snake_case:						Tuple			  =						load_dataset("""hf-internal-testing/librispeech_asr_dummy"""							,    """clean"""							,    split="""validation"""		)
         # automatic decoding with librispeech
         __snake_case:						List[Any]			  =						ds.sort("""id"""		).select(range(A		)		)[:num_samples]["""audio"""]

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






       def 							UpperCAmelCase__			(  self			:   Optional[int]		):
         __snake_case:						Dict			  =						self._load_datasamples(1		)
         __snake_case:						Optional[int]			  =						TvltFeatureExtractor()
         __snake_case:						Optional[Any]			  =						feature_extractor(A							,    return_tensors="""pt"""		).audio_values

         self.assertEquals(audio_values.shape							,    (1, 1, 192, 128)		)

         __snake_case:						str			  =						torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]]		)
         self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]							,    A							,    atol=1E-4		)		)






