

'''simple docstring'''





import gc
import unittest

import numpy as np
import torch

from diffusers import (
    AudioDiffusionPipeline,
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    DiffusionPipeline,
    Mel,
    UNetaDConditionModel,
    UNetaDModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()





class 		__SCREAMING_SNAKE_CASE       ( unittest.TestCase			):







				def    lowerCamelCase_  (					self    :		List[Any]      ):
										'''simple docstring'''
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()







				@property
				def    lowerCamelCase_  (					self    :		Optional[int]      ):
										'''simple docstring'''
										torch.manual_seed(0      )
										lowercase   :       Optional[int]								=UNetaDModel(
										    sample_size=(32, 64)		,				in_channels=1		,				out_channels=1		,				layers_per_block=2		,				block_out_channels=(128, 128)		,				down_block_types=('''AttnDownBlock2D''', '''DownBlock2D''')		,				up_block_types=('''UpBlock2D''', '''AttnUpBlock2D''')		,				)
										return model







				@property
				def    lowerCamelCase_  (					self    :		List[str]      ):
										'''simple docstring'''
										torch.manual_seed(0      )
										lowercase   :       List[str]								=UNetaDConditionModel(
										    sample_size=(64, 32)		,				in_channels=1		,				out_channels=1		,				layers_per_block=2		,				block_out_channels=(128, 128)		,				down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''')		,				up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''')		,				cross_attention_dim=10		,				)
										return model







				@property
				def    lowerCamelCase_  (					self    :		List[str]      ):
										'''simple docstring'''
										torch.manual_seed(0      )
										lowercase   :       Any								=AutoencoderKL(
										    sample_size=(128, 64)		,				in_channels=1		,				out_channels=1		,				latent_channels=1		,				layers_per_block=2		,				block_out_channels=(128, 128)		,				down_block_types=('''DownEncoderBlock2D''', '''DownEncoderBlock2D''')		,				up_block_types=('''UpDecoderBlock2D''', '''UpDecoderBlock2D''')		,				)
										lowercase   :       str								=UNetaDModel(
										    sample_size=(64, 32)		,				in_channels=1		,				out_channels=1		,				layers_per_block=2		,				block_out_channels=(128, 128)		,				down_block_types=('''AttnDownBlock2D''', '''DownBlock2D''')		,				up_block_types=('''UpBlock2D''', '''AttnUpBlock2D''')		,				)
										return vqvae, unet







				@slow
				def    lowerCamelCase_  (					self    :		Optional[int]      ):
										'''simple docstring'''
										lowercase   :       int								="""cpu"""  # ensure determinism for the device-dependent torch.Generator
										lowercase   :       Union[str, Any]								=Mel(
										    x_res=self.dummy_unet.config.sample_size[1]		,				y_res=self.dummy_unet.config.sample_size[0]		,				)

										lowercase   :       str								=DDPMScheduler()
										lowercase   :       Any								=AudioDiffusionPipeline(vqvae=UpperCAmelCase__		,				unet=self.dummy_unet		,				mel=UpperCAmelCase__		,				scheduler=UpperCAmelCase__      )
										lowercase   :       List[Any]								=pipe.to(UpperCAmelCase__      )
										pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

										lowercase   :       Any								=torch.Generator(device=UpperCAmelCase__      ).manual_seed(42      )
										lowercase   :       str								=pipe(generator=UpperCAmelCase__		,				steps=4      )
										lowercase   :       Optional[Any]								=output.audios[0]
										lowercase   :       Optional[int]								=output.images[0]

										lowercase   :       str								=torch.Generator(device=UpperCAmelCase__      ).manual_seed(42      )
										lowercase   :       List[str]								=pipe(generator=UpperCAmelCase__		,				steps=4		,				return_dict=UpperCAmelCase__      )
										lowercase   :       List[str]								=output[0][0]

										assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length)
										assert (
										    image.height == self.dummy_unet.config.sample_size[0]
										    and image.width == self.dummy_unet.config.sample_size[1]
										)
										lowercase   :       Dict								=np.frombuffer(image.tobytes()		,				dtype='''uint8'''      )[:10]
										lowercase   :       Dict								=np.frombuffer(image_from_tuple.tobytes()		,				dtype='''uint8'''      )[:10]
										lowercase   :       List[Any]								=np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127]      )

										assert np.abs(image_slice.flatten() - expected_slice      ).max() == 0
										assert np.abs(image_from_tuple_slice.flatten() - expected_slice      ).max() == 0

										lowercase   :       Tuple								=Mel(
										    x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1]		,				y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0]		,				)

										lowercase   :       List[str]								=DDIMScheduler()
										lowercase   :       Union[str, Any]								=self.dummy_vqvae_and_unet
										lowercase   :       Optional[Any]								=AudioDiffusionPipeline(
										    vqvae=self.dummy_vqvae_and_unet[0]		,				unet=dummy_vqvae_and_unet[1]		,				mel=UpperCAmelCase__		,				scheduler=UpperCAmelCase__      )
										lowercase   :       Dict								=pipe.to(UpperCAmelCase__      )
										pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

										np.random.seed(0      )
										lowercase   :       List[str]								=np.random.uniform(-1		,				1		,				((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,)      )
										lowercase   :       str								=torch.Generator(device=UpperCAmelCase__      ).manual_seed(42      )
										lowercase   :       str								=pipe(raw_audio=UpperCAmelCase__		,				generator=UpperCAmelCase__		,				start_step=5		,				steps=10      )
										lowercase   :       Any								=output.images[0]

										assert (
										    image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0]
										    and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1]
										)
										lowercase   :       str								=np.frombuffer(image.tobytes()		,				dtype='''uint8'''      )[:10]
										lowercase   :       List[str]								=np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121]      )

										assert np.abs(image_slice.flatten() - expected_slice      ).max() == 0

										lowercase   :       Tuple								=self.dummy_unet_condition
										lowercase   :       Tuple								=AudioDiffusionPipeline(
										    vqvae=self.dummy_vqvae_and_unet[0]		,				unet=UpperCAmelCase__		,				mel=UpperCAmelCase__		,				scheduler=UpperCAmelCase__      )
										lowercase   :       List[Any]								=pipe.to(UpperCAmelCase__      )
										pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

										np.random.seed(0      )
										lowercase   :       Tuple								=torch.rand((1, 1, 10)      )
										lowercase   :       Any								=pipe(generator=UpperCAmelCase__		,				encoding=UpperCAmelCase__      )
										lowercase   :       int								=output.images[0]
										lowercase   :       int								=np.frombuffer(image.tobytes()		,				dtype='''uint8'''      )[:10]
										lowercase   :       List[str]								=np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111]      )

										assert np.abs(image_slice.flatten() - expected_slice      ).max() == 0





@slow
@require_torch_gpu
class 		__SCREAMING_SNAKE_CASE       ( unittest.TestCase			):







				def    lowerCamelCase_  (					self    :		str      ):
										'''simple docstring'''
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()







				def    lowerCamelCase_  (					self    :		Tuple      ):
										'''simple docstring'''
										lowercase   :       Union[str, Any]								=torch_device

										lowercase   :       int								=DiffusionPipeline.from_pretrained('''teticio/audio-diffusion-ddim-256'''      )
										lowercase   :       Any								=pipe.to(UpperCAmelCase__      )
										pipe.set_progress_bar_config(disable=UpperCAmelCase__      )

										lowercase   :       Union[str, Any]								=torch.Generator(device=UpperCAmelCase__      ).manual_seed(42      )
										lowercase   :       Tuple								=pipe(generator=UpperCAmelCase__      )
										lowercase   :       Any								=output.audios[0]
										lowercase   :       Dict								=output.images[0]

										assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length)
										assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1]
										lowercase   :       Union[str, Any]								=np.frombuffer(image.tobytes()		,				dtype='''uint8'''      )[:10]
										lowercase   :       str								=np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26]      )

										assert np.abs(image_slice.flatten() - expected_slice      ).max() == 0



'''simple docstring'''





from datetime import datetime

import matplotlib.pyplot as plt
import torch






def 							_lowerCAmelCase (      __magic_name__	:    Dict	)							->     Dict:
						for param in module.parameters():
												lowercase   :       List[str]								=False






def 							_lowerCAmelCase (      )							->     List[str]:
						lowercase   :       Dict								='''cuda''' if torch.cuda.is_available() else '''cpu'''
						if torch.backends.mps.is_available() and torch.backends.mps.is_built():
												lowercase   :       Optional[int]								='''mps'''
						if device == "mps":
												print(
												    '''WARNING: MPS currently doesn\'t seem to work, and messes up backpropagation without any visible torch'''
												    ''' errors. I recommend using CUDA on a colab notebook or CPU instead if you\'re facing inexplicable issues'''
												    ''' with generations.'''	)
						return device






def 							_lowerCAmelCase (      __magic_name__	:    Union[str, Any]	)							->     str:
						lowercase   :       Optional[int]								=plt.imshow(__magic_name__	)
						fig.axes.get_xaxis().set_visible(__magic_name__	)
						fig.axes.get_yaxis().set_visible(__magic_name__	)
						plt.show()







def 							_lowerCAmelCase (      )							->     List[Any]:
						lowercase   :       Any								=datetime.now()
						lowercase   :       Dict								=current_time.strftime('''%H:%M:%S'''	)
						return timestamp





