



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

     """simple docstring"""






     def __init__( self :	Union[str, Any]   ,			__a :	str   ,			__a :	Any=1_3   ,			__a :	str=2   ,			__a :	Union[str, Any]=2_4   ,			__a :	int=1_6   ,			__a :	Any=True   ,			__a :	Optional[int]=True   ,			__a :	int=3_2   ,			__a :	List[Any]=5   ,			__a :	List[str]=4   ,			__a :	List[Any]=3_7   ,			__a :	Optional[int]="gelu"   ,			__a :	Any=0.1   ,			__a :	Any=0.1   ,			__a :	Union[str, Any]=1_0   ,			__a :	List[Any]=0.02   ,			__a :	Dict=None   ,			__a :	str=2   ,			__a :	Optional[int]=2   ,			):
      snake_case__				:							List[Any]      							= parent
      snake_case__				:							Dict      							= batch_size
      snake_case__				:							Tuple      							= patch_size
      snake_case__				:							int      							= max_length
      snake_case__				:							Union[str, Any]      							= num_mel_bins
      snake_case__				:							Any      							= is_training
      snake_case__				:							List[Any]      							= use_labels
      snake_case__				:							Optional[Any]      							= hidden_size
      snake_case__				:							List[str]      							= num_hidden_layers
      snake_case__				:							Dict      							= num_attention_heads
      snake_case__				:							Tuple      							= intermediate_size
      snake_case__				:							List[Any]      							= hidden_act
      snake_case__				:							Dict      							= hidden_dropout_prob
      snake_case__				:							Optional[int]      							= attention_probs_dropout_prob
      snake_case__				:							Tuple      							= type_sequence_label_size
      snake_case__				:							List[str]      							= initializer_range
      snake_case__				:							int      							= scope
      snake_case__				:							str      							= frequency_stride
      snake_case__				:							Dict      							= time_stride

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


     def 		lowercase   ( self :	int ):
      snake_case__				:							List[Any]      							= floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] )

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

      snake_case__				:							List[str]      							= self.get_config()

      return config, input_values, labels


     def 		lowercase   ( self :	Dict ):
      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=lowerCamelCase__   ,			initializer_range=self.initializer_range   ,			frequency_stride=self.frequency_stride   ,			time_stride=self.time_stride   ,			)


     def 		lowercase   ( self :	Optional[int]   ,			__a :	Optional[Any]   ,			__a :	List[Any]   ,			__a :	Any ):
      snake_case__				:							List[str]      							= ASTModel(config=lowerCamelCase__ )
      model.to(lowerCamelCase__ )
      model.eval()
      snake_case__				:							Dict      							= model(lowerCamelCase__ )
      self.parent.assertEqual(result.last_hidden_state.shape   ,			(self.batch_size, self.seq_length, self.hidden_size) )


     def 		lowercase   ( self :	Dict ):
      snake_case__				:							Union[str, Any]      							= self.prepare_config_and_inputs()
      (
          (
          snake_case__		
      )							,		(
          snake_case__		
      )							,		(
          snake_case__		
      )							,				
      )				:							Dict      							= config_and_inputs
      snake_case__				:							Optional[Any]      							= {"""input_values""": input_values}
      return config, inputs_dict



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

     """simple docstring"""






     __UpperCamelCase    :	Optional[int]		=       (
         (
             ASTModel,
             ASTForAudioClassification,
         )
         if is_torch_available()
         else ()
     )
     __UpperCamelCase    :	Any		=       (
         {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
         if is_torch_available()
         else {}
     )
     __UpperCamelCase    :	int		=       False
     __UpperCamelCase    :	str		=       False
     __UpperCamelCase    :	Any		=       False
     __UpperCamelCase    :	Optional[Any]		=       False


     def 		lowercase   ( self :	int   ,			__a :	Optional[Any]   ,			__a :	List[Any]   ,			__a :	Optional[Any]   ,			__a :	Optional[Any]   ,			__a :	List[str] ):
      if pipeline_test_casse_name == "AudioClassificationPipelineTests":
       return True

      return False


     def 		lowercase   ( self :	Optional[Any] ):
      snake_case__				:							List[str]      							= ASTModelTester(self )
      snake_case__				:							Optional[int]      							= ConfigTester(self   ,			config_class=lowerCamelCase__   ,			has_text_modality=lowerCamelCase__   ,			hidden_size=3_7 )


     def 		lowercase   ( self :	Optional[int] ):
      self.config_tester.run_common_tests()


     @unittest.skip(reason="""AST does not use inputs_embeds""" )
     def 		lowercase   ( self :	List[Any] ):
      pass


     def 		lowercase   ( self :	Union[str, Any] ):
      snake_case__							,		snake_case__				:							Any      							= self.model_tester.prepare_config_and_inputs_for_common()

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


     def 		lowercase   ( self :	Optional[Any] ):
      snake_case__							,		snake_case__				:							Union[str, Any]      							= self.model_tester.prepare_config_and_inputs_for_common()

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

       snake_case__				:							List[Any]      							= ["""input_values"""]
       self.assertListEqual(arg_names[:1]   ,			lowerCamelCase__ )


     def 		lowercase   ( self :	int ):
      snake_case__				:							Any      							= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCamelCase__ )


     @slow
     def 		lowercase   ( self :	Union[str, Any] ):
      for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       snake_case__				:							Dict      							= ASTModel.from_pretrained(lowerCamelCase__ )
       self.assertIsNotNone(lowerCamelCase__ )

def 	_lowercase	(     ):




 """simple docstring"""




 snake_case__				:							int      							= hf_hub_download(
     repo_id="""nielsr/audio-spectogram-transformer-checkpoint"""						,   filename="""sample_audio.flac"""						,   repo_type="""dataset""")

 snake_case__							,		snake_case__				:							Optional[Any]      							= torchaudio.load(UpperCamelCase__)

 return audio, sampling_rate



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

     """simple docstring"""






     @cached_property
     def 		lowercase   ( self :	Union[str, Any] ):
      return (
          ASTFeatureExtractor.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593""" )
          if is_torchaudio_available()
          else None
      )


     @slow
     def 		lowercase   ( self :	Dict ):
      snake_case__				:							Any      							= self.default_feature_extractor
      snake_case__				:							Optional[Any]      							= ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593""" ).to(lowerCamelCase__ )

      snake_case__				:							Optional[Any]      							= self.default_feature_extractor
      snake_case__							,		snake_case__				:							Dict      							= prepare_audio()
      snake_case__				:							Tuple      							= audio.squeeze().numpy()
      snake_case__				:							Tuple      							= feature_extractor(lowerCamelCase__   ,			sampling_rate=lowerCamelCase__   ,			return_tensors="""pt""" ).to(lowerCamelCase__ )

      # forward pass
      with torch.no_grad():
       snake_case__				:							Optional[Any]      							= model(**lowerCamelCase__ )

      # verify the logits
      snake_case__				:							Optional[Any]      							= torch.Size((1, 5_2_7) )
      self.assertEqual(outputs.logits.shape   ,			lowerCamelCase__ )

      snake_case__				:							Tuple      							= torch.tensor([-0.8760, -7.0042, -8.6602] ).to(lowerCamelCase__ )

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










from datetime import datetime as dt
import os

from github import Github


__A								=       [
    "good first issue",
    "good second issue",
    "good difficult issue",
    "feature request",
    "new model",
    "wip",
]







def      lowerCamelCase_						(			)	->			int:





				"""simple docstring"""


				__lowerCamelCase									=       Github(os.environ['GITHUB_TOKEN'] )
				__lowerCamelCase									=       g.get_repo('huggingface/transformers' )
				__lowerCamelCase									=       repo.get_issues(state='open' )

				for issue in open_issues:
								__lowerCamelCase									=       sorted([comment for comment in issue.get_comments()]					,	key=lambda UpperCamelCase__ : i.created_at					,	reverse=UpperCamelCase__ )
								__lowerCamelCase									=       comments[0] if len(UpperCamelCase__ ) > 0 else None
								if (
								    last_comment is not None
								    and last_comment.user.login == "github-actions[bot]"
								    and (dt.utcnow() - issue.updated_at).days > 7
								    and (dt.utcnow() - issue.created_at).days >= 30
								    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
								):
												# print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.")
												issue.edit(state='closed' )
								elif (
								    (dt.utcnow() - issue.updated_at).days > 23
								    and (dt.utcnow() - issue.created_at).days >= 30
								    and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() )
								):
												# print(f"Would add stale comment to {issue.number}")
												issue.create_comment(
												    'This issue has been automatically marked as stale because it has not had '
												    'recent activity. If you think this still needs to be addressed '
												    'please comment on this thread.\n\nPlease note that issues that do not follow the '
												    '[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) '
												    'are likely to be ignored.' )


if __name__ == "__main__":
					main()


