

"""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()


lowerCAmelCase       :				Union[str, Any]         =					"./tests/fixtures/elise_format0.mid"
@unittest.skip('''The note-seq package currently throws an error on import''')
class 	_A						(					lowerCAmelCase_				,       unittest.TestCase):
  SCREAMING_SNAKE_CASE      : int    =					SpectrogramDiffusionPipeline
  SCREAMING_SNAKE_CASE      : List[Any]    =					PipelineTesterMixin.required_optional_params - {
      '''callback''',
      '''latents''',
      '''callback_steps''',
      '''output_type''',
      '''num_images_per_prompt''',
  }
  SCREAMING_SNAKE_CASE      : Any    =					False
  SCREAMING_SNAKE_CASE      : List[Any]    =					False
  SCREAMING_SNAKE_CASE      : List[Any]    =					TOKENS_TO_AUDIO_GENERATION_PARAMS
  SCREAMING_SNAKE_CASE      : List[Any]    =					TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        torch.manual_seed(0   )
        SCREAMING_SNAKE_CASE_			:					Dict          =       SpectrogramNotesEncoder(
            max_length=2048	,   vocab_size=1536	,   d_model=768	,   dropout_rate=0.1	,   num_layers=1	,   num_heads=1	,   d_kv=4	,   d_ff=2048	,   feed_forward_proj='gated-gelu'	,   )

        SCREAMING_SNAKE_CASE_			:					int          =       SpectrogramContEncoder(
            input_dims=128	,   targets_context_length=256	,   d_model=768	,   dropout_rate=0.1	,   num_layers=1	,   num_heads=1	,   d_kv=4	,   d_ff=2048	,   feed_forward_proj='gated-gelu'	,   )

        SCREAMING_SNAKE_CASE_			:					Optional[int]          =       TaFilmDecoder(
            input_dims=128	,   targets_length=256	,   max_decoder_noise_time=2_0000.0	,   d_model=768	,   num_layers=1	,   num_heads=1	,   d_kv=4	,   d_ff=2048	,   dropout_rate=0.1	,   )

        SCREAMING_SNAKE_CASE_			:					str          =       DDPMScheduler()

        SCREAMING_SNAKE_CASE_			:					List[str]          =       {
            'notes_encoder': notes_encoder.eval(),
            'continuous_encoder': continuous_encoder.eval(),
            'decoder': decoder.eval(),
            'scheduler': scheduler,
            'melgan': None,
        }
        return components

  def 	UpperCAmelCase      (			self	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE=0   ):





        """simple docstring"""







        if str(_snake_case   ).startswith('mps'   ):
              SCREAMING_SNAKE_CASE_			:					Dict          =       torch.manual_seed(_snake_case   )
        else:
              SCREAMING_SNAKE_CASE_			:					Optional[Any]          =       torch.Generator(device=_snake_case   ).manual_seed(_snake_case   )
        SCREAMING_SNAKE_CASE_			:					Any          =       {
            'input_tokens': [
                [1134, 90, 1135, 1133, 1080, 112, 1132, 1080, 1133, 1079, 133, 1132, 1079, 1133, 1] + [0] * 2033
            ],
            'generator': generator,
            'num_inference_steps': 4,
            'output_type': 'mel',
        }
        return inputs

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       'cpu'  # ensure determinism for the device-dependent torch.Generator
        SCREAMING_SNAKE_CASE_			:					Any          =       self.get_dummy_components()
        SCREAMING_SNAKE_CASE_			:					List[Any]          =       SpectrogramDiffusionPipeline(**_snake_case   )
        SCREAMING_SNAKE_CASE_			:					Optional[Any]          =       pipe.to(_snake_case   )
        pipe.set_progress_bar_config(disable=_snake_case   )

        SCREAMING_SNAKE_CASE_			:					List[str]          =       self.get_dummy_inputs(_snake_case   )
        SCREAMING_SNAKE_CASE_			:					List[str]          =       pipe(**_snake_case   )
        SCREAMING_SNAKE_CASE_			:					List[str]          =       output.audios

        SCREAMING_SNAKE_CASE_			:					Any          =       mel[0, -3:, -3:]

        assert mel_slice.shape == (3, 3)
        SCREAMING_SNAKE_CASE_			:					List[Any]          =       np.array(
            [-11.51_2925, -4.788215, -0.46172905, -2.051715, -10.53_9147, -10.97_0963, -9.091634, 4.0, 4.0]   )
        assert np.abs(mel_slice.flatten() - expected_slice   ).max() < 1e-2

  @skip_mps
  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        return super().test_save_load_local()

  @skip_mps
  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        return super().test_dict_tuple_outputs_equivalent()

  @skip_mps
  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        return super().test_save_load_optional_components()

  @skip_mps
  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        return super().test_attention_slicing_forward_pass()

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        pass

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        pass



  @skip_mps
  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        return super().test_progress_bar()

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

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       torch_device

        SCREAMING_SNAKE_CASE_			:					str          =       SpectrogramDiffusionPipeline.from_pretrained('google/music-spectrogram-diffusion'   )
        SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       pipe.melgan
        SCREAMING_SNAKE_CASE_			:					str          =       None

        SCREAMING_SNAKE_CASE_			:					Optional[Any]          =       pipe.to(_snake_case   )
        pipe.set_progress_bar_config(disable=_snake_case   )

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

        SCREAMING_SNAKE_CASE_			:					int          =       MidiProcessor()
        SCREAMING_SNAKE_CASE_			:					List[Any]          =       processor(_snake_case   )

        SCREAMING_SNAKE_CASE_			:					Tuple          =       input_tokens[:3]
        SCREAMING_SNAKE_CASE_			:					Optional[int]          =       torch.manual_seed(0   )
        pipe(_snake_case	,   num_inference_steps=5	,   generator=_snake_case	,   callback=_snake_case	,   output_type='mel'   )

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					str          =       torch_device

        SCREAMING_SNAKE_CASE_			:					List[str]          =       SpectrogramDiffusionPipeline.from_pretrained('google/music-spectrogram-diffusion'   )
        SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       pipe.to(_snake_case   )
        pipe.set_progress_bar_config(disable=_snake_case   )
        SCREAMING_SNAKE_CASE_			:					Dict          =       MidiProcessor()

        SCREAMING_SNAKE_CASE_			:					List[Any]          =       processor(_snake_case   )
        # just run two denoising loops
        SCREAMING_SNAKE_CASE_			:					int          =       input_tokens[:2]

        SCREAMING_SNAKE_CASE_			:					str          =       torch.manual_seed(0   )
        SCREAMING_SNAKE_CASE_			:					Optional[int]          =       pipe(_snake_case	,   num_inference_steps=2	,   generator=_snake_case   )

        SCREAMING_SNAKE_CASE_			:					Any          =       output.audios[0]

        assert abs(np.abs(_snake_case   ).sum() - 3612.841   ) < 1e-1



  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					int          =       torch_device

        SCREAMING_SNAKE_CASE_			:					List[Any]          =       SpectrogramDiffusionPipeline.from_pretrained('google/music-spectrogram-diffusion'   )
        SCREAMING_SNAKE_CASE_			:					List[str]          =       pipe.to(_snake_case   )
        pipe.set_progress_bar_config(disable=_snake_case   )

        SCREAMING_SNAKE_CASE_			:					Tuple          =       MidiProcessor()

        SCREAMING_SNAKE_CASE_			:					str          =       processor(_snake_case   )

        # just run 4 denoising loops
        SCREAMING_SNAKE_CASE_			:					int          =       input_tokens[:4]

        SCREAMING_SNAKE_CASE_			:					Tuple          =       torch.manual_seed(0   )
        SCREAMING_SNAKE_CASE_			:					Any          =       pipe(_snake_case	,   num_inference_steps=100	,   generator=_snake_case   )

        SCREAMING_SNAKE_CASE_			:					List[str]          =       output.audios[0]
        assert abs(np.abs(_snake_case   ).sum() - 9389.1111   ) < 5e-2









from collections import defaultdict

def 				A_					(							a					):

      """simple docstring"""



      SCREAMING_SNAKE_CASE_			:					defaultdict[str, int]          =       defaultdict(a					)
      # Creating a dictionary containing count of each word
      for word in sentence.split():
            occurrence[word] += 1
      return occurrence


if __name__ == "__main__":
    for word, count in word_occurrence('INPUT STRING').items():
        print(F'{word}: {count}')






