

"""simple docstring"""





import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu




class 					_lowerCAmelCase  (	unittest.TestCase   ):







 """simple docstring"""







 def 					_lowercase (			self							:			Optional[Any]	):
    # clean up the VRAM after each test
    super().tearDown()
    gc.collect()
    torch.cuda.empty_cache()


 @property
 def 					_lowercase (			self							:			str	):
    __lowercase								=						1
    __lowercase								=						3
    __lowercase								=						(3_2, 3_2)

    __lowercase								=						floats_tensor((batch_size, num_channels) + sizes,					rng=random.Random(0	)	).to(UpperCAmelCase__	)
    return image


 @property
 def 					_lowercase (			self							:			Optional[Any]	):
    torch.manual_seed(0	)
    __lowercase								=						UNetaDConditionModel(
        block_out_channels=(3_2, 6_4),					layers_per_block=2,					sample_size=3_2,					in_channels=4,					out_channels=4,					down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),					up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),					cross_attention_dim=3_2,					)
    return model


 @property
 def 					_lowercase (			self							:			Optional[Any]	):
    torch.manual_seed(0	)
    __lowercase								=						AutoencoderKL(
        block_out_channels=[3_2, 6_4],					in_channels=3,					out_channels=3,					down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],					up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],					latent_channels=4,					)
    return model


 @property
 def 					_lowercase (			self							:			Dict	):
    torch.manual_seed(0	)
    __lowercase								=						CLIPTextConfig(
        bos_token_id=0,					eos_token_id=2,					hidden_size=3_2,					intermediate_size=3_7,					layer_norm_eps=1E-05,					num_attention_heads=4,					num_hidden_layers=5,					pad_token_id=1,					vocab_size=1_0_0_0,					)
    return CLIPTextModel(UpperCAmelCase__	)


 @property
 def 					_lowercase (			self							:			str	):
    def extract(*UpperCAmelCase__							:			Tuple,					**UpperCAmelCase__							:			str	):




       class 					_lowerCAmelCase  :







        """simple docstring"""







        def __init__(			self							:			int	):
           __lowercase								=						torch.ones([0]	)



        def 					_lowercase (			self							:			Optional[Any],					UpperCAmelCase__							:			Dict	):
           self.pixel_values.to(UpperCAmelCase__	)
           return self







       return Out()

    return extract


 def 					_lowercase (			self							:			Optional[Any]	):
    __lowercase								=						"cpu"  # ensure determinism for the device-dependent torch.Generator
    __lowercase								=						self.dummy_cond_unet
    __lowercase								=						DDIMScheduler(
        beta_start=0.00_085,					beta_end=0.012,					beta_schedule="scaled_linear",					clip_sample=UpperCAmelCase__,					set_alpha_to_one=UpperCAmelCase__,					)

    __lowercase								=						self.dummy_vae
    __lowercase								=						self.dummy_text_encoder
    __lowercase								=						CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"	)

    # make sure here that pndm scheduler skips prk
    __lowercase								=						StableDiffusionPipeline(
        unet=UpperCAmelCase__,					scheduler=UpperCAmelCase__,					vae=UpperCAmelCase__,					text_encoder=UpperCAmelCase__,					tokenizer=UpperCAmelCase__,					safety_checker=UpperCAmelCase__,					feature_extractor=self.dummy_extractor,					)
    __lowercase								=						sd_pipe.to(UpperCAmelCase__	)
    sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__	)

    __lowercase								=						"A painting of a squirrel eating a burger"

    __lowercase								=						torch.Generator(device=UpperCAmelCase__	).manual_seed(0	)
    __lowercase								=						sd_pipe([prompt],					generator=UpperCAmelCase__,					guidance_scale=6.0,					num_inference_steps=2,					output_type="np"	)
    __lowercase								=						output.images

    __lowercase								=						torch.Generator(device=UpperCAmelCase__	).manual_seed(0	)
    __lowercase								=						sd_pipe(
        [prompt],					generator=UpperCAmelCase__,					guidance_scale=6.0,					num_inference_steps=2,					output_type="np",					return_dict=UpperCAmelCase__,					)[0]

    __lowercase								=						image[0, -3:, -3:, -1]
    __lowercase								=						image_from_tuple[0, -3:, -3:, -1]

    assert image.shape == (1, 6_4, 6_4, 3)
    __lowercase								=						np.array([0.5_756, 0.6_118, 0.5_005, 0.5_041, 0.5_471, 0.4_726, 0.4_976, 0.4_865, 0.4_864]	)

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


 def 					_lowercase (			self							:			Union[str, Any]	):
    __lowercase								=						"cpu"  # ensure determinism for the device-dependent torch.Generator
    __lowercase								=						self.dummy_cond_unet
    __lowercase								=						PNDMScheduler(skip_prk_steps=UpperCAmelCase__	)
    __lowercase								=						self.dummy_vae
    __lowercase								=						self.dummy_text_encoder
    __lowercase								=						CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"	)

    # make sure here that pndm scheduler skips prk
    __lowercase								=						StableDiffusionPipeline(
        unet=UpperCAmelCase__,					scheduler=UpperCAmelCase__,					vae=UpperCAmelCase__,					text_encoder=UpperCAmelCase__,					tokenizer=UpperCAmelCase__,					safety_checker=UpperCAmelCase__,					feature_extractor=self.dummy_extractor,					)
    __lowercase								=						sd_pipe.to(UpperCAmelCase__	)
    sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__	)

    __lowercase								=						"A painting of a squirrel eating a burger"
    __lowercase								=						torch.Generator(device=UpperCAmelCase__	).manual_seed(0	)
    __lowercase								=						sd_pipe([prompt],					generator=UpperCAmelCase__,					guidance_scale=6.0,					num_inference_steps=2,					output_type="np"	)

    __lowercase								=						output.images

    __lowercase								=						torch.Generator(device=UpperCAmelCase__	).manual_seed(0	)
    __lowercase								=						sd_pipe(
        [prompt],					generator=UpperCAmelCase__,					guidance_scale=6.0,					num_inference_steps=2,					output_type="np",					return_dict=UpperCAmelCase__,					)[0]

    __lowercase								=						image[0, -3:, -3:, -1]
    __lowercase								=						image_from_tuple[0, -3:, -3:, -1]

    assert image.shape == (1, 6_4, 6_4, 3)
    __lowercase								=						np.array([0.5_125, 0.5_716, 0.4_828, 0.5_060, 0.5_650, 0.4_768, 0.5_185, 0.4_895, 0.4_993]	)

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


 def 					_lowercase (			self							:			int	):
    __lowercase								=						StableDiffusionPipeline.from_pretrained(
        "hf-internal-testing/tiny-stable-diffusion-lms-pipe",					safety_checker=UpperCAmelCase__	)
    assert isinstance(UpperCAmelCase__,					UpperCAmelCase__	)
    assert isinstance(pipe.scheduler,					UpperCAmelCase__	)
    assert pipe.safety_checker is None

    __lowercase								=						pipe("example prompt",					num_inference_steps=2	).images[0]
    assert image is not None

    # check that there's no error when saving a pipeline with one of the models being None
    with tempfile.TemporaryDirectory() as tmpdirname:
       pipe.save_pretrained(UpperCAmelCase__	)
       __lowercase								=						StableDiffusionPipeline.from_pretrained(UpperCAmelCase__	)

    # sanity check that the pipeline still works
    assert pipe.safety_checker is None
    __lowercase								=						pipe("example prompt",					num_inference_steps=2	).images[0]
    assert image is not None



 @unittest.skipIf(torch_device != "cuda",					"This test requires a GPU"	)
 def 					_lowercase (			self							:			str	):
    __lowercase								=						self.dummy_cond_unet
    __lowercase								=						PNDMScheduler(skip_prk_steps=UpperCAmelCase__	)
    __lowercase								=						self.dummy_vae
    __lowercase								=						self.dummy_text_encoder
    __lowercase								=						CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"	)

    # put models in fp16
    __lowercase								=						unet.half()
    __lowercase								=						vae.half()
    __lowercase								=						bert.half()

    # make sure here that pndm scheduler skips prk
    __lowercase								=						StableDiffusionPipeline(
        unet=UpperCAmelCase__,					scheduler=UpperCAmelCase__,					vae=UpperCAmelCase__,					text_encoder=UpperCAmelCase__,					tokenizer=UpperCAmelCase__,					safety_checker=UpperCAmelCase__,					feature_extractor=self.dummy_extractor,					)
    __lowercase								=						sd_pipe.to(UpperCAmelCase__	)
    sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__	)

    __lowercase								=						"A painting of a squirrel eating a burger"
    __lowercase								=						sd_pipe([prompt],					num_inference_steps=2,					output_type="np"	).images

    assert image.shape == (1, 6_4, 6_4, 3)







@nightly
@require_torch_gpu
class 					_lowerCAmelCase  (	unittest.TestCase   ):







 """simple docstring"""







 def 					_lowercase (			self							:			int	):
    # clean up the VRAM after each test
    super().tearDown()
    gc.collect()
    torch.cuda.empty_cache()


 def 					_lowercase (			self							:			Dict	):
    __lowercase								=						StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5",					safety_checker=UpperCAmelCase__	)
    __lowercase								=						LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config	)
    __lowercase								=						sd_pipe.to(UpperCAmelCase__	)
    sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__	)

    __lowercase								=						(
        "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle"
        " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with"
        " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and"
        " children from bahnhof zoo, detailed "
    )
    __lowercase								=						4_0_0_3_6_6_0_3_4_6
    __lowercase								=						7

    # without safety guidance (sld_guidance_scale = 0)
    __lowercase								=						torch.manual_seed(UpperCAmelCase__	)
    __lowercase								=						sd_pipe(
        [prompt],					generator=UpperCAmelCase__,					guidance_scale=UpperCAmelCase__,					num_inference_steps=5_0,					output_type="np",					width=5_1_2,					height=5_1_2,					sld_guidance_scale=0,					)

    __lowercase								=						output.images
    __lowercase								=						image[0, -3:, -3:, -1]
    __lowercase								=						[0.2_278, 0.2_231, 0.2_249, 0.2_333, 0.2_303, 0.1_885, 0.2_273, 0.2_144, 0.2_176]

    assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

    # without safety guidance (strong configuration)
    __lowercase								=						torch.manual_seed(UpperCAmelCase__	)
    __lowercase								=						sd_pipe(
        [prompt],					generator=UpperCAmelCase__,					guidance_scale=UpperCAmelCase__,					num_inference_steps=5_0,					output_type="np",					width=5_1_2,					height=5_1_2,					sld_guidance_scale=2_0_0_0,					sld_warmup_steps=7,					sld_threshold=0.025,					sld_momentum_scale=0.5,					sld_mom_beta=0.7,					)

    __lowercase								=						output.images
    __lowercase								=						image[0, -3:, -3:, -1]
    __lowercase								=						[0.2_383, 0.2_276, 0.236, 0.2_192, 0.2_186, 0.2_053, 0.1_971, 0.1_901, 0.1_719]

    assert image.shape == (1, 5_1_2, 5_1_2, 3)

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


 def 					_lowercase (			self							:			str	):
    __lowercase								=						StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5",					safety_checker=UpperCAmelCase__	)
    __lowercase								=						LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config	)
    __lowercase								=						sd_pipe.to(UpperCAmelCase__	)
    sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__	)

    __lowercase								=						"padme amidala taking a bath artwork, safe for work, no nudity"
    __lowercase								=						2_7_3_4_9_7_1_7_5_5
    __lowercase								=						7

    __lowercase								=						torch.manual_seed(UpperCAmelCase__	)
    __lowercase								=						sd_pipe(
        [prompt],					generator=UpperCAmelCase__,					guidance_scale=UpperCAmelCase__,					num_inference_steps=5_0,					output_type="np",					width=5_1_2,					height=5_1_2,					sld_guidance_scale=0,					)

    __lowercase								=						output.images
    __lowercase								=						image[0, -3:, -3:, -1]
    __lowercase								=						[0.3_502, 0.3_622, 0.3_396, 0.3_642, 0.3_478, 0.3_318, 0.35, 0.3_348, 0.3_297]

    assert image.shape == (1, 5_1_2, 5_1_2, 3)

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

    __lowercase								=						torch.manual_seed(UpperCAmelCase__	)
    __lowercase								=						sd_pipe(
        [prompt],					generator=UpperCAmelCase__,					guidance_scale=UpperCAmelCase__,					num_inference_steps=5_0,					output_type="np",					width=5_1_2,					height=5_1_2,					sld_guidance_scale=2_0_0_0,					sld_warmup_steps=7,					sld_threshold=0.025,					sld_momentum_scale=0.5,					sld_mom_beta=0.7,					)

    __lowercase								=						output.images
    __lowercase								=						image[0, -3:, -3:, -1]
    __lowercase								=						[0.5_531, 0.5_206, 0.4_895, 0.5_156, 0.5_182, 0.4_751, 0.4_802, 0.4_803, 0.4_443]

    assert image.shape == (1, 5_1_2, 5_1_2, 3)

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



 def 					_lowercase (			self							:			Tuple	):
    __lowercase								=						StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"	)
    __lowercase								=						sd_pipe.to(UpperCAmelCase__	)
    sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__	)

    __lowercase								=						(
        "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c."
        " leyendecker"
    )
    __lowercase								=						1_0_4_4_3_5_5_2_3_4
    __lowercase								=						1_2

    __lowercase								=						torch.manual_seed(UpperCAmelCase__	)
    __lowercase								=						sd_pipe(
        [prompt],					generator=UpperCAmelCase__,					guidance_scale=UpperCAmelCase__,					num_inference_steps=5_0,					output_type="np",					width=5_1_2,					height=5_1_2,					sld_guidance_scale=0,					)

    __lowercase								=						output.images
    __lowercase								=						image[0, -3:, -3:, -1]
    __lowercase								=						np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]	)

    assert image.shape == (1, 5_1_2, 5_1_2, 3)

    assert np.abs(image_slice.flatten() - expected_slice	).max() < 1E-7

    __lowercase								=						torch.manual_seed(UpperCAmelCase__	)
    __lowercase								=						sd_pipe(
        [prompt],					generator=UpperCAmelCase__,					guidance_scale=UpperCAmelCase__,					num_inference_steps=5_0,					output_type="np",					width=5_1_2,					height=5_1_2,					sld_guidance_scale=2_0_0_0,					sld_warmup_steps=7,					sld_threshold=0.025,					sld_momentum_scale=0.5,					sld_mom_beta=0.7,					)

    __lowercase								=						output.images
    __lowercase								=						image[0, -3:, -3:, -1]
    __lowercase								=						np.array([0.5_818, 0.6_285, 0.6_835, 0.6_019, 0.625, 0.6_754, 0.6_096, 0.6_334, 0.6_561]	)
    assert image.shape == (1, 5_1_2, 5_1_2, 3)

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





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       :				List[Any]     ,   __magic_name__       :				Any     ,   __magic_name__       :				List[Any]=13     ,   __magic_name__       :				List[Any]=2     ,   __magic_name__       :				Tuple=24     ,   __magic_name__       :				List[str]=16     ,   __magic_name__       :				Dict=True     ,   __magic_name__       :				List[Any]=True     ,   __magic_name__       :				Optional[int]=32     ,   __magic_name__       :				Tuple=5     ,   __magic_name__       :				int=4     ,   __magic_name__       :				Tuple=37     ,   __magic_name__       :				List[str]="gelu"     ,   __magic_name__       :				Tuple=0.1     ,   __magic_name__       :				Tuple=0.1     ,   __magic_name__       :				Union[str, Any]=10     ,   __magic_name__       :				Tuple=0.02     ,   __magic_name__       :				Tuple=None     ,   __magic_name__       :				Any=2     ,   __magic_name__       :				Dict=2     ,   )     ->		int:
        SCREAMING_SNAKE_CASE_      =     parent
        SCREAMING_SNAKE_CASE_      =     batch_size
        SCREAMING_SNAKE_CASE_      =     patch_size
        SCREAMING_SNAKE_CASE_      =     max_length
        SCREAMING_SNAKE_CASE_      =     num_mel_bins
        SCREAMING_SNAKE_CASE_      =     is_training
        SCREAMING_SNAKE_CASE_      =     use_labels
        SCREAMING_SNAKE_CASE_      =     hidden_size
        SCREAMING_SNAKE_CASE_      =     num_hidden_layers
        SCREAMING_SNAKE_CASE_      =     num_attention_heads
        SCREAMING_SNAKE_CASE_      =     intermediate_size
        SCREAMING_SNAKE_CASE_      =     hidden_act
        SCREAMING_SNAKE_CASE_      =     hidden_dropout_prob
        SCREAMING_SNAKE_CASE_      =     attention_probs_dropout_prob
        SCREAMING_SNAKE_CASE_      =     type_sequence_label_size
        SCREAMING_SNAKE_CASE_      =     initializer_range
        SCREAMING_SNAKE_CASE_      =     scope
        SCREAMING_SNAKE_CASE_      =     frequency_stride
        SCREAMING_SNAKE_CASE_      =     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_      =     (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
        SCREAMING_SNAKE_CASE_      =     (self.max_length - self.patch_size) // self.time_stride + 1
        SCREAMING_SNAKE_CASE_      =     frequency_out_dimension * time_out_dimension
        SCREAMING_SNAKE_CASE_      =     num_patches + 2







  def       __A   (							self       :				Any      )     ->		Any:
        SCREAMING_SNAKE_CASE_      =     floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]      )

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

        SCREAMING_SNAKE_CASE_      =     self.get_config()

        return config, input_values, labels







  def       __A   (							self       :				Any      )     ->		Dict:
        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=__magic_name__     ,   initializer_range=self.initializer_range     ,   frequency_stride=self.frequency_stride     ,   time_stride=self.time_stride     ,   )







  def       __A   (							self       :				List[Any]     ,   __magic_name__       :				List[str]     ,   __magic_name__       :				str     ,   __magic_name__       :				List[str]      )     ->		Union[str, Any]:
        SCREAMING_SNAKE_CASE_      =     ASTModel(config=__magic_name__      )
        model.to(__magic_name__      )
        model.eval()
        SCREAMING_SNAKE_CASE_      =     model(__magic_name__      )
        self.parent.assertEqual(result.last_hidden_state.shape     ,   (self.batch_size, self.seq_length, self.hidden_size)      )







  def       __A   (							self       :				Tuple      )     ->		str:
        SCREAMING_SNAKE_CASE_      =     self.prepare_config_and_inputs()
        (
            (
            SCREAMING_SNAKE_CASE_
        )   ,       (
            SCREAMING_SNAKE_CASE_
        )   ,       (
            SCREAMING_SNAKE_CASE_
        )   ,       
        )      =     config_and_inputs
        SCREAMING_SNAKE_CASE_      =     {"input_values": input_values}
        return config, inputs_dict



@require_torch
class      lowerCamelCase    (SCREAMING_SNAKE_CASE__     ,					SCREAMING_SNAKE_CASE__     ,					unittest.TestCase    ):
  """simple docstring"""







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







  def       __A   (							self       :				Tuple     ,   __magic_name__       :				Union[str, Any]     ,   __magic_name__       :				Optional[Any]     ,   __magic_name__       :				Dict     ,   __magic_name__       :				Optional[int]     ,   __magic_name__       :				Tuple      )     ->		Tuple:
        if pipeline_test_casse_name == "AudioClassificationPipelineTests":
              return True

        return False







  def       __A   (							self       :				Optional[Any]      )     ->		Optional[Any]:
        SCREAMING_SNAKE_CASE_      =     ASTModelTester(self      )
        SCREAMING_SNAKE_CASE_      =     ConfigTester(self     ,   config_class=__magic_name__     ,   has_text_modality=__magic_name__     ,   hidden_size=37      )







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







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







  def       __A   (							self       :				int      )     ->		int:
        SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     self.model_tester.prepare_config_and_inputs_for_common()

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







  def       __A   (							self       :				List[Any]      )     ->		str:
        SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     self.model_tester.prepare_config_and_inputs_for_common()

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

              SCREAMING_SNAKE_CASE_      =     ["input_values"]
              self.assertListEqual(arg_names[:1]     ,   __magic_name__      )







  def       __A   (							self       :				int      )     ->		Any:
        SCREAMING_SNAKE_CASE_      =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__magic_name__      )







  @slow
  def       __A   (							self       :				int      )     ->		int:
        for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE_      =     ASTModel.from_pretrained(__magic_name__      )
              self.assertIsNotNone(__magic_name__      )



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

      SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     torchaudio.load(__UpperCamelCase )

      return audio, sampling_rate





@require_torch
@require_torchaudio
class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  @cached_property
  def       __A   (							self       :				List[Any]      )     ->		List[Any]:
        return (
            ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"      )
            if is_torchaudio_available()
            else None
        )







  @slow
  def       __A   (							self       :				Union[str, Any]      )     ->		Optional[int]:
        SCREAMING_SNAKE_CASE_      =     self.default_feature_extractor
        SCREAMING_SNAKE_CASE_      =     ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"      ).to(__magic_name__      )

        SCREAMING_SNAKE_CASE_      =     self.default_feature_extractor
        SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     prepare_audio()
        SCREAMING_SNAKE_CASE_      =     audio.squeeze().numpy()
        SCREAMING_SNAKE_CASE_      =     feature_extractor(__magic_name__     ,   sampling_rate=__magic_name__     ,   return_tensors="pt"      ).to(__magic_name__      )

        # forward pass
        with torch.no_grad():
              SCREAMING_SNAKE_CASE_      =     model(**__magic_name__      )

        # verify the logits
        SCREAMING_SNAKE_CASE_      =     torch.Size((1, 527)      )
        self.assertEqual(outputs.logits.shape     ,   __magic_name__      )

        SCREAMING_SNAKE_CASE_      =     torch.tensor([-0.8760, -7.0042, -8.6602]      ).to(__magic_name__      )

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


