

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


							"""simple docstring"""





							def __init__( self					,						_A					,						_A=1_3					,						_A=2					,						_A=2_4					,						_A=1_6					,						_A=True					,						_A=True					,						_A=3_2					,						_A=5					,						_A=4					,						_A=3_7					,						_A="gelu"					,						_A=0.1					,						_A=0.1					,						_A=1_0					,						_A=0.02					,						_A=None					,						_A=2					,						_A=2					,						):
												__lowerCAmelCase					=							parent
												__lowerCAmelCase					=							batch_size
												__lowerCAmelCase					=							patch_size
												__lowerCAmelCase					=							max_length
												__lowerCAmelCase					=							num_mel_bins
												__lowerCAmelCase					=							is_training
												__lowerCAmelCase					=							use_labels
												__lowerCAmelCase					=							hidden_size
												__lowerCAmelCase					=							num_hidden_layers
												__lowerCAmelCase					=							num_attention_heads
												__lowerCAmelCase					=							intermediate_size
												__lowerCAmelCase					=							hidden_act
												__lowerCAmelCase					=							hidden_dropout_prob
												__lowerCAmelCase					=							attention_probs_dropout_prob
												__lowerCAmelCase					=							type_sequence_label_size
												__lowerCAmelCase					=							initializer_range
												__lowerCAmelCase					=							scope
												__lowerCAmelCase					=							frequency_stride
												__lowerCAmelCase					=							time_stride

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




							def        A__  ( self							):
												__lowerCAmelCase					=							floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]							)

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

												__lowerCAmelCase					=							self.get_config()

												return config, input_values, labels




							def        A__  ( 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=_A					,						initializer_range=self.initializer_range					,						frequency_stride=self.frequency_stride					,						time_stride=self.time_stride					,						)




							def        A__  ( self					,						_A					,						_A					,						_A							):
												__lowerCAmelCase					=							ASTModel(config=_A							)
												model.to(_A							)
												model.eval()
												__lowerCAmelCase					=							model(_A							)
												self.parent.assertEqual(result.last_hidden_state.shape					,						(self.batch_size, self.seq_length, self.hidden_size)							)




							def        A__  ( self							):
												__lowerCAmelCase					=							self.prepare_config_and_inputs()
												(
												    (
												    __lowerCAmelCase
												),	(
												    __lowerCAmelCase
												),	(
												    __lowerCAmelCase
												),	
												)					=							config_and_inputs
												__lowerCAmelCase					=							{'input_values': input_values}
												return config, inputs_dict





@require_torch
class     snake_case_			(				_a			, _a			, 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					,						_A					,						_A					,						_A					,						_A					,						_A							):
												if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																	return True

												return False




							def        A__  ( self							):
												__lowerCAmelCase					=							ASTModelTester(self							)
												__lowerCAmelCase					=							ConfigTester(self					,						config_class=_A					,						has_text_modality=_A					,						hidden_size=3_7							)




							def        A__  ( self							):
												self.config_tester.run_common_tests()




							@unittest.skip(reason='AST does not use inputs_embeds'							)
							def        A__  ( self							):
												pass




							def        A__  ( self							):
												__lowerCAmelCase,	__lowerCAmelCase					=							self.model_tester.prepare_config_and_inputs_for_common()

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




							def        A__  ( self							):
												__lowerCAmelCase,	__lowerCAmelCase					=							self.model_tester.prepare_config_and_inputs_for_common()

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

																	__lowerCAmelCase					=							['input_values']
																	self.assertListEqual(arg_names[:1]					,						_A							)




							def        A__  ( self							):
												__lowerCAmelCase					=							self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_A							)




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


def        __lowercase    (  ):

					"""simple docstring"""






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

					__lowerCAmelCase,	__lowerCAmelCase					=							torchaudio.load(UpperCAmelCase__      )

					return audio, sampling_rate





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


							"""simple docstring"""





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




							@slow
							def        A__  ( self							):
												__lowerCAmelCase					=							self.default_feature_extractor
												__lowerCAmelCase					=							ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593'							).to(_A							)

												__lowerCAmelCase					=							self.default_feature_extractor
												__lowerCAmelCase,	__lowerCAmelCase					=							prepare_audio()
												__lowerCAmelCase					=							audio.squeeze().numpy()
												__lowerCAmelCase					=							feature_extractor(_A					,						sampling_rate=_A					,						return_tensors='pt'							).to(_A							)

												# forward pass
												with torch.no_grad():
																	__lowerCAmelCase					=							model(**_A							)

												# verify the logits
												__lowerCAmelCase					=							torch.Size((1, 5_2_7)							)
												self.assertEqual(outputs.logits.shape					,						_A							)

												__lowerCAmelCase					=							torch.tensor([-0.8760, -7.0042, -8.6602]							).to(_A							)

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









import hashlib
import unittest

from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available
from transformers.pipelines import DepthEstimationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_timm,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image
else:





		class     snake_case_			:


									"""simple docstring"""





									@staticmethod
									def        A__  ( *_A					,						**_A							):
														pass


def        __lowercase    (  UpperCAmelCase__      ):

					"""simple docstring"""






					__lowerCAmelCase					=							hashlib.mda(image.tobytes()      )
					return m.hexdigest()





@is_pipeline_test
@require_vision
@require_timm
@require_torch
class     snake_case_			(				unittest.TestCase							):


							"""simple docstring"""





							__UpperCAmelCase       =MODEL_FOR_DEPTH_ESTIMATION_MAPPING




							def        A__  ( self					,						_A					,						_A					,						_A							):
												__lowerCAmelCase					=							DepthEstimationPipeline(model=_A					,						image_processor=_A							)
												return depth_estimator, [
												    "./tests/fixtures/tests_samples/COCO/000000039769.png",
												    "./tests/fixtures/tests_samples/COCO/000000039769.png",
												]




							def        A__  ( self					,						_A					,						_A							):
												__lowerCAmelCase					=							depth_estimator('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
												self.assertEqual({'predicted_depth': ANY(torch.Tensor							), 'depth': ANY(Image.Image							)}					,						_A							)
												import datasets

												__lowerCAmelCase					=							datasets.load_dataset('hf-internal-testing/fixtures_image_utils'					,						'image'					,						split='test'							)
												__lowerCAmelCase					=							depth_estimator(
												    [
												        Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							),
												        'http://images.cocodataset.org/val2017/000000039769.jpg',
												        # RGBA
												        dataset[0]['file'],
												        # LA
												        dataset[1]['file'],
												        # L
												        dataset[2]['file'],
												    ]							)
												self.assertEqual(
												    [
												        {'predicted_depth': ANY(torch.Tensor							), 'depth': ANY(Image.Image							)},
												        {'predicted_depth': ANY(torch.Tensor							), 'depth': ANY(Image.Image							)},
												        {'predicted_depth': ANY(torch.Tensor							), 'depth': ANY(Image.Image							)},
												        {'predicted_depth': ANY(torch.Tensor							), 'depth': ANY(Image.Image							)},
												        {'predicted_depth': ANY(torch.Tensor							), 'depth': ANY(Image.Image							)},
												    ]					,						_A					,						)




							@require_tf
							@unittest.skip('Depth estimation is not implemented in TF'							)
							def        A__  ( self							):
												pass




							@slow
							@require_torch
							def        A__  ( self							):
												__lowerCAmelCase					=							'Intel/dpt-large'
												__lowerCAmelCase					=							pipeline('depth-estimation'					,						model=_A							)
												__lowerCAmelCase					=							depth_estimator('http://images.cocodataset.org/val2017/000000039769.jpg'							)
												__lowerCAmelCase					=							hashimage(outputs['depth']							)

												# This seems flaky.
												# self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977")
												self.assertEqual(nested_simplify(outputs['predicted_depth'].max().item()							)					,						29.304							)
												self.assertEqual(nested_simplify(outputs['predicted_depth'].min().item()							)					,						2.662							)




							@require_torch
							def        A__  ( self							):
												# This is highly irregular to have no small tests.
												self.skipTest('There is not hf-internal-testing tiny model for either GLPN nor DPT'							)






