






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				:	Optional[int]		,     __a				:	Dict		,     __a				:	List[Any]=13		,     __a				:	Union[str, Any]=2		,     __a				:	int=24		,     __a				:	Union[str, Any]=16		,     __a				:	Union[str, Any]=True		,     __a				:	Optional[Any]=True		,     __a				:	Dict=32		,     __a				:	Dict=5		,     __a				:	Any=4		,     __a				:	Optional[int]=37		,     __a				:	int="gelu"		,     __a				:	Any=0.1		,     __a				:	Tuple=0.1		,     __a				:	Dict=10		,     __a				:	Union[str, Any]=0.02		,     __a				:	Tuple=None		,     __a				:	Union[str, Any]=2		,     __a				:	Any=2		,     )			->  List[str]:


												"""simple docstring"""

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

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



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


												"""simple docstring"""

												__lowercase      :							List[str]				=     floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]							)

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

												__lowercase      :							Any				=     self.get_config()

												return config, input_values, labels



					def       lowerCAmelCase				(  self				:	List[str]							)			->  Optional[int]:


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



					def       lowerCAmelCase				(  self				:	str		,     __a				:	List[Any]		,     __a				:	Union[str, Any]		,     __a				:	List[str]							)			->  Union[str, Any]:


												"""simple docstring"""

												__lowercase      :							Optional[Any]				=     ASTModel(config=__a							)
												model.to(__a							)
												model.eval()
												__lowercase      :							List[Any]				=     model(__a							)
												self.parent.assertEqual(result.last_hidden_state.shape		,     (self.batch_size, self.seq_length, self.hidden_size)							)



					def       lowerCAmelCase				(  self				:	Any							)			->  List[str]:


												"""simple docstring"""

												__lowercase      :							str				=     self.prepare_config_and_inputs()
												(
												    (
												    __lowercase						
												)			,			(
												    __lowercase						
												)			,			(
												    __lowercase						
												)			,									
												)      :							List[Any]				=     config_and_inputs
												__lowercase      :							Dict				=     {"""input_values""": input_values}
												return config, inputs_dict







@require_torch
class 		lowerCAmelCase     ( __a      ,       __a      ,       unittest.TestCase			):

					'''simple docstring'''

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



					def       lowerCAmelCase				(  self				:	List[str]		,     __a				:	List[Any]		,     __a				:	Dict		,     __a				:	List[str]		,     __a				:	str		,     __a				:	List[Any]							)			->  Optional[Any]:


												"""simple docstring"""

												if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																			return True

												return False



					def       lowerCAmelCase				(  self				:	Tuple							)			->  Any:


												"""simple docstring"""

												__lowercase      :							Tuple				=     ASTModelTester(self							)
												__lowercase      :							Any				=     ConfigTester(self		,     config_class=__a		,     has_text_modality=__a		,     hidden_size=37							)



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


												"""simple docstring"""

												self.config_tester.run_common_tests()



					@unittest.skip(reason="""AST does not use inputs_embeds"""							)
					def       lowerCAmelCase				(  self				:	Optional[Any]							)			->  List[str]:


												"""simple docstring"""

												pass



					def       lowerCAmelCase				(  self				:	Optional[Any]							)			->  List[str]:


												"""simple docstring"""

												__lowercase			,			__lowercase      :							str				=     self.model_tester.prepare_config_and_inputs_for_common()

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



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


												"""simple docstring"""

												__lowercase			,			__lowercase      :							List[str]				=     self.model_tester.prepare_config_and_inputs_for_common()

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

																			__lowercase      :							Any				=     ["""input_values"""]
																			self.assertListEqual(arg_names[:1]		,     __a							)



					def       lowerCAmelCase				(  self				:	str							)			->  Optional[int]:


												"""simple docstring"""

												__lowercase      :							Dict				=     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__a							)



					@slow
					def       lowerCAmelCase				(  self				:	Optional[int]							)			->  Optional[Any]:


												"""simple docstring"""

												for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__lowercase      :							List[Any]				=     ASTModel.from_pretrained(__a							)
																			self.assertIsNotNone(__a							)







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

							__lowercase			,			__lowercase      :							int				=     torchaudio.load(__snake_case      )

							return audio, sampling_rate



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

					'''simple docstring'''

					@cached_property
					def       lowerCAmelCase				(  self				:	Optional[Any]							)			->  Dict:


												"""simple docstring"""

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



					@slow
					def       lowerCAmelCase				(  self				:	str							)			->  Optional[int]:


												"""simple docstring"""

												__lowercase      :							Union[str, Any]				=     self.default_feature_extractor
												__lowercase      :							Any				=     ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""							).to(__a							)

												__lowercase      :							Dict				=     self.default_feature_extractor
												__lowercase			,			__lowercase      :							Tuple				=     prepare_audio()
												__lowercase      :							int				=     audio.squeeze().numpy()
												__lowercase      :							Optional[int]				=     feature_extractor(__a		,     sampling_rate=__a		,     return_tensors="""pt"""							).to(__a							)

												# forward pass
												with torch.no_grad():
																			__lowercase      :							int				=     model(**__a							)

												# verify the logits
												__lowercase      :							Union[str, Any]				=     torch.Size((1, 527)							)
												self.assertEqual(outputs.logits.shape		,     __a							)

												__lowercase      :							Union[str, Any]				=     torch.tensor([-0.8760, -7.0042, -8.6602]							).to(__a							)

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







import logging
import os
import threading
import time


try:
	import warnings
except ImportError:
	lowerCamelCase : Any						   =       None

try:
	import msvcrt
except ImportError:
	lowerCamelCase : str						   =       None

try:
	import fcntl
except ImportError:
	lowerCamelCase : Optional[Any]						   =       None


# Backward compatibility
# ------------------------------------------------
try:
	TimeoutError
except NameError:
	lowerCamelCase : Union[str, Any]						   =       OSError


# Data
# ------------------------------------------------
lowerCamelCase : Tuple						   =       [
    '''Timeout''',
    '''BaseFileLock''',
    '''WindowsFileLock''',
    '''UnixFileLock''',
    '''SoftFileLock''',
    '''FileLock''',
]

lowerCamelCase : Tuple						   =       '''3.0.12'''


lowerCamelCase : Any						   =       None
def       snake_case_		(     ):
							global _logger
							__lowercase      :							List[str]				=     _logger or logging.getLogger(__name__      )
							return _logger

class 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

					def __init__(  self				:	Any		,     __a				:	Any							)			->  List[Any]:


												"""simple docstring"""

												__lowercase      :							List[str]				=     lock_file
												return None



					def __str__(  self				:	str							)			->  Any:


												"""simple docstring"""

												__lowercase      :							Any				=     F"The file lock '{self.lock_file}' could not be acquired."
												return temp







class 		lowerCAmelCase     :

					'''simple docstring'''

					def __init__(  self				:	List[Any]		,     __a				:	Optional[int]							)			->  int:


												"""simple docstring"""

												__lowercase      :							Optional[Any]				=     lock
												return None



					def __enter__(  self				:	Dict							)			->  Dict:


												"""simple docstring"""

												return self.lock



					def __exit__(  self				:	Optional[int]		,     __a				:	Dict		,     __a				:	Any		,     __a				:	Tuple							)			->  Optional[Any]:


												"""simple docstring"""

												self.lock.release()
												return None







class 		lowerCAmelCase     :

					'''simple docstring'''

					def __init__(  self				:	Tuple		,     __a				:	Any		,     __a				:	Dict=-1		,     __a				:	Optional[Any]=None							)			->  Any:


												"""simple docstring"""

												__lowercase      :							Optional[int]				=     max_filename_length if max_filename_length is not None else 255
												# Hash the filename if it's too long
												__lowercase      :							Dict				=     self.hash_filename_if_too_long(__a		,     __a							)
												# The path to the lock file.
												__lowercase      :							Optional[Any]				=     lock_file

												# The file descriptor for the *_lock_file* as it is returned by the
												# os.open() function.
												# This file lock is only NOT None, if the object currently holds the
												# lock.
												__lowercase      :							int				=     None

												# The default timeout value.
												__lowercase      :							Optional[int]				=     timeout

												# We use this lock primarily for the lock counter.
												__lowercase      :							Optional[Any]				=     threading.Lock()

												# The lock counter is used for implementing the nested locking
												# mechanism. Whenever the lock is acquired, the counter is increased and
												# the lock is only released, when this value is 0 again.
												__lowercase      :							Union[str, Any]				=     0
												return None



					@property
					def       lowerCAmelCase				(  self				:	Optional[Any]							)			->  Optional[int]:


												"""simple docstring"""

												return self._lock_file



					@property
					def       lowerCAmelCase				(  self				:	Optional[int]							)			->  Optional[Any]:


												"""simple docstring"""

												return self._timeout



					@timeout.setter
					def       lowerCAmelCase				(  self				:	Tuple		,     __a				:	Tuple							)			->  Dict:


												"""simple docstring"""

												__lowercase      :							Tuple				=     float(__a							)
												return None



					def       lowerCAmelCase				(  self				:	Dict							)			->  Tuple:


												"""simple docstring"""

												raise NotImplementedError()



					def       lowerCAmelCase				(  self				:	Dict							)			->  Any:


												"""simple docstring"""

												raise NotImplementedError()



					@property
					def       lowerCAmelCase				(  self				:	Dict							)			->  List[Any]:


												"""simple docstring"""

												return self._lock_file_fd is not None



					def       lowerCAmelCase				(  self				:	Any		,     __a				:	Optional[Any]=None		,     __a				:	Union[str, Any]=0.05							)			->  List[str]:


												"""simple docstring"""

												if timeout is None:
																			__lowercase      :							Union[str, Any]				=     self.timeout

												# Increment the number right at the beginning.
												# We can still undo it, if something fails.
												with self._thread_lock:
																			self._lock_counter += 1

												__lowercase      :							int				=     id(self							)
												__lowercase      :							Optional[Any]				=     self._lock_file
												__lowercase      :							List[str]				=     time.time()
												try:
																			while True:
																										with self._thread_lock:
																																	if not self.is_locked:
																																								logger().debug(F"Attempting to acquire lock {lock_id} on {lock_filename}"							)
																																								self._acquire()

																										if self.is_locked:
																																	logger().debug(F"Lock {lock_id} acquired on {lock_filename}"							)
																																	break
																										elif timeout >= 0 and time.time() - start_time > timeout:
																																	logger().debug(F"Timeout on acquiring lock {lock_id} on {lock_filename}"							)
																																	raise Timeout(self._lock_file							)
																										else:
																																	logger().debug(
																																	    F"Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ..."							)
																																	time.sleep(__a							)
												except:  # noqa
																			# Something did go wrong, so decrement the counter.
																			with self._thread_lock:
																										__lowercase      :							Optional[int]				=     max(0		,     self._lock_counter - 1							)

																			raise
												return _Acquire_ReturnProxy(lock=self							)



					def       lowerCAmelCase				(  self				:	Union[str, Any]		,     __a				:	Optional[Any]=False							)			->  Optional[Any]:


												"""simple docstring"""

												with self._thread_lock:
																			if self.is_locked:
																										self._lock_counter -= 1

																										if self._lock_counter == 0 or force:
																																	__lowercase      :							Optional[Any]				=     id(self							)
																																	__lowercase      :							str				=     self._lock_file

																																	logger().debug(F"Attempting to release lock {lock_id} on {lock_filename}"							)
																																	self._release()
																																	__lowercase      :							List[str]				=     0
																																	logger().debug(F"Lock {lock_id} released on {lock_filename}"							)

												return None



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


												"""simple docstring"""

												self.acquire()
												return self



					def __exit__(  self				:	List[str]		,     __a				:	str		,     __a				:	int		,     __a				:	List[Any]							)			->  Tuple:


												"""simple docstring"""

												self.release()
												return None



					def __del__(  self				:	Optional[int]							)			->  Optional[int]:


												"""simple docstring"""

												self.release(force=__a							)
												return None



					def       lowerCAmelCase				(  self				:	Tuple		,     __a				:	str		,     __a				:	int							)			->  str:


												"""simple docstring"""

												__lowercase      :							List[Any]				=     os.path.basename(__a							)
												if len(__a							) > max_length and max_length > 0:
																			__lowercase      :							int				=     os.path.dirname(__a							)
																			__lowercase      :							List[str]				=     str(hash(__a							)							)
																			__lowercase      :							Optional[Any]				=     filename[: max_length - len(__a							) - 8] + """...""" + hashed_filename + """.lock"""
																			return os.path.join(__a		,     __a							)
												else:
																			return path







class 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

					def __init__(  self				:	Union[str, Any]		,     __a				:	List[Any]		,     __a				:	Optional[int]=-1		,     __a				:	Tuple=None							)			->  List[Any]:


												"""simple docstring"""

												from .file_utils import relative_to_absolute_path

												super().__init__(__a		,     timeout=__a		,     max_filename_length=__a							)
												__lowercase      :							Tuple				=     """\\\\?\\""" + relative_to_absolute_path(self.lock_file							)



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


												"""simple docstring"""

												__lowercase      :							List[str]				=     os.O_RDWR | os.O_CREAT | os.O_TRUNC

												try:
																			__lowercase      :							Tuple				=     os.open(self._lock_file		,     __a							)
												except OSError:
																			pass
												else:
																			try:
																										msvcrt.locking(__a		,     msvcrt.LK_NBLCK		,     1							)
																			except OSError:
																										os.close(__a							)
																			else:
																										__lowercase      :							Union[str, Any]				=     fd
												return None



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


												"""simple docstring"""

												__lowercase      :							Optional[Any]				=     self._lock_file_fd
												__lowercase      :							int				=     None
												msvcrt.locking(__a		,     msvcrt.LK_UNLCK		,     1							)
												os.close(__a							)

												try:
																			os.remove(self._lock_file							)
												# Probably another instance of the application
												# that acquired the file lock.
												except OSError:
																			pass
												return None







class 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

					def __init__(  self				:	List[str]		,     __a				:	Optional[Any]		,     __a				:	str=-1		,     __a				:	List[str]=None							)			->  Any:


												"""simple docstring"""

												__lowercase      :							Dict				=     os.statvfs(os.path.dirname(__a							)							).f_namemax
												super().__init__(__a		,     timeout=__a		,     max_filename_length=__a							)



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


												"""simple docstring"""

												__lowercase      :							List[Any]				=     os.O_RDWR | os.O_CREAT | os.O_TRUNC
												__lowercase      :							List[str]				=     os.open(self._lock_file		,     __a							)

												try:
																			fcntl.flock(__a		,     fcntl.LOCK_EX | fcntl.LOCK_NB							)
												except OSError:
																			os.close(__a							)
												else:
																			__lowercase      :							str				=     fd
												return None



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


												"""simple docstring"""

												__lowercase      :							Any				=     self._lock_file_fd
												__lowercase      :							List[str]				=     None
												fcntl.flock(__a		,     fcntl.LOCK_UN							)
												os.close(__a							)
												return None







class 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

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


												"""simple docstring"""

												__lowercase      :							Tuple				=     os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
												try:
																			__lowercase      :							Union[str, Any]				=     os.open(self._lock_file		,     __a							)
												except OSError:
																			pass
												else:
																			__lowercase      :							Optional[int]				=     fd
												return None



					def       lowerCAmelCase				(  self				:	List[str]							)			->  Tuple:


												"""simple docstring"""

												os.close(self._lock_file_fd							)
												__lowercase      :							int				=     None

												try:
																			os.remove(self._lock_file							)
												# The file is already deleted and that's what we want.
												except OSError:
																			pass
												return None







lowerCamelCase : Optional[Any]						   =       None

if msvcrt:
	lowerCamelCase : List[Any]						   =       WindowsFileLock
elif fcntl:
	lowerCamelCase : List[Any]						   =       UnixFileLock
else:
	lowerCamelCase : Union[str, Any]						   =       SoftFileLock

	if warnings is not None:
		warnings.warn('''only soft file lock is available''')