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




    """simple docstring"""




    def __init__(		self							:     Dict	,      A_							:     Optional[int]	,      A_							:     str=13	,      A_							:     Any=2	,      A_							:     Dict=24	,      A_							:     Optional[int]=16	,      A_							:     Any=True	,      A_							:     Optional[int]=True	,      A_							:     Optional[int]=32	,      A_							:     List[str]=5	,      A_							:     Dict=4	,      A_							:     Optional[int]=37	,      A_							:     Union[str, Any]="gelu"	,      A_							:     Dict=0.1	,      A_							:     int=0.1	,      A_							:     Any=10	,      A_							:     Union[str, Any]=0.02	,      A_							:     str=None	,      A_							:     Tuple=2	,      A_							:     Union[str, Any]=2	,      )    ->       Dict:
         __snake_case				=							parent
         __snake_case				=							batch_size
         __snake_case				=							patch_size
         __snake_case				=							max_length
         __snake_case				=							num_mel_bins
         __snake_case				=							is_training
         __snake_case				=							use_labels
         __snake_case				=							hidden_size
         __snake_case				=							num_hidden_layers
         __snake_case				=							num_attention_heads
         __snake_case				=							intermediate_size
         __snake_case				=							hidden_act
         __snake_case				=							hidden_dropout_prob
         __snake_case				=							attention_probs_dropout_prob
         __snake_case				=							type_sequence_label_size
         __snake_case				=							initializer_range
         __snake_case				=							scope
         __snake_case				=							frequency_stride
         __snake_case				=							time_stride

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

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

         __snake_case				=							self.get_config()

         return config, input_values, labels
    def  lowercase					(		self							:     List[str]    )    ->       Optional[Any]:
         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  lowercase					(		self							:     int	,      A_							:     int	,      A_							:     Dict	,      A_							:     str    )    ->       str:
         __snake_case				=							ASTModel(config=A_    )
         model.to(A_    )
         model.eval()
         __snake_case				=							model(A_    )
         self.parent.assertEqual(result.last_hidden_state.shape	,      (self.batch_size, self.seq_length, self.hidden_size)    )







    def  lowercase					(		self							:     List[str]    )    ->       Dict:
         __snake_case				=							self.prepare_config_and_inputs()
         (
             (
             __snake_case
         )		,	(
             __snake_case
         )		,	(
             __snake_case
         )		,	
         )				=							config_and_inputs
         __snake_case				=							{'''input_values''': input_values}
         return config, inputs_dict






@require_torch
class      _A	(						_UpperCAmelCase							, _UpperCAmelCase							, unittest.TestCase					):




    """simple docstring"""




    UpperCamelCase_	:					Union[str, Any]							=					(
        (
            ASTModel,
            ASTForAudioClassification,
        )
        if is_torch_available()
        else ()
    )
    UpperCamelCase_	:					Tuple							=					(
        {'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel}
        if is_torch_available()
        else {}
    )
    UpperCamelCase_	:					List[str]							=					False
    UpperCamelCase_	:					Tuple							=					False
    UpperCamelCase_	:					Any							=					False
    UpperCamelCase_	:					Tuple							=					False
    def  lowercase					(		self							:     Tuple	,      A_							:     Optional[int]	,      A_							:     Any	,      A_							:     Tuple	,      A_							:     int	,      A_							:     Union[str, Any]    )    ->       List[str]:
         if pipeline_test_casse_name == "AudioClassificationPipelineTests":
              return True

         return False
    def  lowercase					(		self							:     Dict    )    ->       Dict:
         __snake_case				=							ASTModelTester(self    )
         __snake_case				=							ConfigTester(self	,      config_class=A_	,      has_text_modality=A_	,      hidden_size=37    )
    def  lowercase					(		self							:     Optional[int]    )    ->       List[Any]:
         self.config_tester.run_common_tests()
    @unittest.skip(reason='''AST does not use inputs_embeds'''    )
    def  lowercase					(		self							:     str    )    ->       List[Any]:
         pass
    def  lowercase					(		self							:     Dict    )    ->       Tuple:
         __snake_case		,	__snake_case				=							self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              __snake_case				=							model_class(A_    )
              self.assertIsInstance(model.get_input_embeddings()	,      (nn.Module)    )
              __snake_case				=							model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(A_	,      nn.Linear    )    )
    def  lowercase					(		self							:     List[str]    )    ->       Optional[int]:
         __snake_case		,	__snake_case				=							self.model_tester.prepare_config_and_inputs_for_common()

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

              __snake_case				=							['''input_values''']
              self.assertListEqual(arg_names[:1]	,      A_    )
    def  lowercase					(		self							:     Tuple    )    ->       str:
         __snake_case				=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*A_    )







    @slow
    def  lowercase					(		self							:     Tuple    )    ->       List[str]:
         for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __snake_case				=							ASTModel.from_pretrained(A_    )
              self.assertIsNotNone(A_    )






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

     __snake_case		,	__snake_case				=							torchaudio.load(snake_case)

     return audio, sampling_rate




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




    """simple docstring"""




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







    @slow
    def  lowercase					(		self							:     Dict    )    ->       int:
         __snake_case				=							self.default_feature_extractor
         __snake_case				=							ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''    ).to(A_    )

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

         # forward pass
         with torch.no_grad():
              __snake_case				=							model(**A_    )

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

         __snake_case				=							torch.tensor([-0.87_60, -7.00_42, -8.66_02]    ).to(A_    )

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



import gc
import unittest

import numpy as np
import torch

from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()



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




    """simple docstring"""




    def  lowercase					(		self							:     Tuple    )    ->       str:
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()
    def  lowercase					(		self							:     int    )    ->       Tuple:
         __snake_case				=							StableDiffusionKDiffusionPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4'''    )
         __snake_case				=							sd_pipe.to(A_    )
         sd_pipe.set_progress_bar_config(disable=A_    )

         sd_pipe.set_scheduler('''sample_euler'''    )

         __snake_case				=							'''A painting of a squirrel eating a burger'''
         __snake_case				=							torch.manual_seed(0    )
         __snake_case				=							sd_pipe([prompt]	,      generator=A_	,      guidance_scale=9.0	,      num_inference_steps=20	,      output_type='''np'''    )

         __snake_case				=							output.images

         __snake_case				=							image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         __snake_case				=							np.array([0.04_47, 0.04_92, 0.04_68, 0.04_08, 0.03_83, 0.04_08, 0.03_54, 0.03_80, 0.03_39]    )

         assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1E-2
    def  lowercase					(		self							:     Optional[Any]    )    ->       Tuple:
         __snake_case				=							StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''    )
         __snake_case				=							sd_pipe.to(A_    )
         sd_pipe.set_progress_bar_config(disable=A_    )

         sd_pipe.set_scheduler('''sample_euler'''    )

         __snake_case				=							'''A painting of a squirrel eating a burger'''
         __snake_case				=							torch.manual_seed(0    )
         __snake_case				=							sd_pipe([prompt]	,      generator=A_	,      guidance_scale=9.0	,      num_inference_steps=20	,      output_type='''np'''    )

         __snake_case				=							output.images

         __snake_case				=							image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         __snake_case				=							np.array([0.12_37, 0.13_20, 0.14_38, 0.13_59, 0.13_90, 0.11_32, 0.12_77, 0.11_75, 0.11_12]    )

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







    def  lowercase					(		self							:     List[str]    )    ->       Optional[Any]:
         __snake_case				=							StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base'''    )
         __snake_case				=							sd_pipe.to(A_    )
         sd_pipe.set_progress_bar_config(disable=A_    )

         sd_pipe.set_scheduler('''sample_dpmpp_2m'''    )

         __snake_case				=							'''A painting of a squirrel eating a burger'''
         __snake_case				=							torch.manual_seed(0    )
         __snake_case				=							sd_pipe(
             [prompt]	,      generator=A_	,      guidance_scale=7.5	,      num_inference_steps=15	,      output_type='''np'''	,      use_karras_sigmas=A_	,      )

         __snake_case				=							output.images

         __snake_case				=							image[0, -3:, -3:, -1]

         assert image.shape == (1, 512, 512, 3)
         __snake_case				=							np.array(
             [0.11_38_16_89, 0.12_11_29_21, 0.1_38_94_57, 0.12_54_96_06, 0.1_24_49_64, 0.10_83_15_17, 0.11_56_28_66, 0.10_86_78_16, 0.10_49_90_48]    )

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