
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	:Tuple  ,     a	:str  ,     a	:Optional[int]=1_3  ,     a	:Any=2  ,     a	:str=2_4  ,     a	:str=1_6  ,     a	:Tuple=True  ,     a	:Tuple=True  ,     a	:str=3_2  ,     a	:int=5  ,     a	:Optional[Any]=4  ,     a	:List[Any]=3_7  ,     a	:Dict="gelu"  ,     a	:Union[str, Any]=0.1  ,     a	:Optional[Any]=0.1  ,     a	:Optional[Any]=1_0  ,     a	:Tuple=0.02  ,     a	:List[Any]=None  ,     a	:Union[str, Any]=2  ,     a	:int=2  ,     )	->				Any:
        __UpperCamelCase			:     Dict         =      parent
        __UpperCamelCase			:     Tuple         =      batch_size
        __UpperCamelCase			:     int         =      patch_size
        __UpperCamelCase			:     int         =      max_length
        __UpperCamelCase			:     Tuple         =      num_mel_bins
        __UpperCamelCase			:     List[Any]         =      is_training
        __UpperCamelCase			:     List[Any]         =      use_labels
        __UpperCamelCase			:     Any         =      hidden_size
        __UpperCamelCase			:     Optional[int]         =      num_hidden_layers
        __UpperCamelCase			:     List[Any]         =      num_attention_heads
        __UpperCamelCase			:     Optional[Any]         =      intermediate_size
        __UpperCamelCase			:     List[str]         =      hidden_act
        __UpperCamelCase			:     Dict         =      hidden_dropout_prob
        __UpperCamelCase			:     Optional[Any]         =      attention_probs_dropout_prob
        __UpperCamelCase			:     Dict         =      type_sequence_label_size
        __UpperCamelCase			:     List[Any]         =      initializer_range
        __UpperCamelCase			:     List[str]         =      scope
        __UpperCamelCase			:     List[Any]         =      frequency_stride
        __UpperCamelCase			:     str         =      time_stride

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







 def      _lowerCamelCase       (      self	:Tuple		)	->				Union[str, Any]:
        __UpperCamelCase			:     str         =      floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]		)

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

        __UpperCamelCase			:     List[Any]         =      self.get_config()

        return config, input_values, labels







 def      _lowerCamelCase       (      self	:Any		)	->				str:
        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      _lowerCamelCase       (      self	:Tuple  ,     a	:List[str]  ,     a	:Union[str, Any]  ,     a	:Optional[Any]		)	->				int:
        __UpperCamelCase			:     Optional[Any]         =      ASTModel(config=UpperCamelCase__		)
        model.to(UpperCamelCase__		)
        model.eval()
        __UpperCamelCase			:     Union[str, Any]         =      model(UpperCamelCase__		)
        self.parent.assertEqual(result.last_hidden_state.shape  ,     (self.batch_size, self.seq_length, self.hidden_size)		)







 def      _lowerCamelCase       (      self	:str		)	->				Optional[Any]:
        __UpperCamelCase			:     Any         =      self.prepare_config_and_inputs()
        (
            __UpperCamelCase							
        )			:     str         =      config_and_inputs
        __UpperCamelCase			:     Optional[int]         =      {'''input_values''': input_values}
        return config, inputs_dict




@require_torch
class 				lowerCamelCase__							(       SCREAMING_SNAKE_CASE_  ,		SCREAMING_SNAKE_CASE_  ,		unittest.TestCase):




 '''simple docstring'''




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







 def      _lowerCamelCase       (      self	:Any  ,     a	:Any  ,     a	:str  ,     a	:Union[str, Any]  ,     a	:str  ,     a	:List[Any]		)	->				int:
        if pipeline_test_casse_name == "AudioClassificationPipelineTests":
               return True

        return False







 def      _lowerCamelCase       (      self	:int		)	->				Union[str, Any]:
        __UpperCamelCase			:     Union[str, Any]         =      ASTModelTester(self		)
        __UpperCamelCase			:     Dict         =      ConfigTester(self  ,     config_class=UpperCamelCase__  ,     has_text_modality=UpperCamelCase__  ,     hidden_size=3_7		)







 def      _lowerCamelCase       (      self	:Dict		)	->				Union[str, Any]:
        self.config_tester.run_common_tests()







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







 def      _lowerCamelCase       (      self	:str		)	->				Any:
        __UpperCamelCase			:     int         =      self.model_tester.prepare_config_and_inputs_for_common()

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







 def      _lowerCamelCase       (      self	:Any		)	->				Tuple:
        __UpperCamelCase			:     Tuple         =      self.model_tester.prepare_config_and_inputs_for_common()

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

               __UpperCamelCase			:     List[Any]         =      ['''input_values''']
               self.assertListEqual(arg_names[:1]  ,     UpperCamelCase__		)







 def      _lowerCamelCase       (      self	:Optional[Any]		)	->				Union[str, Any]:
        __UpperCamelCase			:     str         =      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCamelCase__		)







 @slow
 def      _lowerCamelCase       (      self	:Any		)	->				str:
        for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __UpperCamelCase			:     int         =      ASTModel.from_pretrained(UpperCamelCase__		)
               self.assertIsNotNone(UpperCamelCase__		)




def 			_SCREAMING_SNAKE_CASE      (	)      ->					Optional[int]:






       '''simple docstring'''





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

       __UpperCamelCase			:     List[Any]         =      torchaudio.load(__UpperCamelCase)

       return audio, sampling_rate




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




 '''simple docstring'''




 @cached_property
 def      _lowerCamelCase       (      self	:Optional[int]		)	->				Tuple:
        return (
            ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"		)
            if is_torchaudio_available()
            else None
        )







 @slow
 def      _lowerCamelCase       (      self	:str		)	->				Dict:
        __UpperCamelCase			:     Union[str, Any]         =      self.default_feature_extractor
        __UpperCamelCase			:     Optional[Any]         =      ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"		).to(UpperCamelCase__		)

        __UpperCamelCase			:     str         =      self.default_feature_extractor
        __UpperCamelCase			:     Optional[int]         =      prepare_audio()
        __UpperCamelCase			:     Optional[Any]         =      audio.squeeze().numpy()
        __UpperCamelCase			:     Any         =      feature_extractor(UpperCamelCase__  ,     sampling_rate=UpperCamelCase__  ,     return_tensors="pt"		).to(UpperCamelCase__		)

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

        # verify the logits
        __UpperCamelCase			:     Optional[int]         =      torch.Size((1, 5_2_7)		)
        self.assertEqual(outputs.logits.shape  ,     UpperCamelCase__		)

        __UpperCamelCase			:     str         =      torch.tensor([-0.8760, -7.0042, -8.6602]		).to(UpperCamelCase__		)

        self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,     UpperCamelCase__  ,     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 				lowerCamelCase__							:




			'''simple docstring'''




			@staticmethod
			def      _lowerCamelCase       (      *a	:Union[str, Any]  ,     **a	:int		)	->				str:
										pass




def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    Image)      ->					str:






							'''simple docstring'''





							__UpperCamelCase			:     Optional[int]         =      hashlib.mda(image.tobytes())
							return m.hexdigest()




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




	'''simple docstring'''




	_A			=  MODEL_FOR_DEPTH_ESTIMATION_MAPPING







	def      _lowerCamelCase       (      self	:Union[str, Any]  ,     a	:Optional[Any]  ,     a	:Optional[Any]  ,     a	:Optional[int]		)	->				Optional[Any]:
								__UpperCamelCase			:     Any         =      DepthEstimationPipeline(model=a  ,     image_processor=a		)
								return depth_estimator, [
								    "./tests/fixtures/tests_samples/COCO/000000039769.png",
								    "./tests/fixtures/tests_samples/COCO/000000039769.png",
								]







	def      _lowerCamelCase       (      self	:Union[str, Any]  ,     a	:Optional[Any]  ,     a	:List[Any]		)	->				Dict:
								__UpperCamelCase			:     str         =      depth_estimator("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
								self.assertEqual({"predicted_depth": ANY(torch.Tensor		), "depth": ANY(Image.Image		)}  ,     a		)
								import datasets

								__UpperCamelCase			:     List[Any]         =      datasets.load_dataset("hf-internal-testing/fixtures_image_utils"  ,     "image"  ,     split="test"		)
								__UpperCamelCase			:     int         =      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      _lowerCamelCase       (      self	:str		)	->				Optional[Any]:
								pass







	@slow
	@require_torch
	def      _lowerCamelCase       (      self	:List[Any]		)	->				List[Any]:
								__UpperCamelCase			:     Dict         =      "Intel/dpt-large"
								__UpperCamelCase			:     int         =      pipeline("depth-estimation"  ,     model=a		)
								__UpperCamelCase			:     Optional[int]         =      depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg"		)
								__UpperCamelCase			:     Optional[int]         =      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      _lowerCamelCase       (      self	:List[Any]		)	->				List[str]:
								# This is highly irregular to have no small tests.
								self.skipTest("There is not hf-internal-testing tiny model for either GLPN nor DPT"		)