





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







							"""simple docstring"""




							def __init__( self     :					Any,			_UpperCAmelCase     :					Tuple,			_UpperCAmelCase     :					List[Any]=1_3,			_UpperCAmelCase     :					Dict=2,			_UpperCAmelCase     :					int=2_4,			_UpperCAmelCase     :					List[str]=1_6,			_UpperCAmelCase     :					Union[str, Any]=True,			_UpperCAmelCase     :					Any=True,			_UpperCAmelCase     :					Optional[int]=3_2,			_UpperCAmelCase     :					int=5,			_UpperCAmelCase     :					Dict=4,			_UpperCAmelCase     :					str=3_7,			_UpperCAmelCase     :					Optional[int]="gelu",			_UpperCAmelCase     :					List[str]=0.1,			_UpperCAmelCase     :					Optional[Any]=0.1,			_UpperCAmelCase     :					List[str]=1_0,			_UpperCAmelCase     :					List[Any]=0.02,			_UpperCAmelCase     :					Union[str, Any]=None,			_UpperCAmelCase     :					Optional[int]=2,			_UpperCAmelCase     :					List[Any]=2,			)				->			Optional[int]:





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

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






							def  A_     ( self     :					Dict						)				->			int:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      List[str]     =						floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]						)

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

														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						self.get_config()

														return config, input_values, labels






							def  A_     ( self     :					Optional[Any]						)				->			Dict:





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






							def  A_     ( self     :					Optional[int],			_UpperCAmelCase     :					Tuple,			_UpperCAmelCase     :					Any,			_UpperCAmelCase     :					int						)				->			Union[str, Any]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Dict     =						ASTModel(config=_UpperCAmelCase						)
														model.to(_UpperCAmelCase						)
														model.eval()
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						model(_UpperCAmelCase						)
														self.parent.assertEqual(result.last_hidden_state.shape,			(self.batch_size, self.seq_length, self.hidden_size)						)






							def  A_     ( self     :					str						)				->			Union[str, Any]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      str     =						self.prepare_config_and_inputs()
														(
														    (
														    SCREAMING_SNAKE_CASE__
														)   ,(
														    SCREAMING_SNAKE_CASE__
														)   ,(
														    SCREAMING_SNAKE_CASE__
														)   ,
														)       :      Union[str, Any]     =						config_and_inputs
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						{"input_values": input_values}
														return config, inputs_dict


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







							"""simple docstring"""




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






							def  A_     ( self     :					Tuple,			_UpperCAmelCase     :					str,			_UpperCAmelCase     :					Optional[Any],			_UpperCAmelCase     :					Optional[int],			_UpperCAmelCase     :					Dict,			_UpperCAmelCase     :					Optional[Any]						)				->			Any:





														"""simple docstring"""
														if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																					return True

														return False






							def  A_     ( self     :					List[Any]						)				->			Dict:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Optional[int]     =						ASTModelTester(self						)
														SCREAMING_SNAKE_CASE__       :      Tuple     =						ConfigTester(self,			config_class=_UpperCAmelCase,			has_text_modality=_UpperCAmelCase,			hidden_size=3_7						)






							def  A_     ( self     :					Optional[Any]						)				->			int:





														"""simple docstring"""
														self.config_tester.run_common_tests()






							@unittest.skip(reason="AST does not use inputs_embeds"						)
							def  A_     ( self     :					Optional[int]						)				->			Tuple:





														"""simple docstring"""
														pass






							def  A_     ( self     :					Tuple						)				->			Optional[Any]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__       :      List[Any]     =						self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					SCREAMING_SNAKE_CASE__       :      Any     =						model_class(_UpperCAmelCase						)
																					self.assertIsInstance(model.get_input_embeddings(),			(nn.Module)						)
																					SCREAMING_SNAKE_CASE__       :      Dict     =						model.get_output_embeddings()
																					self.assertTrue(x is None or isinstance(_UpperCAmelCase,			nn.Linear						)						)






							def  A_     ( self     :					Union[str, Any]						)				->			Optional[Any]:





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						self.model_tester.prepare_config_and_inputs_for_common()

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

																					SCREAMING_SNAKE_CASE__       :      Tuple     =						["input_values"]
																					self.assertListEqual(arg_names[:1],			_UpperCAmelCase						)






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





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      Dict     =						self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*_UpperCAmelCase						)






							@slow
							def  A_     ( self     :					str						)				->			str:





														"""simple docstring"""
														for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						ASTModel.from_pretrained(_UpperCAmelCase						)
																					self.assertIsNotNone(_UpperCAmelCase						)




def _a (  )	->    str:

							'''simple docstring'''






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

							SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__       :      Dict     =						torchaudio.load(SCREAMING_SNAKE_CASE__       )

							return audio, sampling_rate







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







							"""simple docstring"""




							@cached_property
							def  A_     ( self     :					List[Any]						)				->			List[str]:





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






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





														"""simple docstring"""
														SCREAMING_SNAKE_CASE__       :      int     =						self.default_feature_extractor
														SCREAMING_SNAKE_CASE__       :      Union[str, Any]     =						ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"						).to(_UpperCAmelCase						)

														SCREAMING_SNAKE_CASE__       :      List[Any]     =						self.default_feature_extractor
														SCREAMING_SNAKE_CASE__   ,SCREAMING_SNAKE_CASE__       :      str     =						prepare_audio()
														SCREAMING_SNAKE_CASE__       :      Optional[Any]     =						audio.squeeze().numpy()
														SCREAMING_SNAKE_CASE__       :      Any     =						feature_extractor(_UpperCAmelCase,			sampling_rate=_UpperCAmelCase,			return_tensors="pt"						).to(_UpperCAmelCase						)

														# forward pass
														with torch.no_grad():
																					SCREAMING_SNAKE_CASE__       :      Dict     =						model(**_UpperCAmelCase						)

														# verify the logits
														SCREAMING_SNAKE_CASE__       :      List[str]     =						torch.Size((1, 5_2_7)						)
														self.assertEqual(outputs.logits.shape,			_UpperCAmelCase						)

														SCREAMING_SNAKE_CASE__       :      Dict     =						torch.tensor([-0.8760, -7.0042, -8.6602]						).to(_UpperCAmelCase						)

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













import webbrowser
from sys import argv
from urllib.parse import parse_qs, quote

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

if __name__ == "__main__":
		_lowerCamelCase :    Union[str, Any]  							= '''%20'''.join(argv[1:]) if len(argv) > 1 else quote(str(input('''Search: ''')))

		print('''Googling.....''')

		_lowerCamelCase :    Any  							= f"https://www.google.com/search?q={query}&num=100"

		_lowerCamelCase :    Optional[Any]  							= requests.get(
		    url,
		    headers={'''User-Agent''': str(UserAgent().random)},
		)

		try:
				_lowerCamelCase :    Union[str, Any]  							= (
				    BeautifulSoup(res.text, '''html.parser''')
				    .find('''div''', attrs={'''class''': '''yuRUbf'''})
				    .find('''a''')
				    .get('''href''')
				)

		except AttributeError:
				_lowerCamelCase :    Optional[Any]  							= parse_qs(
				    BeautifulSoup(res.text, '''html.parser''')
				    .find('''div''', attrs={'''class''': '''kCrYT'''})
				    .find('''a''')
				    .get('''href''')
				)['''url'''][0]

		webbrowser.open(link)






