


"""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 _lowerCAmelCase				:







   def __init__(	self						,	UpperCamelCase__						,	UpperCamelCase__=13						,	UpperCamelCase__=2						,	UpperCamelCase__=24						,	UpperCamelCase__=16						,	UpperCamelCase__=True						,	UpperCamelCase__=True						,	UpperCamelCase__=32						,	UpperCamelCase__=5						,	UpperCamelCase__=4						,	UpperCamelCase__=37						,	UpperCamelCase__="gelu"						,	UpperCamelCase__=0.1						,	UpperCamelCase__=0.1						,	UpperCamelCase__=10						,	UpperCamelCase__=0.02						,	UpperCamelCase__=None						,	UpperCamelCase__=2						,	UpperCamelCase__=2						,	)	->		List[Any]:

       '''simple docstring'''




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

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







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      List[Any]      					=    floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]						)

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

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

       return config, input_values, labels







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

       '''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  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)	->		List[Any]:

       '''simple docstring'''




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







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

       '''simple docstring'''




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







@require_torch
class _lowerCAmelCase				(      _lowercase    ,							_lowercase    ,							unittest.TestCase	):
   __UpperCAmelCase :       List[Any]							  =  (
       (
           ASTModel,
           ASTForAudioClassification,
       )
       if is_torch_available()
       else ()
   )
   __UpperCAmelCase :       List[Any]							  =  (
       {'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel}
       if is_torch_available()
       else {}
   )
   __UpperCAmelCase :       int							  =  False
   __UpperCAmelCase :       Optional[int]							  =  False
   __UpperCAmelCase :       Tuple							  =  False
   __UpperCAmelCase :       str							  =  False







   def  lowerCamelCase		(	self						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						)	->		List[Any]:

       '''simple docstring'''




       if pipeline_test_casse_name == "AudioClassificationPipelineTests":
           return True

       return False







   def  lowerCamelCase		(	self						)	->		str:

       '''simple docstring'''




       snake_case    :      str      					=    ASTModelTester(self						)
       snake_case    :      List[str]      					=    ConfigTester(self						,	config_class=UpperCamelCase__						,	has_text_modality=UpperCamelCase__						,	hidden_size=37						)







   def  lowerCamelCase		(	self						)	->		Tuple:

       '''simple docstring'''




       self.config_tester.run_common_tests()







   @unittest.skip(reason="AST does not use inputs_embeds"						)
   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




       pass







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

       '''simple docstring'''




       snake_case    :      Optional[int]      					=    self.model_tester.prepare_config_and_inputs_for_common()

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







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

       '''simple docstring'''




       snake_case    :      str      					=    self.model_tester.prepare_config_and_inputs_for_common()

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

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







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

       '''simple docstring'''




       snake_case    :      Dict      					=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__						)







   @slow
   def  lowerCamelCase		(	self						)	->		List[Any]:

       '''simple docstring'''




       for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           snake_case    :      Union[str, Any]      					=    ASTModel.from_pretrained(UpperCamelCase__						)
           self.assertIsNotNone(UpperCamelCase__						)







def   __lowerCAmelCase						(						)	->						List[Any]:


    """simple docstring"""





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

    snake_case    :      List[Any]      					=    torchaudio.load(lowercase )

    return audio, sampling_rate







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







   @cached_property
   def  lowerCamelCase		(	self						)	->		int:

       '''simple docstring'''




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







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

       '''simple docstring'''




       snake_case    :      int      					=    self.default_feature_extractor
       snake_case    :      List[Any]      					=    ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"						).to(UpperCamelCase__						)

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

       # forward pass
       with torch.no_grad():
           snake_case    :      Union[str, Any]      					=    model(**UpperCamelCase__						)

       # verify the logits
       snake_case    :      Tuple      					=    torch.Size((1, 527)						)
       self.assertEqual(outputs.logits.shape						,	UpperCamelCase__						)

       snake_case    :      Optional[int]      					=    torch.tensor([-0.8760, -7.0042, -8.6602]						).to(UpperCamelCase__						)

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













'''simple docstring'''







import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionImageVariationPipeline
from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device


_A	:			Union[str, Any]         =False

class _lowercase	(				unittest.TestCase		):
							pass



@slow
@require_torch_gpu
class _lowercase	(				unittest.TestCase		):




							def 		lowerCamelCase_				(							self:				Optional[int]     ):
														lowerCamelCase__					:	Tuple         =       VersatileDiffusionImageVariationPipeline.from_pretrained("""shi-labs/versatile-diffusion"""     )
														pipe.to(UpperCamelCase__     )
														pipe.set_progress_bar_config(disable=UpperCamelCase__     )

														lowerCamelCase__					:	Optional[int]         =       load_image(
														    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"""     )
														lowerCamelCase__					:	List[Any]         =       torch.manual_seed(0     )
														lowerCamelCase__					:	List[Any]         =       pipe(
														    image=UpperCamelCase__			,							generator=UpperCamelCase__			,							guidance_scale=7.5			,							num_inference_steps=50			,							output_type="""numpy"""			,							).images

														lowerCamelCase__					:	List[str]         =       image[0, 253:256, 253:256, -1]

														assert image.shape == (1, 512, 512, 3)
														lowerCamelCase__					:	Tuple         =       np.array([0.0_441, 0.0_469, 0.0_507, 0.0_575, 0.0_632, 0.0_650, 0.0_865, 0.0_909, 0.0_945]     )

														assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1e-2

