
'''simple docstring'''




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 					A							:





     def __init__(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE=13		,     SCREAMING_SNAKE_CASE=2		,     SCREAMING_SNAKE_CASE=24		,     SCREAMING_SNAKE_CASE=16		,     SCREAMING_SNAKE_CASE=True		,     SCREAMING_SNAKE_CASE=True		,     SCREAMING_SNAKE_CASE=32		,     SCREAMING_SNAKE_CASE=5		,     SCREAMING_SNAKE_CASE=4		,     SCREAMING_SNAKE_CASE=37		,     SCREAMING_SNAKE_CASE="gelu"		,     SCREAMING_SNAKE_CASE=0.1		,     SCREAMING_SNAKE_CASE=0.1		,     SCREAMING_SNAKE_CASE=10		,     SCREAMING_SNAKE_CASE=0.02		,     SCREAMING_SNAKE_CASE=None		,     SCREAMING_SNAKE_CASE=2		,     SCREAMING_SNAKE_CASE=2		,     )					->							Optional[Any]:






         """simple docstring"""






         A			:  Optional[int]   =		parent
         A			:  Dict   =		batch_size
         A			:  Union[str, Any]   =		patch_size
         A			:  Optional[int]   =		max_length
         A			:  Optional[Any]   =		num_mel_bins
         A			:  Any   =		is_training
         A			:  Tuple   =		use_labels
         A			:  Any   =		hidden_size
         A			:  Optional[int]   =		num_hidden_layers
         A			:  int   =		num_attention_heads
         A			:  Optional[Any]   =		intermediate_size
         A			:  Tuple   =		hidden_act
         A			:  Any   =		hidden_dropout_prob
         A			:  Union[str, Any]   =		attention_probs_dropout_prob
         A			:  Optional[Any]   =		type_sequence_label_size
         A			:  Any   =		initializer_range
         A			:  List[Any]   =		scope
         A			:  List[str]   =		frequency_stride
         A			:  Optional[int]   =		time_stride

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





     def 							__lowerCAmelCase				(				self      )					->							List[str]:






         """simple docstring"""






         A			:  Tuple   =		floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]      )

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

         A			:  Optional[int]   =		self.get_config()

         return config, input_values, labels





     def 							__lowerCAmelCase				(				self      )					->							Tuple:






         """simple docstring"""






         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=SCREAMING_SNAKE_CASE		,     initializer_range=self.initializer_range		,     frequency_stride=self.frequency_stride		,     time_stride=self.time_stride		,     )





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )					->							Optional[Any]:






         """simple docstring"""






         A			:  str   =		ASTModel(config=SCREAMING_SNAKE_CASE      )
         model.to(SCREAMING_SNAKE_CASE      )
         model.eval()
         A			:  int   =		model(SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(result.last_hidden_state.shape		,     (self.batch_size, self.seq_length, self.hidden_size)      )





     def 							__lowerCAmelCase				(				self      )					->							List[Any]:






         """simple docstring"""






         A			:  Tuple   =		self.prepare_config_and_inputs()
         (
             (
             A
         ),    (
             A
         ),    (
             A
         ),    
         )			:  List[Any]   =		config_and_inputs
         A			:  List[Any]   =		{'''input_values''': input_values}
         return config, inputs_dict





@require_torch
class 					A							(				__snake_case       ,     __snake_case       ,     unittest.TestCase		):
     __magic_name__          =						(
         (
             ASTModel,
             ASTForAudioClassification,
         )
         if is_torch_available()
         else ()
     )
     __magic_name__          =						(
         {'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel}
         if is_torch_available()
         else {}
     )
     __magic_name__          =						False
     __magic_name__          =						False
     __magic_name__          =						False
     __magic_name__          =						False





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )					->							Optional[int]:






         """simple docstring"""






         if pipeline_test_casse_name == "AudioClassificationPipelineTests":
             return True

         return False





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






         """simple docstring"""






         A			:  Optional[int]   =		ASTModelTester(self      )
         A			:  str   =		ConfigTester(self		,     config_class=SCREAMING_SNAKE_CASE		,     has_text_modality=SCREAMING_SNAKE_CASE		,     hidden_size=37      )





     def 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         self.config_tester.run_common_tests()





     @unittest.skip(reason='''AST does not use inputs_embeds'''      )
     def 							__lowerCAmelCase				(				self      )					->							Dict:






         """simple docstring"""






         pass





     def 							__lowerCAmelCase				(				self      )					->							str:






         """simple docstring"""






         A,    A			:  Optional[Any]   =		self.model_tester.prepare_config_and_inputs_for_common()

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





     def 							__lowerCAmelCase				(				self      )					->							str:






         """simple docstring"""






         A,    A			:  Any   =		self.model_tester.prepare_config_and_inputs_for_common()

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

             A			:  Dict   =		['''input_values''']
             self.assertListEqual(arg_names[:1]		,     SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							int:






         """simple docstring"""






         A			:  Optional[Any]   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE      )





     @slow
     def 							__lowerCAmelCase				(				self      )					->							List[str]:






         """simple docstring"""






         for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             A			:  Union[str, Any]   =		ASTModel.from_pretrained(SCREAMING_SNAKE_CASE      )
             self.assertIsNotNone(SCREAMING_SNAKE_CASE      )







def 						lowerCAmelCase_							(  ):




    '''simple docstring'''



    A			:  Any   =		hf_hub_download(
        repo_id='''nielsr/audio-spectogram-transformer-checkpoint'''						,							filename='''sample_audio.flac'''						,							repo_type='''dataset'''		)

    A,    A			:  List[Any]   =		torchaudio.load(snake_case__		)

    return audio, sampling_rate







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





     @cached_property
     def 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         return (
             ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''      )
             if is_torchaudio_available()
             else None
         )





     @slow
     def 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         A			:  int   =		self.default_feature_extractor
         A			:  str   =		ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''      ).to(SCREAMING_SNAKE_CASE      )

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

         # forward pass
         with torch.no_grad():
             A			:  List[str]   =		model(**SCREAMING_SNAKE_CASE      )

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

         A			:  Tuple   =		torch.tensor([-0.8_760, -7.0_042, -8.6_602]      ).to(SCREAMING_SNAKE_CASE      )

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






'''simple docstring'''




# Copyright 2023 The HuggingFace Inc. 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.
import re

from ..utils import cached_file


# docstyle-ignore
lowercase     :							Tuple       						=     '\nHuman: <<task>>\n\nAssistant: '


lowercase     :							Union[str, Any]       						=     'huggingface-tools/default-prompts'
lowercase     :							int       						=     {'chat': 'chat_prompt_template.txt', 'run': 'run_prompt_template.txt'}







def 						lowerCAmelCase_							(  snake_case__						,							snake_case__						,							snake_case__="run"		):




    '''simple docstring'''



    if prompt_or_repo_id is None:
        A			:  List[Any]   =		DEFAULT_PROMPTS_REPO

    # prompt is considered a repo ID when it does not contain any kind of space
    if re.search('''\\s'''						,							snake_case__		) is not None:
        return prompt_or_repo_id

    A			:  int   =		cached_file(
        snake_case__						,							PROMPT_FILES[mode]						,							repo_type='''dataset'''						,							user_agent={'''agent''': agent_name}		)
    with open(snake_case__						,							'''r'''						,							encoding='''utf-8'''		) as f:
        return f.read()




