code: 
  
  
  
  
  
  import os
  from argparse import ArgumentParser
  from pathlib import Path
  from shutil import copyfile
  from typing import List
  
  from datasets import config
  from datasets.builder import DatasetBuilder
  from datasets.commands import BaseDatasetsCLICommand
  from datasets.download.download_config import DownloadConfig
  from datasets.download.download_manager import DownloadMode
  from datasets.load import dataset_module_factory, import_main_class
  from datasets.utils.info_utils import VerificationMode
  
  
  def 		_SCREAMING_SNAKE_CASE    (   lowerCAmelCase__       ,**lowerCAmelCase__	):
  		return RunBeamCommand(
  		    args.dataset       ,args.name       ,args.cache_dir       ,args.beam_pipeline_options       ,args.data_dir       ,args.all_configs       ,args.save_info or args.save_infos       ,args.ignore_verifications       ,args.force_redownload       ,**lowerCAmelCase__       ,)
  
  
  
  
  
  
  class 	UpperCamelCase_     (     snake_case__       ):
  
  
  
  					@staticmethod
  					def      __a    (		lowerCamelCase    :    ArgumentParser	):
  							lowerCamelCase_  :    Tuple   	=			parser.add_parser('run_beam'					,			help='Run a Beam dataset processing pipeline'	)
  							run_beam_parser.add_argument('dataset'					,			type=lowerCamelCase					,			help='Name of the dataset to download'	)
  							run_beam_parser.add_argument('--name'					,			type=lowerCamelCase					,			default=lowerCamelCase					,			help='Dataset config name'	)
  							run_beam_parser.add_argument(
  							    '--cache_dir'					,			type=lowerCamelCase					,			default=lowerCamelCase					,			help='Cache directory where the datasets are stored'					,			)
  							run_beam_parser.add_argument(
  							    '--beam_pipeline_options'					,			type=lowerCamelCase					,			default=''					,			help='Beam pipeline options, separated by commas. Example:: `--beam_pipeline_options=job_name=my-job,project=my-project`'					,			)
  							run_beam_parser.add_argument(
  							    '--data_dir'					,			type=lowerCamelCase					,			default=lowerCamelCase					,			help='Can be used to specify a manual directory to get the files from'					,			)
  							run_beam_parser.add_argument('--all_configs'					,			action='store_true'					,			help='Test all dataset configurations'	)
  							run_beam_parser.add_argument('--save_info'					,			action='store_true'					,			help='Save the dataset infos file'	)
  							run_beam_parser.add_argument(
  							    '--ignore_verifications'					,			action='store_true'					,			help='Run the test without checksums and splits checks'	)
  							run_beam_parser.add_argument('--force_redownload'					,			action='store_true'					,			help='Force dataset redownload'	)
  							# aliases
  							run_beam_parser.add_argument('--save_infos'					,			action='store_true'					,			help='alias for save_info'	)
  							run_beam_parser.set_defaults(func=lowerCamelCase	)
  
  
  
  					def __init__(		self    :    Optional[Any]					,			lowerCamelCase    :    str					,			lowerCamelCase    :    str					,			lowerCamelCase    :    str					,			lowerCamelCase    :    str					,			lowerCamelCase    :    str					,			lowerCamelCase    :    bool					,			lowerCamelCase    :    bool					,			lowerCamelCase    :    bool					,			lowerCamelCase    :    bool					,			**lowerCamelCase    :    Any					,			):
  							lowerCamelCase_  :    int   	=			dataset
  							lowerCamelCase_  :    List[Any]   	=			name
  							lowerCamelCase_  :    List[Any]   	=			cache_dir
  							lowerCamelCase_  :    str   	=			beam_pipeline_options
  							lowerCamelCase_  :    Any   	=			data_dir
  							lowerCamelCase_  :    int   	=			all_configs
  							lowerCamelCase_  :    int   	=			save_infos
  							lowerCamelCase_  :    Optional[int]   	=			ignore_verifications
  							lowerCamelCase_  :    List[Any]   	=			force_redownload
  							lowerCamelCase_  :    Optional[Any]   	=			config_kwargs
  
  
  
  
  
  					def      __a    (		self    :    Optional[int]	):
  							import apache_beam as beam
  
  							if self._name is not None and self._all_configs:
  									print('Both parameters `name` and `all_configs` can\'t be used at once.'	)
  									exit(1	)
  							lowerCamelCase_	,			lowerCamelCase_  :    List[Any]   	=			self._dataset, self._name
  							lowerCamelCase_  :    List[Any]   	=			dataset_module_factory(lowerCamelCase	)
  							lowerCamelCase_  :    Optional[int]   	=			import_main_class(dataset_module.module_path	)
  							lowerCamelCase_  :    List[DatasetBuilder]   	=			[]
  							if self._beam_pipeline_options:
  									lowerCamelCase_  :    str   	=			beam.options.pipeline_options.PipelineOptions(
  									    flags=[F"--{opt.strip()}" for opt in self._beam_pipeline_options.split(','	) if opt]	)
  							else:
  									lowerCamelCase_  :    Tuple   	=			None
  							if self._all_configs and len(builder_cls.BUILDER_CONFIGS	) > 0:
  									for builder_config in builder_cls.BUILDER_CONFIGS:
  											builders.append(
  											    builder_cls(
  											        config_name=builder_config.name					,			data_dir=self._data_dir					,			hash=dataset_module.hash					,			beam_options=lowerCamelCase					,			cache_dir=self._cache_dir					,			base_path=dataset_module.builder_kwargs.get('base_path'	)					,			)	)
  							else:
  									builders.append(
  									    builder_cls(
  									        config_name=lowerCamelCase					,			data_dir=self._data_dir					,			beam_options=lowerCamelCase					,			cache_dir=self._cache_dir					,			base_path=dataset_module.builder_kwargs.get('base_path'	)					,			**self._config_kwargs					,			)	)
  
  							for builder in builders:
  									builder.download_and_prepare(
  									    download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
  									    if not self._force_redownload
  									    else DownloadMode.FORCE_REDOWNLOAD					,			download_config=DownloadConfig(cache_dir=config.DOWNLOADED_DATASETS_PATH	)					,			verification_mode=VerificationMode.NO_CHECKS
  									    if self._ignore_verifications
  									    else VerificationMode.ALL_CHECKS					,			try_from_hf_gcs=lowerCamelCase					,			)
  									if self._save_infos:
  											builder._save_infos()
  
  							print('Apache beam run successful.'	)
  
  							# If save_infos=True, the dataset infos file is created next to the loaded module file.
  							# Let's move it to the original directory of the dataset script, to allow the user to
  							# upload them on S3 at the same time afterwards.
  							if self._save_infos:
  									lowerCamelCase_  :    Tuple   	=			os.path.join(builder_cls.get_imported_module_dir()					,			config.DATASETDICT_INFOS_FILENAME	)
  
  									lowerCamelCase_  :    str   	=			Path(lowerCamelCase	).name + '.py'
  
  									lowerCamelCase_  :    List[str]   	=			os.path.join(lowerCamelCase					,			lowerCamelCase	)
  									if os.path.isfile(lowerCamelCase	):
  											lowerCamelCase_  :    List[str]   	=			os.path.dirname(lowerCamelCase	)
  									elif os.path.isfile(lowerCamelCase	):
  											lowerCamelCase_  :    Tuple   	=			path
  									else:  # in case of a remote dataset
  											print(F"Dataset Infos file saved at {dataset_infos_path}"	)
  											exit(1	)
  
  									# Move datasetinfo back to the user
  									lowerCamelCase_  :    Tuple   	=			os.path.join(lowerCamelCase					,			config.DATASETDICT_INFOS_FILENAME	)
  									copyfile(lowerCamelCase					,			lowerCamelCase	)
  									print(F"Dataset Infos file saved at {user_dataset_infos_path}"	)
  
style_context: 
  
  
  
  
  
  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()
  
  
  _lowercase		:     Optional[Any] 					="""./tests/fixtures/elise_format0.mid"""
  
  
  
  
  
  
  @unittest.skip('The note-seq package currently throws an error on import'       )
  class 	UpperCamelCase_     (     snake_case__     ,    unittest.TestCase       ):
  					_a			:	int							=				SpectrogramDiffusionPipeline
  					_a			:	Dict							=				PipelineTesterMixin.required_optional_params - {
  					    'callback',
  					    'latents',
  					    'callback_steps',
  					    'output_type',
  					    'num_images_per_prompt',
  					}
  					_a			:	str							=				False
  					_a			:	Union[str, Any]							=				False
  					_a			:	Optional[int]							=				TOKENS_TO_AUDIO_GENERATION_PARAMS
  					_a			:	Optional[Any]							=				TOKENS_TO_AUDIO_GENERATION_BATCH_PARAMS
  
  
  
  					def      __a    (		self    :    Dict	):
  							torch.manual_seed(0	)
  							lowerCamelCase_  :    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'					,			)
  
  							lowerCamelCase_  :    Union[str, Any]   	=			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'					,			)
  
  							lowerCamelCase_  :    Union[str, Any]   	=			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					,			)
  
  							lowerCamelCase_  :    Any   	=			DDPMScheduler()
  
  							lowerCamelCase_  :    str   	=			{
  							    'notes_encoder': notes_encoder.eval(),
  							    'continuous_encoder': continuous_encoder.eval(),
  							    'decoder': decoder.eval(),
  							    'scheduler': scheduler,
  							    'melgan': None,
  							}
  							return components
  
  
  
  					def      __a    (		self    :    Any					,			lowerCamelCase    :    Any					,			lowerCamelCase    :    int=0	):
  							if str(lowerCamelCase	).startswith('mps'	):
  									lowerCamelCase_  :    Optional[int]   	=			torch.manual_seed(lowerCamelCase	)
  							else:
  									lowerCamelCase_  :    Dict   	=			torch.Generator(device=lowerCamelCase	).manual_seed(lowerCamelCase	)
  							lowerCamelCase_  :    str   	=			{
  							    '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      __a    (		self    :    Dict	):
  							lowerCamelCase_  :    str   	=			'cpu'  # ensure determinism for the device-dependent torch.Generator
  							lowerCamelCase_  :    Dict   	=			self.get_dummy_components()
  							lowerCamelCase_  :    Tuple   	=			SpectrogramDiffusionPipeline(**lowerCamelCase	)
  							lowerCamelCase_  :    List[str]   	=			pipe.to(lowerCamelCase	)
  							pipe.set_progress_bar_config(disable=lowerCamelCase	)
  
  							lowerCamelCase_  :    Optional[Any]   	=			self.get_dummy_inputs(lowerCamelCase	)
  							lowerCamelCase_  :    str   	=			pipe(**lowerCamelCase	)
  							lowerCamelCase_  :    Tuple   	=			output.audios
  
  							lowerCamelCase_  :    Tuple   	=			mel[0, -3:, -3:]
  
  							assert mel_slice.shape == (3, 3)
  							lowerCamelCase_  :    List[str]   	=			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      __a    (		self    :    Any	):
  							return super().test_save_load_local()
  
  
  
  					@skip_mps
  					def      __a    (		self    :    Tuple	):
  							return super().test_dict_tuple_outputs_equivalent()
  
  
  
  					@skip_mps
  					def      __a    (		self    :    Dict	):
  							return super().test_save_load_optional_components()
  
  
  
  					@skip_mps
  					def      __a    (		self    :    str	):
  							return super().test_attention_slicing_forward_pass()
  
  
  
  					def      __a    (		self    :    Any	):
  							pass
  
  
  
  					def      __a    (		self    :    Optional[int]	):
  							pass
  
  
  
  
  
  					@skip_mps
  					def      __a    (		self    :    Optional[Any]	):
  							return super().test_progress_bar()
  
  
  
  
  
  
  @slow
  @require_torch_gpu
  @require_onnxruntime
  @require_note_seq
  class 	UpperCamelCase_     (     unittest.TestCase       ):
  
  
  
  					def      __a    (		self    :    Optional[int]	):
  							# clean up the VRAM after each test
  							super().tearDown()
  							gc.collect()
  							torch.cuda.empty_cache()
  
  
  
  					def      __a    (		self    :    str	):
  							# TODO - test that pipeline can decode tokens in a callback
  							# so that music can be played live
  							lowerCamelCase_  :    Optional[Any]   	=			torch_device
  
  							lowerCamelCase_  :    Union[str, Any]   	=			SpectrogramDiffusionPipeline.from_pretrained('google/music-spectrogram-diffusion'	)
  							lowerCamelCase_  :    str   	=			pipe.melgan
  							lowerCamelCase_  :    Optional[int]   	=			None
  
  							lowerCamelCase_  :    str   	=			pipe.to(lowerCamelCase	)
  							pipe.set_progress_bar_config(disable=lowerCamelCase	)
  
  							def callback(lowerCamelCase    :    int					,			lowerCamelCase    :    int	):
  									# decode mel to audio
  									lowerCamelCase_  :    Union[str, Any]   	=			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
  
  							lowerCamelCase_  :    Any   	=			MidiProcessor()
  							lowerCamelCase_  :    str   	=			processor(lowerCamelCase	)
  
  							lowerCamelCase_  :    str   	=			input_tokens[:3]
  							lowerCamelCase_  :    Dict   	=			torch.manual_seed(0	)
  							pipe(lowerCamelCase					,			num_inference_steps=5					,			generator=lowerCamelCase					,			callback=lowerCamelCase					,			output_type='mel'	)
  
  
  
  					def      __a    (		self    :    str	):
  							lowerCamelCase_  :    List[str]   	=			torch_device
  
  							lowerCamelCase_  :    List[str]   	=			SpectrogramDiffusionPipeline.from_pretrained('google/music-spectrogram-diffusion'	)
  							lowerCamelCase_  :    Union[str, Any]   	=			pipe.to(lowerCamelCase	)
  							pipe.set_progress_bar_config(disable=lowerCamelCase	)
  							lowerCamelCase_  :    int   	=			MidiProcessor()
  
  							lowerCamelCase_  :    Dict   	=			processor(lowerCamelCase	)
  							# just run two denoising loops
  							lowerCamelCase_  :    Optional[Any]   	=			input_tokens[:2]
  
  							lowerCamelCase_  :    List[Any]   	=			torch.manual_seed(0	)
  							lowerCamelCase_  :    str   	=			pipe(lowerCamelCase					,			num_inference_steps=2					,			generator=lowerCamelCase	)
  
  							lowerCamelCase_  :    Dict   	=			output.audios[0]
  
  							assert abs(np.abs(lowerCamelCase	).sum() - 3_612.841	) < 1E-1
  
  
  
  
  
  					def      __a    (		self    :    List[Any]	):
  							lowerCamelCase_  :    int   	=			torch_device
  
  							lowerCamelCase_  :    str   	=			SpectrogramDiffusionPipeline.from_pretrained('google/music-spectrogram-diffusion'	)
  							lowerCamelCase_  :    Optional[int]   	=			pipe.to(lowerCamelCase	)
  							pipe.set_progress_bar_config(disable=lowerCamelCase	)
  
  							lowerCamelCase_  :    Tuple   	=			MidiProcessor()
  
  							lowerCamelCase_  :    int   	=			processor(lowerCamelCase	)
  
  							# just run 4 denoising loops
  							lowerCamelCase_  :    Optional[Any]   	=			input_tokens[:4]
  
  							lowerCamelCase_  :    List[Any]   	=			torch.manual_seed(0	)
  							lowerCamelCase_  :    int   	=			pipe(lowerCamelCase					,			num_inference_steps=1_00					,			generator=lowerCamelCase	)
  
  							lowerCamelCase_  :    List[Any]   	=			output.audios[0]
  							assert abs(np.abs(lowerCamelCase	).sum() - 9_389.1_111	) < 5E-2
  