




'''simple docstring'''
import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


A				: Dict					      =			logging.get_logger(__name__)

A				: Tuple					      =			{
    """facebook/hubert-base-ls960""": """https://huggingface.co/facebook/hubert-base-ls960/resolve/main/config.json""",
    # See all Hubert models at https://huggingface.co/models?filter=hubert
}






class 			SCREAMING_SNAKE_CASE(							__A	):
       snake_case_					:	Optional[Any]       =   """hubert"""

       def __init__(       self   ,						lowerCamelCase__=32   ,						lowerCamelCase__=768   ,						lowerCamelCase__=12   ,						lowerCamelCase__=12   ,						lowerCamelCase__=3072   ,						lowerCamelCase__="gelu"   ,						lowerCamelCase__=0.1   ,						lowerCamelCase__=0.1   ,						lowerCamelCase__=0.1   ,						lowerCamelCase__=True   ,						lowerCamelCase__=0.0   ,						lowerCamelCase__=0.1   ,						lowerCamelCase__=0.1   ,						lowerCamelCase__=0.02   ,						lowerCamelCase__=1E-5   ,						lowerCamelCase__="group"   ,						lowerCamelCase__="gelu"   ,						lowerCamelCase__=(512, 512, 512, 512, 512, 512, 512)   ,						lowerCamelCase__=(5, 2, 2, 2, 2, 2, 2)   ,						lowerCamelCase__=(10, 3, 3, 3, 3, 2, 2)   ,						lowerCamelCase__=False   ,						lowerCamelCase__=128   ,						lowerCamelCase__=16   ,						lowerCamelCase__=False   ,						lowerCamelCase__=True   ,						lowerCamelCase__=0.05   ,						lowerCamelCase__=10   ,						lowerCamelCase__=2   ,						lowerCamelCase__=0.0   ,						lowerCamelCase__=10   ,						lowerCamelCase__=0   ,						lowerCamelCase__="sum"   ,						lowerCamelCase__=False   ,						lowerCamelCase__=False   ,						lowerCamelCase__=256   ,						lowerCamelCase__=0   ,						lowerCamelCase__=1   ,						lowerCamelCase__=2   ,						**lowerCamelCase__   ,						)       ->   Optional[Any]:

           """simple docstring"""



           super().__init__(**lowerCamelCase__   ,						pad_token_id=lowerCamelCase__   ,						bos_token_id=lowerCamelCase__   ,						eos_token_id=lowerCamelCase__	)
           __lowercase     							=		hidden_size
           __lowercase     							=		feat_extract_norm
           __lowercase     							=		feat_extract_activation
           __lowercase     							=		list(lowerCamelCase__	)
           __lowercase     							=		list(lowerCamelCase__	)
           __lowercase     							=		list(lowerCamelCase__	)
           __lowercase     							=		conv_bias
           __lowercase     							=		num_conv_pos_embeddings
           __lowercase     							=		num_conv_pos_embedding_groups
           __lowercase     							=		len(self.conv_dim	)
           __lowercase     							=		num_hidden_layers
           __lowercase     							=		intermediate_size
           __lowercase     							=		hidden_act
           __lowercase     							=		num_attention_heads
           __lowercase     							=		hidden_dropout
           __lowercase     							=		attention_dropout
           __lowercase     							=		activation_dropout
           __lowercase     							=		feat_proj_layer_norm
           __lowercase     							=		feat_proj_dropout
           __lowercase     							=		final_dropout
           __lowercase     							=		layerdrop
           __lowercase     							=		layer_norm_eps
           __lowercase     							=		initializer_range
           __lowercase     							=		vocab_size
           __lowercase     							=		do_stable_layer_norm
           __lowercase     							=		use_weighted_layer_sum
           __lowercase     							=		classifier_proj_size

           if (
               (len(self.conv_stride	) != self.num_feat_extract_layers)
               or (len(self.conv_kernel	) != self.num_feat_extract_layers)
               or (len(self.conv_dim	) != self.num_feat_extract_layers)
           ):
               raise ValueError(
                   """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="""
                   """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="""
                   F' {len(self.conv_dim	)}`, `len(config.conv_stride) = {len(self.conv_stride	)}`,'
                   F' `len(config.conv_kernel) = {len(self.conv_kernel	)}`.'	)

           # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
           __lowercase     							=		apply_spec_augment
           __lowercase     							=		mask_time_prob
           __lowercase     							=		mask_time_length
           __lowercase     							=		mask_time_min_masks
           __lowercase     							=		mask_feature_prob
           __lowercase     							=		mask_feature_length
           __lowercase     							=		mask_feature_min_masks

           # ctc loss
           __lowercase     							=		ctc_loss_reduction
           __lowercase     							=		ctc_zero_infinity




       @property
       def        snake_case__     (       self	)       ->   Optional[Any]:

           """simple docstring"""



           return functools.reduce(operator.mul   ,						self.conv_stride   ,						1	)










'''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				: List[str]					      =			"""./tests/fixtures/elise_format0.mid"""






@unittest.skip("""The note-seq package currently throws an error on import"""	)
class 			SCREAMING_SNAKE_CASE(							__A  , unittest.TestCase	):
       snake_case_					:	List[str]       =   SpectrogramDiffusionPipeline
       snake_case_					:	Any       =   PipelineTesterMixin.required_optional_params - {
           """callback""",
           """latents""",
           """callback_steps""",
           """output_type""",
           """num_images_per_prompt""",
       }
       snake_case_					:	int       =   False
       snake_case_					:	Tuple       =   False
       snake_case_					:	Tuple       =   TOKENS_TO_AUDIO_GENERATION_PARAMS
       snake_case_					:	Optional[int]       =   TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS

       def        snake_case__     (       self	)       ->   Optional[Any]:

           """simple docstring"""



           torch.manual_seed(0	)
           __lowercase     							=		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"""   ,						)

           __lowercase     							=		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"""   ,						)

           __lowercase     							=		TaFilmDecoder(
               input_dims=128   ,						targets_length=256   ,						max_decoder_noise_time=2_00_00.0   ,						d_model=768   ,						num_layers=1   ,						num_heads=1   ,						d_kv=4   ,						d_ff=2048   ,						dropout_rate=0.1   ,						)

           __lowercase     							=		DDPMScheduler()

           __lowercase     							=		{
               """notes_encoder""": notes_encoder.eval(),
               """continuous_encoder""": continuous_encoder.eval(),
               """decoder""": decoder.eval(),
               """scheduler""": scheduler,
               """melgan""": None,
           }
           return components

       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__=0	)       ->   Any:

           """simple docstring"""



           if str(lowerCamelCase__	).startswith("""mps"""	):
               __lowercase     							=		torch.manual_seed(lowerCamelCase__	)
           else:
               __lowercase     							=		torch.Generator(device=lowerCamelCase__	).manual_seed(lowerCamelCase__	)
           __lowercase     							=		{
               """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        snake_case__     (       self	)       ->   str:

           """simple docstring"""



           __lowercase     							=		"""cpu"""  # ensure determinism for the device-dependent torch.Generator
           __lowercase     							=		self.get_dummy_components()
           __lowercase     							=		SpectrogramDiffusionPipeline(**lowerCamelCase__	)
           __lowercase     							=		pipe.to(lowerCamelCase__	)
           pipe.set_progress_bar_config(disable=lowerCamelCase__	)

           __lowercase     							=		self.get_dummy_inputs(lowerCamelCase__	)
           __lowercase     							=		pipe(**lowerCamelCase__	)
           __lowercase     							=		output.audios

           __lowercase     							=		mel[0, -3:, -3:]

           assert mel_slice.shape == (3, 3)
           __lowercase     							=		np.array(
               [-11.51_29_25, -4.78_82_15, -0.46_17_29_05, -2.05_17_15, -10.53_91_47, -10.97_09_63, -9.09_16_34, 4.0, 4.0]	)
           assert np.abs(mel_slice.flatten() - expected_slice	).max() < 1E-2

       @skip_mps
       def        snake_case__     (       self	)       ->   Any:

           """simple docstring"""



           return super().test_save_load_local()

       @skip_mps
       def        snake_case__     (       self	)       ->   Tuple:

           """simple docstring"""



           return super().test_dict_tuple_outputs_equivalent()

       @skip_mps
       def        snake_case__     (       self	)       ->   Any:

           """simple docstring"""



           return super().test_save_load_optional_components()

       @skip_mps
       def        snake_case__     (       self	)       ->   List[str]:

           """simple docstring"""



           return super().test_attention_slicing_forward_pass()

       def        snake_case__     (       self	)       ->   Optional[Any]:

           """simple docstring"""



           pass

       def        snake_case__     (       self	)       ->   Union[str, Any]:

           """simple docstring"""



           pass




       @skip_mps
       def        snake_case__     (       self	)       ->   Optional[Any]:

           """simple docstring"""



           return super().test_progress_bar()






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

       def        snake_case__     (       self	)       ->   Tuple:

           """simple docstring"""



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

       def        snake_case__     (       self	)       ->   List[Any]:

           """simple docstring"""



           __lowercase     							=		torch_device

           __lowercase     							=		SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""	)
           __lowercase     							=		pipe.melgan
           __lowercase     							=		None

           __lowercase     							=		pipe.to(lowerCamelCase__	)
           pipe.set_progress_bar_config(disable=lowerCamelCase__	)

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

           __lowercase     							=		MidiProcessor()
           __lowercase     							=		processor(lowerCamelCase__	)

           __lowercase     							=		input_tokens[:3]
           __lowercase     							=		torch.manual_seed(0	)
           pipe(lowerCamelCase__   ,						num_inference_steps=5   ,						generator=lowerCamelCase__   ,						callback=lowerCamelCase__   ,						output_type="""mel"""	)

       def        snake_case__     (       self	)       ->   Union[str, Any]:

           """simple docstring"""



           __lowercase     							=		torch_device

           __lowercase     							=		SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""	)
           __lowercase     							=		pipe.to(lowerCamelCase__	)
           pipe.set_progress_bar_config(disable=lowerCamelCase__	)
           __lowercase     							=		MidiProcessor()

           __lowercase     							=		processor(lowerCamelCase__	)
           # just run two denoising loops
           __lowercase     							=		input_tokens[:2]

           __lowercase     							=		torch.manual_seed(0	)
           __lowercase     							=		pipe(lowerCamelCase__   ,						num_inference_steps=2   ,						generator=lowerCamelCase__	)

           __lowercase     							=		output.audios[0]

           assert abs(np.abs(lowerCamelCase__	).sum() - 36_12.8_41	) < 1E-1




       def        snake_case__     (       self	)       ->   List[str]:

           """simple docstring"""



           __lowercase     							=		torch_device

           __lowercase     							=		SpectrogramDiffusionPipeline.from_pretrained("""google/music-spectrogram-diffusion"""	)
           __lowercase     							=		pipe.to(lowerCamelCase__	)
           pipe.set_progress_bar_config(disable=lowerCamelCase__	)

           __lowercase     							=		MidiProcessor()

           __lowercase     							=		processor(lowerCamelCase__	)

           # just run 4 denoising loops
           __lowercase     							=		input_tokens[:4]

           __lowercase     							=		torch.manual_seed(0	)
           __lowercase     							=		pipe(lowerCamelCase__   ,						num_inference_steps=100   ,						generator=lowerCamelCase__	)

           __lowercase     							=		output.audios[0]
           assert abs(np.abs(lowerCamelCase__	).sum() - 93_89.11_11	) < 5E-2




