






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






 """simple docstring"""





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

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

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

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

       return config, input_values, labels
 def   _UpperCAmelCase       (							self ):
       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   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       UpperCamelCase_				:   Optional[Any]					    =							ASTModel(config=__lowerCAmelCase )
       model.to(__lowerCAmelCase )
       model.eval()
       UpperCamelCase_				:   Optional[Any]					    =							model(__lowerCAmelCase )
       self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, self.seq_length, self.hidden_size) )





 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Any					    =							self.prepare_config_and_inputs()
       (
           (
           UpperCamelCase_
       )    ,			(
           UpperCamelCase_
       )    ,			(
           UpperCamelCase_
       )    ,			
       )				:   Any					    =							config_and_inputs
       UpperCamelCase_				:   Union[str, Any]					    =							{"""input_values""": input_values}
       return config, inputs_dict






@require_torch
class     A    (      SCREAMING_SNAKE_CASE__,   SCREAMING_SNAKE_CASE__,   unittest.TestCase						):






 """simple docstring"""





 __a			:						str      =						(
     (
         ASTModel,
         ASTForAudioClassification,
     )
     if is_torch_available()
     else ()
 )
 __a			:						Union[str, Any]      =						(
     {'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel}
     if is_torch_available()
     else {}
 )
 __a			:						List[Any]      =						False
 __a			:						int      =						False
 __a			:						Union[str, Any]      =						False
 __a			:						str      =						False
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       if pipeline_test_casse_name == "AudioClassificationPipelineTests":
             return True

       return False
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[Any]					    =							ASTModelTester(self )
       UpperCamelCase_				:   Any					    =							ConfigTester(self			,     config_class=__lowerCAmelCase			,     has_text_modality=__lowerCAmelCase			,     hidden_size=37 )
 def   _UpperCAmelCase       (							self ):
       self.config_tester.run_common_tests()
 @unittest.skip(reason="""AST does not use inputs_embeds""" )
 def   _UpperCAmelCase       (							self ):
       pass
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_    ,			UpperCamelCase_				:   Union[str, Any]					    =							self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             UpperCamelCase_				:   Optional[Any]					    =							model_class(__lowerCAmelCase )
             self.assertIsInstance(model.get_input_embeddings()			,     (nn.Module) )
             UpperCamelCase_				:   Union[str, Any]					    =							model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(__lowerCAmelCase			,     nn.Linear ) )
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_    ,			UpperCamelCase_				:   Any					    =							self.model_tester.prepare_config_and_inputs_for_common()

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

             UpperCamelCase_				:   Optional[int]					    =							["""input_values"""]
             self.assertListEqual(arg_names[:1]			,     __lowerCAmelCase )
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[int]					    =							self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCAmelCase )





 @slow
 def   _UpperCAmelCase       (							self ):
       for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCamelCase_				:   Any					    =							ASTModel.from_pretrained(__lowerCAmelCase )
             self.assertIsNotNone(__lowerCAmelCase )






def 							snake_case					(     )       ->				Any:





      """simple docstring"""

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

      UpperCamelCase_    ,			UpperCamelCase_				:   Optional[int]					    =							torchaudio.load(a_	)

      return audio, sampling_rate




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






 """simple docstring"""





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





 @slow
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   int					    =							self.default_feature_extractor
       UpperCamelCase_				:   str					    =							ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593""" ).to(__lowerCAmelCase )

       UpperCamelCase_				:   Tuple					    =							self.default_feature_extractor
       UpperCamelCase_    ,			UpperCamelCase_				:   Dict					    =							prepare_audio()
       UpperCamelCase_				:   int					    =							audio.squeeze().numpy()
       UpperCamelCase_				:   Any					    =							feature_extractor(__lowerCAmelCase			,     sampling_rate=__lowerCAmelCase			,     return_tensors="""pt""" ).to(__lowerCAmelCase )

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

       # verify the logits
       UpperCamelCase_				:   Dict					    =							torch.Size((1, 5_27) )
       self.assertEqual(outputs.logits.shape			,     __lowerCAmelCase )

       UpperCamelCase_				:   Union[str, Any]					    =							torch.tensor([-0.87_60, -7.00_42, -8.66_02] ).to(__lowerCAmelCase )

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














'''simple docstring'''

from __future__ import annotations

import os
from typing import Any

import requests

UpperCamelCase							="https://api.github.com"

# https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user
UpperCamelCase							=BASE_URL + "/user"

# https://github.com/settings/tokens
UpperCamelCase							=os.environ.get("USER_TOKEN", "")



def 							snake_case					(     a_							: str	)       ->				dict[Any, Any]:





      """simple docstring"""

      UpperCamelCase_				:   Tuple					    =							{
          """Authorization""": f"token {auth_token}",
          """Accept""": """application/vnd.github.v3+json""",
      }
      return requests.get(a_    ,   headers=a_	).json()


if __name__ == "__main__":  # pragma: no cover
      if USER_TOKEN:
            for key, value in fetch_github_info(USER_TOKEN).items():
                  print(f"{key}: {value}")
      else:
            raise ValueError("'USER_TOKEN' field cannot be empty.")






