


import json
import os
import re
import unicodedata
from typing import Dict, List, Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


snake_case__  				=			logging.get_logger(__name__)

snake_case__  				=			{
    'src_vocab_file': 'vocab-src.json',
    'tgt_vocab_file': 'vocab-tgt.json',
    'merges_file': 'merges.txt',
}

snake_case__  				=			{
    'src_vocab_file': {
        'stas/tiny-wmt19-en-de': 'https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/vocab-src.json'
    },
    'tgt_vocab_file': {
        'stas/tiny-wmt19-en-de': 'https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/vocab-tgt.json'
    },
    'merges_file': {'stas/tiny-wmt19-en-de': 'https://huggingface.co/stas/tiny-wmt19-en-de/resolve/main/merges.txt'},
}

snake_case__  				=			{'stas/tiny-wmt19-en-de': 1024}
snake_case__  				=			{
    'stas/tiny-wmt19-en-de': {
        'langs': ['en', 'de'],
        'model_max_length': 1024,
        'special_tokens_map_file': None,
        'full_tokenizer_file': None,
    }
}
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:Optional[Any]					)							->	List[Any]:
						__magic_name__					:				Optional[Any]				=   set()
						__magic_name__					:				List[str]				=   word[0]
						for char in word[1:]:
												pairs.add((prev_char, char)					)
												__magic_name__					:				Union[str, Any]				=   char
						return pairs
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:Optional[Any]					)							->	Tuple:
						__magic_name__					:				List[Any]				=   text.replace('，'   ,    ','					)
						__magic_name__					:				Union[str, Any]				=   re.sub(R'。\s*'   ,    '. '   ,    lowercase__					)
						__magic_name__					:				str				=   text.replace('、'   ,    ','					)
						__magic_name__					:				Union[str, Any]				=   text.replace('”'   ,    '"'					)
						__magic_name__					:				Union[str, Any]				=   text.replace('“'   ,    '"'					)
						__magic_name__					:				Dict				=   text.replace('∶'   ,    ':'					)
						__magic_name__					:				List[str]				=   text.replace('：'   ,    ':'					)
						__magic_name__					:				Optional[Any]				=   text.replace('？'   ,    '?'					)
						__magic_name__					:				Dict				=   text.replace('《'   ,    '"'					)
						__magic_name__					:				Optional[int]				=   text.replace('》'   ,    '"'					)
						__magic_name__					:				str				=   text.replace('）'   ,    ')'					)
						__magic_name__					:				Dict				=   text.replace('！'   ,    '!'					)
						__magic_name__					:				List[Any]				=   text.replace('（'   ,    '('					)
						__magic_name__					:				str				=   text.replace('；'   ,    ';'					)
						__magic_name__					:				List[Any]				=   text.replace('１'   ,    '1'					)
						__magic_name__					:				Union[str, Any]				=   text.replace('」'   ,    '"'					)
						__magic_name__					:				Any				=   text.replace('「'   ,    '"'					)
						__magic_name__					:				int				=   text.replace('０'   ,    '0'					)
						__magic_name__					:				Union[str, Any]				=   text.replace('３'   ,    '3'					)
						__magic_name__					:				Union[str, Any]				=   text.replace('２'   ,    '2'					)
						__magic_name__					:				Optional[int]				=   text.replace('５'   ,    '5'					)
						__magic_name__					:				List[Any]				=   text.replace('６'   ,    '6'					)
						__magic_name__					:				int				=   text.replace('９'   ,    '9'					)
						__magic_name__					:				Any				=   text.replace('７'   ,    '7'					)
						__magic_name__					:				Any				=   text.replace('８'   ,    '8'					)
						__magic_name__					:				Tuple				=   text.replace('４'   ,    '4'					)
						__magic_name__					:				Optional[Any]				=   re.sub(R'．\s*'   ,    '. '   ,    lowercase__					)
						__magic_name__					:				int				=   text.replace('～'   ,    '~'					)
						__magic_name__					:				Optional[Any]				=   text.replace('’'   ,    '\''					)
						__magic_name__					:				int				=   text.replace('…'   ,    '...'					)
						__magic_name__					:				List[Any]				=   text.replace('━'   ,    '-'					)
						__magic_name__					:				List[Any]				=   text.replace('〈'   ,    '<'					)
						__magic_name__					:				List[Any]				=   text.replace('〉'   ,    '>'					)
						__magic_name__					:				Tuple				=   text.replace('【'   ,    '['					)
						__magic_name__					:				int				=   text.replace('】'   ,    ']'					)
						__magic_name__					:				str				=   text.replace('％'   ,    '%'					)
						return text
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:Tuple					)							->	Optional[Any]:
						__magic_name__					:				List[Any]				=   []
						for char in text:
												__magic_name__					:				List[str]				=   unicodedata.category(lowercase__					)
												if cat.startswith('C'					):
																		continue
												output.append(lowercase__					)
						return "".join(lowercase__					)



class      snake_case__	(   _A	):
				__lowerCAmelCase		=   VOCAB_FILES_NAMES
				__lowerCAmelCase		=   PRETRAINED_VOCAB_FILES_MAP
				__lowerCAmelCase		=   PRETRAINED_INIT_CONFIGURATION
				__lowerCAmelCase		=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				__lowerCAmelCase		=   ['''input_ids''', '''attention_mask''']
				def __init__(	self  ,   _UpperCAmelCase=None  ,   _UpperCAmelCase=None  ,   _UpperCAmelCase=None  ,   _UpperCAmelCase=None  ,   _UpperCAmelCase=False  ,   _UpperCAmelCase="<unk>"  ,   _UpperCAmelCase="<s>"  ,   _UpperCAmelCase="</s>"  ,   _UpperCAmelCase="<pad>"  ,   **_UpperCAmelCase  ,   ):




										"""simple docstring"""




										super().__init__(
										    langs=_UpperCAmelCase  ,   src_vocab_file=_UpperCAmelCase  ,   tgt_vocab_file=_UpperCAmelCase  ,   merges_file=_UpperCAmelCase  ,   do_lower_case=_UpperCAmelCase  ,   unk_token=_UpperCAmelCase  ,   bos_token=_UpperCAmelCase  ,   sep_token=_UpperCAmelCase  ,   pad_token=_UpperCAmelCase  ,   **_UpperCAmelCase  ,   )

										try:
																import sacremoses
										except ImportError:
																raise ImportError(
																    'You need to install sacremoses to use XLMTokenizer. '
																    'See https://pypi.org/project/sacremoses/ for installation.'   )

										__magic_name__					:				str				=   sacremoses

										__magic_name__					:				Tuple				=   src_vocab_file
										__magic_name__					:				Optional[int]				=   tgt_vocab_file
										__magic_name__					:				Tuple				=   merges_file
										__magic_name__					:				List[str]				=   do_lower_case

										# cache of sm.MosesPunctNormalizer instance
										__magic_name__					:				Optional[int]				=   {}
										# cache of sm.MosesTokenizer instance
										__magic_name__					:				Union[str, Any]				=   {}
										__magic_name__					:				Tuple				=   {}

										if langs and len(_UpperCAmelCase   ) == 2:
																__magic_name__		,			__magic_name__					:				Dict				=   langs
										else:
																raise ValueError(
																    F"arg `langs` needs to be a list of 2 langs, e.g. ['en', 'ru'], but got {langs}. "
																    'Usually that means that tokenizer can\'t find a mapping for the given model path '
																    'in PRETRAINED_VOCAB_FILES_MAP, and other maps of this tokenizer.'   )

										with open(_UpperCAmelCase  ,   encoding='utf-8'   ) as src_vocab_handle:
																__magic_name__					:				Optional[Any]				=   json.load(_UpperCAmelCase   )
										with open(_UpperCAmelCase  ,   encoding='utf-8'   ) as tgt_vocab_handle:
																__magic_name__					:				str				=   json.load(_UpperCAmelCase   )
																__magic_name__					:				Tuple				=   {v: k for k, v in tgt_vocab.items()}
										with open(_UpperCAmelCase  ,   encoding='utf-8'   ) as merges_handle:
																__magic_name__					:				Tuple				=   merges_handle.read().split('\n'   )[:-1]
										__magic_name__					:				List[str]				=   [tuple(merge.split()[:2]   ) for merge in merges]
										__magic_name__					:				str				=   dict(zip(_UpperCAmelCase  ,   range(len(_UpperCAmelCase   )   )   )   )
										__magic_name__					:				Tuple				=   {}
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										return self.get_src_vocab()
				@property
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										return self.src_vocab_size
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										if lang not in self.cache_moses_punct_normalizer:
																__magic_name__					:				str				=   self.sm.MosesPunctNormalizer(lang=_UpperCAmelCase   )
																__magic_name__					:				List[str]				=   punct_normalizer
										return self.cache_moses_punct_normalizer[lang].normalize(_UpperCAmelCase   )
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										if lang not in self.cache_moses_tokenizer:
																__magic_name__					:				Dict				=   self.sm.MosesTokenizer(lang=_UpperCAmelCase   )
																__magic_name__					:				Tuple				=   moses_tokenizer
										return self.cache_moses_tokenizer[lang].tokenize(
										    _UpperCAmelCase  ,   aggressive_dash_splits=_UpperCAmelCase  ,   return_str=_UpperCAmelCase  ,   escape=_UpperCAmelCase   )
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										if lang not in self.cache_moses_detokenizer:
																__magic_name__					:				Dict				=   self.sm.MosesDetokenizer(lang=_UpperCAmelCase   )
																__magic_name__					:				List[str]				=   moses_detokenizer
										return self.cache_moses_detokenizer[lang].detokenize(_UpperCAmelCase   )
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										__magic_name__					:				Union[str, Any]				=   replace_unicode_punct(_UpperCAmelCase   )
										__magic_name__					:				str				=   self.moses_punct_norm(_UpperCAmelCase  ,   _UpperCAmelCase   )
										__magic_name__					:				List[str]				=   remove_non_printing_char(_UpperCAmelCase   )
										return text
				@property
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										return len(self.encoder   )
				@property
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										return len(self.decoder   )
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										return dict(self.encoder  ,   **self.added_tokens_encoder   )
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										return dict(self.decoder  ,   **self.added_tokens_decoder   )
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										__magic_name__					:				Optional[int]				=   tuple(token[:-1]   ) + (token[-1] + '</w>',)
										if token in self.cache:
																return self.cache[token]
										__magic_name__					:				str				=   get_pairs(_UpperCAmelCase   )

										if not pairs:
																return token + "</w>"

										while True:
																__magic_name__					:				Optional[int]				=   min(_UpperCAmelCase  ,   key=lambda _UpperCAmelCase   : self.bpe_ranks.get(_UpperCAmelCase  ,   float('inf'   )   )   )
																if bigram not in self.bpe_ranks:
																						break
																__magic_name__		,			__magic_name__					:				Optional[int]				=   bigram
																__magic_name__					:				List[Any]				=   []
																__magic_name__					:				Dict				=   0
																while i < len(_UpperCAmelCase   ):
																						try:
																												__magic_name__					:				Dict				=   word.index(_UpperCAmelCase  ,   _UpperCAmelCase   )
																						except ValueError:
																												new_word.extend(word[i:]   )
																												break
																						else:
																												new_word.extend(word[i:j]   )
																												__magic_name__					:				Tuple				=   j

																						if word[i] == first and i < len(_UpperCAmelCase   ) - 1 and word[i + 1] == second:
																												new_word.append(first + second   )
																												i += 2
																						else:
																												new_word.append(word[i]   )
																												i += 1
																__magic_name__					:				Optional[Any]				=   tuple(_UpperCAmelCase   )
																__magic_name__					:				List[Any]				=   new_word
																if len(_UpperCAmelCase   ) == 1:
																						break
																else:
																						__magic_name__					:				Union[str, Any]				=   get_pairs(_UpperCAmelCase   )
										__magic_name__					:				Union[str, Any]				=   ' '.join(_UpperCAmelCase   )
										if word == "\n  </w>":
																__magic_name__					:				Optional[int]				=   '\n</w>'
										__magic_name__					:				Optional[Any]				=   word
										return word
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase="en"  ,   _UpperCAmelCase=False   ):




										"""simple docstring"""




										__magic_name__					:				List[Any]				=   self.src_lang

										if self.do_lower_case:
																__magic_name__					:				Optional[int]				=   text.lower()

										if bypass_tokenizer:
																__magic_name__					:				Any				=   text.split()
										else:
																__magic_name__					:				str				=   self.moses_pipeline(_UpperCAmelCase  ,   lang=_UpperCAmelCase   )
																__magic_name__					:				Any				=   self.moses_tokenize(_UpperCAmelCase  ,   lang=_UpperCAmelCase   )

										__magic_name__					:				Optional[int]				=   []
										for token in text:
																if token:
																						split_tokens.extend(list(self.bpe(_UpperCAmelCase   ).split(' '   )   )   )

										return split_tokens
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										return self.encoder.get(_UpperCAmelCase  ,   self.encoder.get(self.unk_token   )   )
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										return self.decoder.get(_UpperCAmelCase  ,   self.unk_token   )
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										__magic_name__					:				Any				=   [t.replace(' '  ,   ''   ).replace('</w>'  ,   ' '   ) for t in tokens]
										__magic_name__					:				Optional[Any]				=   ''.join(_UpperCAmelCase   ).split()
										# detokenize
										__magic_name__					:				int				=   self.moses_detokenize(_UpperCAmelCase  ,   self.tgt_lang   )
										return text
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase = None   ):




										"""simple docstring"""




										__magic_name__					:				Optional[int]				=   [self.sep_token_id]

										# no bos used in fairseq
										if token_ids_a is None:
																return token_ids_a + sep
										return token_ids_a + sep + token_ids_a + sep
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase = None  ,   _UpperCAmelCase = False   ):




										"""simple docstring"""




										if already_has_special_tokens:
																return super().get_special_tokens_mask(
																    token_ids_a=_UpperCAmelCase  ,   token_ids_a=_UpperCAmelCase  ,   already_has_special_tokens=_UpperCAmelCase   )
										# no bos used in fairseq
										if token_ids_a is not None:
																return ([0] * len(_UpperCAmelCase   )) + [1] + ([0] * len(_UpperCAmelCase   )) + [1]
										return ([0] * len(_UpperCAmelCase   )) + [1]
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase = None   ):




										"""simple docstring"""




										__magic_name__					:				Optional[Any]				=   [self.sep_token_id]

										# no bos used in fairseq
										if token_ids_a is None:
																return len(token_ids_a + sep   ) * [0]
										return len(token_ids_a + sep   ) * [0] + len(token_ids_a + sep   ) * [1]
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase = None   ):




										"""simple docstring"""




										if not os.path.isdir(_UpperCAmelCase   ):
																logger.error(F"Vocabulary path ({save_directory}) should be a directory"   )
																return

										__magic_name__					:				int				=   os.path.join(
										    _UpperCAmelCase  ,   (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['src_vocab_file']   )
										__magic_name__					:				Dict				=   os.path.join(
										    _UpperCAmelCase  ,   (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['tgt_vocab_file']   )
										__magic_name__					:				int				=   os.path.join(
										    _UpperCAmelCase  ,   (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']   )

										with open(_UpperCAmelCase  ,   'w'  ,   encoding='utf-8'   ) as f:
																f.write(json.dumps(self.encoder  ,   indent=2  ,   sort_keys=_UpperCAmelCase  ,   ensure_ascii=_UpperCAmelCase   ) + '\n'   )

										with open(_UpperCAmelCase  ,   'w'  ,   encoding='utf-8'   ) as f:
																__magic_name__					:				Tuple				=   {v: k for k, v in self.decoder.items()}
																f.write(json.dumps(_UpperCAmelCase  ,   indent=2  ,   sort_keys=_UpperCAmelCase  ,   ensure_ascii=_UpperCAmelCase   ) + '\n'   )

										__magic_name__					:				Any				=   0
										with open(_UpperCAmelCase  ,   'w'  ,   encoding='utf-8'   ) as writer:
																for bpe_tokens, token_index in sorted(self.bpe_ranks.items()  ,   key=lambda _UpperCAmelCase   : kv[1]   ):
																						if index != token_index:
																												logger.warning(
																												    F"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."
																												    ' Please check that the tokenizer is not corrupted!'   )
																												__magic_name__					:				Any				=   token_index
																						writer.write(' '.join(_UpperCAmelCase   ) + '\n'   )
																						index += 1

										return src_vocab_file, tgt_vocab_file, merges_file
				def __getstate__(	self   ):




										"""simple docstring"""




										__magic_name__					:				Dict				=   self.__dict__.copy()
										__magic_name__					:				Dict				=   None
										return state





				def __setstate__(	self  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										__magic_name__					:				Union[str, Any]				=   d

										try:
																import sacremoses
										except ImportError:
																raise ImportError(
																    'You need to install sacremoses to use XLMTokenizer. '
																    'See https://pypi.org/project/sacremoses/ for installation.'   )

										__magic_name__					:				int				=   sacremoses






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


snake_case__  				=			'./tests/fixtures/elise_format0.mid'



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




										"""simple docstring"""




										torch.manual_seed(0   )
										__magic_name__					:				Tuple				=   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'  ,   )

										__magic_name__					:				Union[str, Any]				=   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'  ,   )

										__magic_name__					:				Optional[Any]				=   TaFilmDecoder(
										    input_dims=128  ,   targets_length=256  ,   max_decoder_noise_time=20000.0  ,   d_model=768  ,   num_layers=1  ,   num_heads=1  ,   d_kv=4  ,   d_ff=2048  ,   dropout_rate=0.1  ,   )

										__magic_name__					:				Any				=   DDPMScheduler()

										__magic_name__					:				Tuple				=   {
										    'notes_encoder': notes_encoder.eval(),
										    'continuous_encoder': continuous_encoder.eval(),
										    'decoder': decoder.eval(),
										    'scheduler': scheduler,
										    'melgan': None,
										}
										return components
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase=0   ):




										"""simple docstring"""




										if str(_UpperCAmelCase   ).startswith('mps'   ):
																__magic_name__					:				str				=   torch.manual_seed(_UpperCAmelCase   )
										else:
																__magic_name__					:				Optional[int]				=   torch.Generator(device=_UpperCAmelCase   ).manual_seed(_UpperCAmelCase   )
										__magic_name__					:				List[str]				=   {
										    '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"""




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

										__magic_name__					:				List[Any]				=   self.get_dummy_inputs(_UpperCAmelCase   )
										__magic_name__					:				Dict				=   pipe(**_UpperCAmelCase   )
										__magic_name__					:				Optional[Any]				=   output.audios

										__magic_name__					:				Dict				=   mel[0, -3:, -3:]

										assert mel_slice.shape == (3, 3)
										__magic_name__					:				Union[str, Any]				=   np.array(
										    [-11.512925, -4.788215, -0.46172905, -2.051715, -10.539147, -10.970963, -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      snake_case__	(   unittest.TestCase	):
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Tuple				=   torch_device

										__magic_name__					:				Optional[int]				=   SpectrogramDiffusionPipeline.from_pretrained('google/music-spectrogram-diffusion'   )
										__magic_name__					:				Dict				=   pipe.melgan
										__magic_name__					:				int				=   None

										__magic_name__					:				List[str]				=   pipe.to(_UpperCAmelCase   )
										pipe.set_progress_bar_config(disable=_UpperCAmelCase   )

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

										__magic_name__					:				Optional[Any]				=   MidiProcessor()
										__magic_name__					:				str				=   processor(_UpperCAmelCase   )

										__magic_name__					:				Optional[int]				=   input_tokens[:3]
										__magic_name__					:				Optional[Any]				=   torch.manual_seed(0   )
										pipe(_UpperCAmelCase  ,   num_inference_steps=5  ,   generator=_UpperCAmelCase  ,   callback=_UpperCAmelCase  ,   output_type='mel'   )
				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Tuple				=   torch_device

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

										__magic_name__					:				List[Any]				=   processor(_UpperCAmelCase   )
										# just run two denoising loops
										__magic_name__					:				List[Any]				=   input_tokens[:2]

										__magic_name__					:				int				=   torch.manual_seed(0   )
										__magic_name__					:				int				=   pipe(_UpperCAmelCase  ,   num_inference_steps=2  ,   generator=_UpperCAmelCase   )

										__magic_name__					:				List[str]				=   output.audios[0]

										assert abs(np.abs(_UpperCAmelCase   ).sum() - 3612.841   ) < 1E-1





				def 			UpperCamelCase_    (	self   ):




										"""simple docstring"""




										__magic_name__					:				Any				=   torch_device

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

										__magic_name__					:				List[str]				=   MidiProcessor()

										__magic_name__					:				Union[str, Any]				=   processor(_UpperCAmelCase   )

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

										__magic_name__					:				Dict				=   torch.manual_seed(0   )
										__magic_name__					:				Union[str, Any]				=   pipe(_UpperCAmelCase  ,   num_inference_steps=100  ,   generator=_UpperCAmelCase   )

										__magic_name__					:				Dict				=   output.audios[0]
										assert abs(np.abs(_UpperCAmelCase   ).sum() - 9389.1111   ) < 5E-2


