





from typing import Dict, List, Optional, Tuple, Union

import torch

from ...models import AutoencoderKL, TransformeraDModel
from ...schedulers import KarrasDiffusionSchedulers
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput







class   _UpperCamelCase  (       A_  ):







     '''simple docstring'''

     def __init__(						self    :  List[str] ,					__lowercase    :  TransformeraDModel ,					__lowercase    :  AutoencoderKL ,					__lowercase    :  KarrasDiffusionSchedulers ,					__lowercase    :  Optional[Dict[int, str]] = None ,					):






      '''simple docstring'''







      super().__init__()
      self.register_modules(transformer=__lowercase ,					vae=__lowercase ,					scheduler=__lowercase		)

      # create a imagenet -> id dictionary for easier use
      UpperCAmelCase_								=     {}
      if idalabel is not None:
       for key, value in idalabel.items():
        for label in value.split(""","""		):
         UpperCAmelCase_								=     int(__lowercase		)
       UpperCAmelCase_								=     dict(sorted(self.labels.items()		)		)





     def        SCREAMING_SNAKE_CASE							(						self    :  Union[str, Any] ,					__lowercase    :  Union[str, List[str]]		):






      '''simple docstring'''







      if not isinstance(__lowercase ,					__lowercase		):
       UpperCAmelCase_								=     list(__lowercase		)

      for l in label:
       if l not in self.labels:
        raise ValueError(
            F"""{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}."""		)

      return [self.labels[l] for l in label]





     @torch.no_grad()
     def __call__(						self    :  Union[str, Any] ,					__lowercase    :  List[int] ,					__lowercase    :  float = 4.0 ,					__lowercase    :  Optional[Union[torch.Generator, List[torch.Generator]]] = None ,					__lowercase    :  int = 50 ,					__lowercase    :  Optional[str] = "pil" ,					__lowercase    :  bool = True ,					):






      '''simple docstring'''







      UpperCAmelCase_								=     len(__lowercase		)
      UpperCAmelCase_								=     self.transformer.config.sample_size
      UpperCAmelCase_								=     self.transformer.config.in_channels

      UpperCAmelCase_								=     randn_tensor(
          shape=(batch_size, latent_channels, latent_size, latent_size) ,					generator=__lowercase ,					device=self.device ,					dtype=self.transformer.dtype ,					)
      UpperCAmelCase_								=     torch.cat([latents] * 2		) if guidance_scale > 1 else latents

      UpperCAmelCase_								=     torch.tensor(__lowercase ,					device=self.device		).reshape(-1		)
      UpperCAmelCase_								=     torch.tensor([10_00] * batch_size ,					device=self.device		)
      UpperCAmelCase_								=     torch.cat([class_labels, class_null] ,					0		) if guidance_scale > 1 else class_labels

      # set step values
      self.scheduler.set_timesteps(__lowercase		)

      for t in self.progress_bar(self.scheduler.timesteps		):
       if guidance_scale > 1:
        UpperCAmelCase_								=     latent_model_input[: len(__lowercase		) // 2]
        UpperCAmelCase_								=     torch.cat([half, half] ,					dim=0		)
       UpperCAmelCase_								=     self.scheduler.scale_model_input(__lowercase ,					__lowercase		)

       UpperCAmelCase_								=     t
       if not torch.is_tensor(__lowercase		):
        # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
        # This would be a good case for the `match` statement (Python 3.10+)
        UpperCAmelCase_								=     latent_model_input.device.type == """mps"""
        if isinstance(__lowercase ,					__lowercase		):
         UpperCAmelCase_								=     torch.floataa if is_mps else torch.floataa
        else:
         UpperCAmelCase_								=     torch.intaa if is_mps else torch.intaa
        UpperCAmelCase_								=     torch.tensor([timesteps] ,					dtype=__lowercase ,					device=latent_model_input.device		)
       elif len(timesteps.shape		) == 0:
        UpperCAmelCase_								=     timesteps[None].to(latent_model_input.device		)
       # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
       UpperCAmelCase_								=     timesteps.expand(latent_model_input.shape[0]		)
       # predict noise model_output
       UpperCAmelCase_								=     self.transformer(
           __lowercase ,					timestep=__lowercase ,					class_labels=__lowercase		).sample

       # perform guidance
       if guidance_scale > 1:
        UpperCAmelCase_						,	UpperCAmelCase_								=     noise_pred[:, :latent_channels], noise_pred[:, latent_channels:]
        UpperCAmelCase_						,	UpperCAmelCase_								=     torch.split(__lowercase ,					len(__lowercase		) // 2 ,					dim=0		)

        UpperCAmelCase_								=     uncond_eps + guidance_scale * (cond_eps - uncond_eps)
        UpperCAmelCase_								=     torch.cat([half_eps, half_eps] ,					dim=0		)

        UpperCAmelCase_								=     torch.cat([eps, rest] ,					dim=1		)

       # learned sigma
       if self.transformer.config.out_channels // 2 == latent_channels:
        UpperCAmelCase_						,	UpperCAmelCase_								=     torch.split(__lowercase ,					__lowercase ,					dim=1		)
       else:
        UpperCAmelCase_								=     noise_pred

       # compute previous image: x_t -> x_t-1
       UpperCAmelCase_								=     self.scheduler.step(__lowercase ,					__lowercase ,					__lowercase		).prev_sample

      if guidance_scale > 1:
       UpperCAmelCase_						,	UpperCAmelCase_								=     latent_model_input.chunk(2 ,					dim=0		)
      else:
       UpperCAmelCase_								=     latent_model_input

      UpperCAmelCase_								=     1 / self.vae.config.scaling_factor * latents
      UpperCAmelCase_								=     self.vae.decode(__lowercase		).sample

      UpperCAmelCase_								=     (samples / 2 + 0.5).clamp(0 ,					1		)

      # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
      UpperCAmelCase_								=     samples.cpu().permute(0 ,					2 ,					3 ,					1		).float().numpy()

      if output_type == "pil":
       UpperCAmelCase_								=     self.numpy_to_pil(__lowercase		)

      if not return_dict:
       return (samples,)

      return ImagePipelineOutput(images=__lowercase		)









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







					'''simple docstring'''

					def __init__(						self    :  Optional[int] ,					__lowercase    :  Union[str, Any] ,					__lowercase    :  Optional[int]=13 ,					__lowercase    :  Union[str, Any]=2 ,					__lowercase    :  Union[str, Any]=24 ,					__lowercase    :  Tuple=16 ,					__lowercase    :  Any=True ,					__lowercase    :  List[str]=True ,					__lowercase    :  List[Any]=32 ,					__lowercase    :  Tuple=5 ,					__lowercase    :  List[str]=4 ,					__lowercase    :  Optional[Any]=37 ,					__lowercase    :  Tuple="gelu" ,					__lowercase    :  Any=0.1 ,					__lowercase    :  Optional[int]=0.1 ,					__lowercase    :  Tuple=10 ,					__lowercase    :  List[str]=0.02 ,					__lowercase    :  str=None ,					__lowercase    :  Any=2 ,					__lowercase    :  Optional[int]=2 ,					):






						'''simple docstring'''







						UpperCAmelCase_								=     parent
						UpperCAmelCase_								=     batch_size
						UpperCAmelCase_								=     patch_size
						UpperCAmelCase_								=     max_length
						UpperCAmelCase_								=     num_mel_bins
						UpperCAmelCase_								=     is_training
						UpperCAmelCase_								=     use_labels
						UpperCAmelCase_								=     hidden_size
						UpperCAmelCase_								=     num_hidden_layers
						UpperCAmelCase_								=     num_attention_heads
						UpperCAmelCase_								=     intermediate_size
						UpperCAmelCase_								=     hidden_act
						UpperCAmelCase_								=     hidden_dropout_prob
						UpperCAmelCase_								=     attention_probs_dropout_prob
						UpperCAmelCase_								=     type_sequence_label_size
						UpperCAmelCase_								=     initializer_range
						UpperCAmelCase_								=     scope
						UpperCAmelCase_								=     frequency_stride
						UpperCAmelCase_								=     time_stride

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





					def        SCREAMING_SNAKE_CASE							(						self    :  int		):






						'''simple docstring'''







						UpperCAmelCase_								=     floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]		)

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

						UpperCAmelCase_								=     self.get_config()

						return config, input_values, labels





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''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=__lowercase ,					initializer_range=self.initializer_range ,					frequency_stride=self.frequency_stride ,					time_stride=self.time_stride ,					)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[str] ,					__lowercase    :  int ,					__lowercase    :  Dict ,					__lowercase    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     ASTModel(config=__lowercase		)
						model.to(__lowercase		)
						model.eval()
						UpperCAmelCase_								=     model(__lowercase		)
						self.parent.assertEqual(result.last_hidden_state.shape ,					(self.batch_size, self.seq_length, self.hidden_size)		)





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.prepare_config_and_inputs()
						(
						    (
						    UpperCAmelCase_
						)						,	(
						    UpperCAmelCase_
						)						,	(
						    UpperCAmelCase_
						)						,	
						)								=     config_and_inputs
						UpperCAmelCase_								=     {"""input_values""": input_values}
						return config, inputs_dict







@require_torch
class   _UpperCamelCase  (       A_						,       A_						,       unittest.TestCase  ):







					'''simple docstring'''

					lowerCamelCase     :     Any			    =       (
					    (
					        ASTModel,
					        ASTForAudioClassification,
					    )
					    if is_torch_available()
					    else ()
					)
					lowerCamelCase     :     Optional[Any]			    =       (
					    {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
					    if is_torch_available()
					    else {}
					)
					lowerCamelCase     :     Union[str, Any]			    =       False
					lowerCamelCase     :     Tuple			    =       False
					lowerCamelCase     :     List[str]			    =       False
					lowerCamelCase     :     List[Any]			    =       False





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any] ,					__lowercase    :  Union[str, Any] ,					__lowercase    :  List[str] ,					__lowercase    :  int ,					__lowercase    :  str ,					__lowercase    :  Dict		):






						'''simple docstring'''







						if pipeline_test_casse_name == "AudioClassificationPipelineTests":
							return True

						return False





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_								=     ASTModelTester(self		)
						UpperCAmelCase_								=     ConfigTester(self ,					config_class=__lowercase ,					has_text_modality=__lowercase ,					hidden_size=37		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						self.config_tester.run_common_tests()





					@unittest.skip(reason="""AST does not use inputs_embeds"""		)
					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						pass





					def        SCREAMING_SNAKE_CASE							(						self    :  List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs_for_common()

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





					def        SCREAMING_SNAKE_CASE							(						self    :  Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_						,	UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs_for_common()

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

							UpperCAmelCase_								=     ["""input_values"""]
							self.assertListEqual(arg_names[:1] ,					__lowercase		)





					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__lowercase		)





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  str		):






						'''simple docstring'''







						for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							UpperCAmelCase_								=     ASTModel.from_pretrained(__lowercase		)
							self.assertIsNotNone(__lowercase		)




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

	UpperCAmelCase_						,	UpperCAmelCase_								=     torchaudio.load(A   )

	return audio, sampling_rate







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







					'''simple docstring'''

					@cached_property
					def        SCREAMING_SNAKE_CASE							(						self    :  Any		):






						'''simple docstring'''







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





					@slow
					def        SCREAMING_SNAKE_CASE							(						self    :  Any		):






						'''simple docstring'''







						UpperCAmelCase_								=     self.default_feature_extractor
						UpperCAmelCase_								=     ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""		).to(__lowercase		)

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

						# forward pass
						with torch.no_grad():
							UpperCAmelCase_								=     model(**__lowercase		)

						# verify the logits
						UpperCAmelCase_								=     torch.Size((1, 5_27)		)
						self.assertEqual(outputs.logits.shape ,					__lowercase		)

						UpperCAmelCase_								=     torch.tensor([-0.8760, -7.0042, -8.6602]		).to(__lowercase		)

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


