
'''simple docstring'''
from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import numpy as np
  import tensorflow as tf

  from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
  from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import MobileViTImageProcessor






class 				UpperCAmelCase_			(		snake_case__   ):





 def     snake_case__						(      self):
     snake_case_	:      Optional[Any]            =  self.config_class(**self.inputs_dict)
     self.parent.assertTrue(hasattr(lowercase_	,    "hidden_sizes"))
     self.parent.assertTrue(hasattr(lowercase_	,    "neck_hidden_sizes"))
     self.parent.assertTrue(hasattr(lowercase_	,    "num_attention_heads"))






class 				UpperCAmelCase_			:





 def __init__(      self	,    lowercase_	,    lowercase_=13	,    lowercase_=32	,    lowercase_=2	,    lowercase_=3	,    lowercase_=6_40	,    lowercase_=4	,    lowercase_="silu"	,    lowercase_=3	,    lowercase_=32	,    lowercase_=0.1	,    lowercase_=0.1	,    lowercase_=0.1	,    lowercase_=0.02	,    lowercase_=True	,    lowercase_=True	,    lowercase_=10	,    lowercase_=None	,    ):
     snake_case_	:      str            =  parent
     snake_case_	:      Optional[int]            =  batch_size
     snake_case_	:      Any            =  image_size
     snake_case_	:      List[Any]            =  patch_size
     snake_case_	:      Optional[Any]            =  num_channels
     snake_case_	:      List[Any]            =  last_hidden_size
     snake_case_	:      Union[str, Any]            =  num_attention_heads
     snake_case_	:      int            =  hidden_act
     snake_case_	:      Union[str, Any]            =  conv_kernel_size
     snake_case_	:      Tuple            =  output_stride
     snake_case_	:      Any            =  hidden_dropout_prob
     snake_case_	:      List[Any]            =  attention_probs_dropout_prob
     snake_case_	:      List[str]            =  classifier_dropout_prob
     snake_case_	:      str            =  use_labels
     snake_case_	:      List[Any]            =  is_training
     snake_case_	:      List[Any]            =  num_labels
     snake_case_	:      Optional[int]            =  initializer_range
     snake_case_	:      Union[str, Any]            =  scope





 def     snake_case__						(      self):
     snake_case_	:      str            =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

     snake_case_	:      Dict            =  None
     snake_case_	:      Any            =  None
     if self.use_labels:
         snake_case_	:      Dict            =  ids_tensor([self.batch_size]	,    self.num_labels)
         snake_case_	:      Optional[Any]            =  ids_tensor([self.batch_size, self.image_size, self.image_size]	,    self.num_labels)

     snake_case_	:      Tuple            =  self.get_config()

     return config, pixel_values, labels, pixel_labels





 def     snake_case__						(      self):
     return MobileViTConfig(
         image_size=self.image_size	,    patch_size=self.patch_size	,    num_channels=self.num_channels	,    num_attention_heads=self.num_attention_heads	,    hidden_act=self.hidden_act	,    conv_kernel_size=self.conv_kernel_size	,    output_stride=self.output_stride	,    hidden_dropout_prob=self.hidden_dropout_prob	,    attention_probs_dropout_prob=self.attention_probs_dropout_prob	,    classifier_dropout_prob=self.classifier_dropout_prob	,    initializer_range=self.initializer_range	,    )





 def     snake_case__						(      self	,    lowercase_	,    lowercase_	,    lowercase_	,    lowercase_):
     snake_case_	:      Union[str, Any]            =  TFMobileViTModel(config=lowercase_)
     snake_case_	:      Dict            =  model(lowercase_	,    training=lowercase_)
     snake_case_	:      Any            =  self.image_size // self.output_stride
     self.parent.assertEqual(
         result.last_hidden_state.shape	,    (self.batch_size, self.last_hidden_size, expected_height, expected_width))





 def     snake_case__						(      self	,    lowercase_	,    lowercase_	,    lowercase_	,    lowercase_):
     snake_case_	:      Optional[int]            =  self.num_labels
     snake_case_	:      int            =  TFMobileViTForImageClassification(lowercase_)
     snake_case_	:      Union[str, Any]            =  model(lowercase_	,    labels=lowercase_	,    training=lowercase_)
     self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_labels))





 def     snake_case__						(      self	,    lowercase_	,    lowercase_	,    lowercase_	,    lowercase_):
     snake_case_	:      List[str]            =  self.num_labels
     snake_case_	:      Optional[int]            =  TFMobileViTForSemanticSegmentation(lowercase_)
     snake_case_	:      Any            =  self.image_size // self.output_stride

     snake_case_	:      Union[str, Any]            =  model(lowercase_	,    training=lowercase_)
     self.parent.assertEqual(
         result.logits.shape	,    (self.batch_size, self.num_labels, expected_height, expected_width))

     snake_case_	:      Tuple            =  model(lowercase_	,    labels=lowercase_	,    training=lowercase_)
     self.parent.assertEqual(
         result.logits.shape	,    (self.batch_size, self.num_labels, expected_height, expected_width))





 def     snake_case__						(      self):
     snake_case_	:      List[str]            =  self.prepare_config_and_inputs()
     snake_case_     ,	snake_case_     ,	snake_case_     ,	snake_case_	:      Any            =  config_and_inputs
     snake_case_	:      Dict            =  {"pixel_values": pixel_values}
     return config, inputs_dict






@require_tf
class 				UpperCAmelCase_			(		snake_case__      ,  snake_case__      ,  unittest.TestCase   ):
 UpperCAmelCase_						      =  (
     (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
     if is_tf_available()
     else ()
 )
 UpperCAmelCase_						      =  (
     {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
     if is_tf_available()
     else {}
 )

 UpperCAmelCase_						      =  False
 UpperCAmelCase_						      =  False
 UpperCAmelCase_						      =  False
 UpperCAmelCase_						      =  False
 UpperCAmelCase_						      =  False





 def     snake_case__						(      self):
     snake_case_	:      List[Any]            =  TFMobileViTModelTester(self)
     snake_case_	:      Tuple            =  TFMobileViTConfigTester(self	,    config_class=lowercase_	,    has_text_modality=lowercase_)





 def     snake_case__						(      self):
     self.config_tester.run_common_tests()





 @unittest.skip(reason="MobileViT does not use inputs_embeds")
 def     snake_case__						(      self):
     pass





 @unittest.skip(reason="MobileViT does not support input and output embeddings")
 def     snake_case__						(      self):
     pass





 @unittest.skip(reason="MobileViT does not output attentions")
 def     snake_case__						(      self):
     pass





 def     snake_case__						(      self):
     snake_case_     ,	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(lowercase_)
         snake_case_	:      List[Any]            =  inspect.signature(model.call)
         # signature.parameters is an OrderedDict => so arg_names order is deterministic
         snake_case_	:      Optional[int]            =  [*signature.parameters.keys()]

         snake_case_	:      Tuple            =  ["pixel_values"]
         self.assertListEqual(arg_names[:1]	,    lowercase_)





 def     snake_case__						(      self):
     snake_case_	:      Any            =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_)





 def     snake_case__						(      self):
     def check_hidden_states_output(lowercase_	,    lowercase_	,    lowercase_):
         snake_case_	:      int            =  model_class(lowercase_)

         snake_case_	:      Union[str, Any]            =  model(**self._prepare_for_class(lowercase_	,    lowercase_))

         snake_case_	:      Optional[Any]            =  outputs.hidden_states

         snake_case_	:      int            =  5
         self.assertEqual(len(lowercase_)	,    lowercase_)

         # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
         # with the width and height being successively divided by 2.
         snake_case_	:      Any            =  2
         for i in range(len(lowercase_)):
             self.assertListEqual(
                 list(hidden_states[i].shape[-2:])	,    [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]	,    )
             divisor *= 2

         self.assertEqual(self.model_tester.output_stride	,    divisor // 2)

     snake_case_     ,	snake_case_	:      int            =  self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         snake_case_	:      Optional[int]            =  True
         check_hidden_states_output(lowercase_	,    lowercase_	,    lowercase_)

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         snake_case_	:      int            =  True

         check_hidden_states_output(lowercase_	,    lowercase_	,    lowercase_)





 def     snake_case__						(      self):
     snake_case_	:      str            =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowercase_)





 def     snake_case__						(      self):
     snake_case_	:      Optional[Any]            =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_semantic_segmentation(*lowercase_)





 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0	,    reason="TF does not support backprop for grouped convolutions on CPU."	,    )
 def     snake_case__						(      self):
     super().test_dataset_conversion()





 def     snake_case__						(      self	,    lowercase_	,    lowercase_	,    lowercase_=2E-1	,    lowercase_=2E-1):
     self.assertTrue(np.allclose(lowercase_	,    lowercase_	,    atol=lowercase_	,    rtol=lowercase_))





 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0	,    reason="TF does not support backprop for grouped convolutions on CPU."	,    )
 @slow
 def     snake_case__						(      self):
     snake_case_     ,	snake_case_	:      Dict            =  self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
         # Since `TFMobileViTModel` cannot operate with the default `fit()` method.
         if model_class.__name__ != "TFMobileViTModel":
             snake_case_	:      Dict            =  model_class(lowercase_)
             if getattr(lowercase_	,    "hf_compute_loss"	,    lowercase_):
                 super().test_keras_fit()





 def     snake_case__						(      self):
     snake_case_     ,	snake_case_	:      Any            =  self.model_tester.prepare_config_and_inputs_for_common()
     for model_class in self.all_model_classes:
         # set an ignore index to correctly test the masked loss used in
         # `TFMobileViTForSemanticSegmentation`.
         if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
             snake_case_	:      Tuple            =  5

         snake_case_	:      Tuple            =  model_class(lowercase_)
         if getattr(lowercase_	,    "hf_compute_loss"	,    lowercase_):
             # The number of elements in the loss should be the same as the number of elements in the label
             snake_case_	:      List[str]            =  self._prepare_for_class(inputs_dict.copy()	,    lowercase_	,    return_labels=lowercase_)
             snake_case_	:      Any            =  prepared_for_class[
                 sorted(prepared_for_class.keys() - inputs_dict.keys()	,    reverse=lowercase_)[0]
             ]
             snake_case_	:      Any            =  added_label.shape.as_list()[:1]

             # Test that model correctly compute the loss with kwargs
             snake_case_	:      Dict            =  self._prepare_for_class(inputs_dict.copy()	,    lowercase_	,    return_labels=lowercase_)
             snake_case_	:      Tuple            =  {"input_ids", "pixel_values", "input_features"}
             snake_case_	:      Optional[Any]            =  possible_input_names.intersection(set(lowercase_)).pop()
             snake_case_	:      Optional[Any]            =  prepared_for_class.pop(lowercase_)

             snake_case_	:      Any            =  model(lowercase_	,    **lowercase_)[0]
             self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])

             # Test that model correctly compute the loss when we mask some positions
             snake_case_	:      Union[str, Any]            =  self._prepare_for_class(inputs_dict.copy()	,    lowercase_	,    return_labels=lowercase_)
             snake_case_	:      List[str]            =  {"input_ids", "pixel_values", "input_features"}
             snake_case_	:      str            =  possible_input_names.intersection(set(lowercase_)).pop()
             snake_case_	:      Dict            =  prepared_for_class.pop(lowercase_)
             if "labels" in prepared_for_class:
                 snake_case_	:      Dict            =  prepared_for_class["labels"].numpy()
                 if len(labels.shape) > 1 and labels.shape[1] != 1:
                     # labels[0] = -100
                     snake_case_	:      int            =  tf.convert_to_tensor(lowercase_)
                     snake_case_	:      Optional[int]            =  model(lowercase_	,    **lowercase_)[0]
                     self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])
                     self.assertTrue(not np.any(np.isnan(loss.numpy())))

                # Test that model correctly compute the loss with a dict
             snake_case_	:      int            =  self._prepare_for_class(inputs_dict.copy()	,    lowercase_	,    return_labels=lowercase_)
             snake_case_	:      Optional[int]            =  model(lowercase_)[0]
             self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])

             # Test that model correctly compute the loss with a tuple
             snake_case_	:      List[str]            =  self._prepare_for_class(inputs_dict.copy()	,    lowercase_	,    return_labels=lowercase_)

             # Get keys that were added with the _prepare_for_class function
             snake_case_	:      str            =  prepared_for_class.keys() - inputs_dict.keys()
             snake_case_	:      Union[str, Any]            =  inspect.signature(model.call).parameters
             snake_case_	:      List[Any]            =  list(signature.keys())

             # Create a dictionary holding the location of the tensors in the tuple
             snake_case_	:      int            =  {0: input_name}
             for label_key in label_keys:
                 snake_case_	:      Any            =  signature_names.index(lowercase_)
                 snake_case_	:      Dict            =  label_key
             snake_case_	:      Dict            =  sorted(tuple_index_mapping.items())
             # Initialize a list with their default values, update the values and convert to a tuple
             snake_case_	:      Optional[Any]            =  []

             for name in signature_names:
                 if name != "kwargs":
                     list_input.append(signature[name].default)

             for index, value in sorted_tuple_index_mapping:
                 snake_case_	:      int            =  prepared_for_class[value]

             snake_case_	:      Optional[int]            =  tuple(lowercase_)

             # Send to model
             snake_case_	:      str            =  model(tuple_input[:-1])[0]

             self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])





 @slow
 def     snake_case__						(      self):
     for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         snake_case_	:      Any            =  TFMobileViTModel.from_pretrained(lowercase_)
         self.assertIsNotNone(lowercase_)


def   UpperCamelCase_       (		):
    """simple docstring"""






    snake_case_	:      Dict            =  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
    return image






@require_tf
class 				UpperCAmelCase_			(		unittest.TestCase   ):





 @slow
 def     snake_case__						(      self):
     snake_case_	:      int            =  TFMobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small")

     snake_case_	:      Tuple            =  MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small")
     snake_case_	:      List[str]            =  prepare_img()
     snake_case_	:      List[str]            =  image_processor(images=lowercase_	,    return_tensors="tf")

     # forward pass
     snake_case_	:      int            =  model(**lowercase_	,    training=lowercase_)

     # verify the logits
     snake_case_	:      str            =  tf.TensorShape((1, 10_00))
     self.assertEqual(outputs.logits.shape	,    lowercase_)

     snake_case_	:      List[str]            =  tf.constant([-1.9_364, -1.2_327, -0.4_653])

     tf.debugging.assert_near(outputs.logits[0, :3]	,    lowercase_	,    atol=1E-4	,    rtol=1E-04)





 @slow
 def     snake_case__						(      self):
     # `from_pt` will be removed
     snake_case_	:      Union[str, Any]            =  TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

     snake_case_	:      Optional[Any]            =  MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

     snake_case_	:      Any            =  prepare_img()
     snake_case_	:      Dict            =  image_processor(images=lowercase_	,    return_tensors="tf")

     # forward pass
     snake_case_	:      int            =  model(inputs.pixel_values	,    training=lowercase_)
     snake_case_	:      List[Any]            =  outputs.logits

     # verify the logits
     snake_case_	:      List[str]            =  tf.TensorShape((1, 21, 32, 32))
     self.assertEqual(logits.shape	,    lowercase_)

     snake_case_	:      List[str]            =  tf.constant(
         [
             [[6.9_713, 6.9_786, 7.2_422], [7.2_893, 7.2_825, 7.4_446], [7.6_580, 7.8_797, 7.9_420]],
             [[-10.6_869, -10.3_250, -10.3_471], [-10.4_228, -9.9_868, -9.7_132], [-11.0_405, -11.0_221, -10.7_318]],
             [[-3.3_089, -2.8_539, -2.6_740], [-3.2_706, -2.5_621, -2.5_108], [-3.2_534, -2.6_615, -2.6_651]],
         ])

     tf.debugging.assert_near(logits[0, :3, :3, :3]	,    lowercase_	,    rtol=1E-4	,    atol=1E-4)






'''simple docstring'''
import gc
import unittest

import numpy as np
import torch

from diffusers import DDPMScheduler, MidiProcessor, SpectrogramDiffusionPipeline
from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder
from diffusers.utils import require_torch_gpu, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_note_seq, require_onnxruntime

from ..pipeline_params import TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS, TOKENS_TO_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


a_     =  "./tests/fixtures/elise_format0.mid"






@unittest.skip("""The note-seq package currently throws an error on import"""   )
class 				UpperCAmelCase_			(		snake_case__      ,  unittest.TestCase   ):
 UpperCAmelCase_						      =  SpectrogramDiffusionPipeline
 UpperCAmelCase_						      =  PipelineTesterMixin.required_optional_params - {
     """callback""",
     """latents""",
     """callback_steps""",
     """output_type""",
     """num_images_per_prompt""",
 }
 UpperCAmelCase_						      =  False
 UpperCAmelCase_						      =  False
 UpperCAmelCase_						      =  TOKENS_TO_AUDIO_GENERATION_PARAMS
 UpperCAmelCase_						      =  TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS





 def     snake_case__						(      self):
     torch.manual_seed(0)
     snake_case_	:      List[str]            =  SpectrogramNotesEncoder(
         max_length=20_48	,    vocab_size=15_36	,    d_model=7_68	,    dropout_rate=0.1	,    num_layers=1	,    num_heads=1	,    d_kv=4	,    d_ff=20_48	,    feed_forward_proj="gated-gelu"	,    )

     snake_case_	:      int            =  SpectrogramContEncoder(
         input_dims=1_28	,    targets_context_length=2_56	,    d_model=7_68	,    dropout_rate=0.1	,    num_layers=1	,    num_heads=1	,    d_kv=4	,    d_ff=20_48	,    feed_forward_proj="gated-gelu"	,    )

     snake_case_	:      Tuple            =  TaFilmDecoder(
         input_dims=1_28	,    targets_length=2_56	,    max_decoder_noise_time=20_000.0	,    d_model=7_68	,    num_layers=1	,    num_heads=1	,    d_kv=4	,    d_ff=20_48	,    dropout_rate=0.1	,    )

     snake_case_	:      Union[str, Any]            =  DDPMScheduler()

     snake_case_	:      List[Any]            =  {
         "notes_encoder": notes_encoder.eval(),
         "continuous_encoder": continuous_encoder.eval(),
         "decoder": decoder.eval(),
         "scheduler": scheduler,
         "melgan": None,
     }
     return components





 def     snake_case__						(      self	,    lowercase_	,    lowercase_=0):
     if str(lowercase_).startswith("mps"):
         snake_case_	:      Dict            =  torch.manual_seed(lowercase_)
     else:
         snake_case_	:      Dict            =  torch.Generator(device=lowercase_).manual_seed(lowercase_)
     snake_case_	:      int            =  {
         "input_tokens": [
             [11_34, 90, 11_35, 11_33, 10_80, 1_12, 11_32, 10_80, 11_33, 10_79, 1_33, 11_32, 10_79, 11_33, 1] + [0] * 20_33
         ],
         "generator": generator,
         "num_inference_steps": 4,
         "output_type": "mel",
     }
     return inputs





 def     snake_case__						(      self):
     snake_case_	:      List[Any]            =  "cpu"  # ensure determinism for the device-dependent torch.Generator
     snake_case_	:      List[Any]            =  self.get_dummy_components()
     snake_case_	:      Tuple            =  SpectrogramDiffusionPipeline(**lowercase_)
     snake_case_	:      Tuple            =  pipe.to(lowercase_)
     pipe.set_progress_bar_config(disable=lowercase_)

     snake_case_	:      List[str]            =  self.get_dummy_inputs(lowercase_)
     snake_case_	:      Any            =  pipe(**lowercase_)
     snake_case_	:      str            =  output.audios

     snake_case_	:      str            =  mel[0, -3:, -3:]

     assert mel_slice.shape == (3, 3)
     snake_case_	:      Any            =  np.array(
         [-11.512_925, -4.788_215, -0.46_172_905, -2.051_715, -10.539_147, -10.970_963, -9.091_634, 4.0, 4.0])
     assert np.abs(mel_slice.flatten() - expected_slice).max() < 1E-2





 @skip_mps
 def     snake_case__						(      self):
     return super().test_save_load_local()





 @skip_mps
 def     snake_case__						(      self):
     return super().test_dict_tuple_outputs_equivalent()





 @skip_mps
 def     snake_case__						(      self):
     return super().test_save_load_optional_components()





 @skip_mps
 def     snake_case__						(      self):
     return super().test_attention_slicing_forward_pass()





 def     snake_case__						(      self):
     pass





 def     snake_case__						(      self):
     pass





 @skip_mps
 def     snake_case__						(      self):
     return super().test_progress_bar()






@slow
@require_torch_gpu
@require_onnxruntime
@require_note_seq
class 				UpperCAmelCase_			(		unittest.TestCase   ):





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





 def     snake_case__						(      self):
     # TODO - test that pipeline can decode tokens in a callback
     # so that music can be played live
     snake_case_	:      Any            =  torch_device

     snake_case_	:      str            =  SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion")
     snake_case_	:      Tuple            =  pipe.melgan
     snake_case_	:      List[str]            =  None

     snake_case_	:      int            =  pipe.to(lowercase_)
     pipe.set_progress_bar_config(disable=lowercase_)

     def callback(lowercase_	,    lowercase_):
         # decode mel to audio
         snake_case_	:      Dict            =  melgan(input_features=mel_output.astype(np.floataa))[0]
         assert len(audio[0]) == 8_19_20 * (step + 1)
         # simulate that audio is played
         return audio

     snake_case_	:      Tuple            =  MidiProcessor()
     snake_case_	:      int            =  processor(lowercase_)

     snake_case_	:      int            =  input_tokens[:3]
     snake_case_	:      Union[str, Any]            =  torch.manual_seed(0)
     pipe(lowercase_	,    num_inference_steps=5	,    generator=lowercase_	,    callback=lowercase_	,    output_type="mel")





 def     snake_case__						(      self):
     snake_case_	:      Any            =  torch_device

     snake_case_	:      Optional[Any]            =  SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion")
     snake_case_	:      Optional[int]            =  pipe.to(lowercase_)
     pipe.set_progress_bar_config(disable=lowercase_)
     snake_case_	:      Union[str, Any]            =  MidiProcessor()

     snake_case_	:      List[str]            =  processor(lowercase_)
     # just run two denoising loops
     snake_case_	:      int            =  input_tokens[:2]

     snake_case_	:      Optional[Any]            =  torch.manual_seed(0)
     snake_case_	:      Tuple            =  pipe(lowercase_	,    num_inference_steps=2	,    generator=lowercase_)

     snake_case_	:      Optional[Any]            =  output.audios[0]

     assert abs(np.abs(lowercase_).sum() - 3_612.841) < 1E-1





 def     snake_case__						(      self):
     snake_case_	:      Union[str, Any]            =  torch_device

     snake_case_	:      Tuple            =  SpectrogramDiffusionPipeline.from_pretrained("google/music-spectrogram-diffusion")
     snake_case_	:      Optional[Any]            =  pipe.to(lowercase_)
     pipe.set_progress_bar_config(disable=lowercase_)

     snake_case_	:      Tuple            =  MidiProcessor()

     snake_case_	:      int            =  processor(lowercase_)

     # just run 4 denoising loops
     snake_case_	:      Any            =  input_tokens[:4]

     snake_case_	:      Optional[Any]            =  torch.manual_seed(0)
     snake_case_	:      Tuple            =  pipe(lowercase_	,    num_inference_steps=1_00	,    generator=lowercase_)

     snake_case_	:      Tuple            =  output.audios[0]
     assert abs(np.abs(lowercase_).sum() - 9_389.1_111) < 5E-2




