
import gc
import unittest

import numpy as np
import torch

from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()





class       __A(				UpperCAmelCase     ,		unittest.TestCase       ):
					SCREAMING_SNAKE_CASE			    =    DanceDiffusionPipeline
					SCREAMING_SNAKE_CASE			    =    UNCONDITIONAL_AUDIO_GENERATION_PARAMS
					SCREAMING_SNAKE_CASE			    =    PipelineTesterMixin.required_optional_params - {
					    '''callback''',
					    '''latents''',
					    '''callback_steps''',
					    '''output_type''',
					    '''num_images_per_prompt''',
					}
					SCREAMING_SNAKE_CASE			    =    UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
					SCREAMING_SNAKE_CASE			    =    False
					SCREAMING_SNAKE_CASE			    =    False

					def    lowercase__      (	self					:     List[Any]   ):
												torch.manual_seed(0   )
												lowerCamelCase_							  =					UNetaDModel(
												    block_out_channels=(3_2, 3_2, 6_4)   ,					extra_in_channels=1_6   ,					sample_size=5_1_2   ,					sample_rate=1_6_0_0_0   ,					in_channels=2   ,					out_channels=2   ,					flip_sin_to_cos=__UpperCamelCase   ,					use_timestep_embedding=__UpperCamelCase   ,					time_embedding_type="""fourier"""   ,					mid_block_type="""UNetMidBlock1D"""   ,					down_block_types=("""DownBlock1DNoSkip""", """DownBlock1D""", """AttnDownBlock1D""")   ,					up_block_types=("""AttnUpBlock1D""", """UpBlock1D""", """UpBlock1DNoSkip""")   ,					)
												lowerCamelCase_							  =					IPNDMScheduler()

												lowerCamelCase_							  =					{
												    """unet""": unet,
												    """scheduler""": scheduler,
												}
												return components

					def    lowercase__      (	self					:     int   ,					__UpperCamelCase					:     Union[str, Any]   ,					__UpperCamelCase					:     Any=0   ):
												if str(__UpperCamelCase   ).startswith("""mps"""   ):
																			lowerCamelCase_							  =					torch.manual_seed(__UpperCamelCase   )
												else:
																			lowerCamelCase_							  =					torch.Generator(device=__UpperCamelCase   ).manual_seed(__UpperCamelCase   )
												lowerCamelCase_							  =					{
												    """batch_size""": 1,
												    """generator""": generator,
												    """num_inference_steps""": 4,
												}
												return inputs

					def    lowercase__      (	self					:     Tuple   ):
												lowerCamelCase_							  =					"""cpu"""  # ensure determinism for the device-dependent torch.Generator
												lowerCamelCase_							  =					self.get_dummy_components()
												lowerCamelCase_							  =					DanceDiffusionPipeline(**__UpperCamelCase   )
												lowerCamelCase_							  =					pipe.to(__UpperCamelCase   )
												pipe.set_progress_bar_config(disable=__UpperCamelCase   )

												lowerCamelCase_							  =					self.get_dummy_inputs(__UpperCamelCase   )
												lowerCamelCase_							  =					pipe(**__UpperCamelCase   )
												lowerCamelCase_							  =					output.audios

												lowerCamelCase_							  =					audio[0, -3:, -3:]

												assert audio.shape == (1, 2, components["unet"].sample_size)
												lowerCamelCase_							  =					np.array([-0.7265, 1.0000, -0.8388, 0.1175, 0.9498, -1.0000]   )
												assert np.abs(audio_slice.flatten() - expected_slice   ).max() < 1E-2

					@skip_mps
					def    lowercase__      (	self					:     Optional[int]   ):
												return super().test_save_load_local()

					@skip_mps
					def    lowercase__      (	self					:     Optional[int]   ):
												return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3   )

					@skip_mps
					def    lowercase__      (	self					:     Tuple   ):
												return super().test_save_load_optional_components()

					@skip_mps
					def    lowercase__      (	self					:     Optional[Any]   ):
												return super().test_attention_slicing_forward_pass()



					def    lowercase__      (	self					:     List[str]   ):
												super().test_inference_batch_single_identical(expected_max_diff=3E-3   )





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

					def    lowercase__      (	self					:     List[str]   ):
												# clean up the VRAM after each test
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()

					def    lowercase__      (	self					:     int   ):
												lowerCamelCase_							  =					torch_device

												lowerCamelCase_							  =					DanceDiffusionPipeline.from_pretrained("""harmonai/maestro-150k"""   )
												lowerCamelCase_							  =					pipe.to(__UpperCamelCase   )
												pipe.set_progress_bar_config(disable=__UpperCamelCase   )

												lowerCamelCase_							  =					torch.manual_seed(0   )
												lowerCamelCase_							  =					pipe(generator=__UpperCamelCase   ,					num_inference_steps=1_0_0   ,					audio_length_in_s=4.096   )
												lowerCamelCase_							  =					output.audios

												lowerCamelCase_							  =					audio[0, -3:, -3:]

												assert audio.shape == (1, 2, pipe.unet.sample_size)
												lowerCamelCase_							  =					np.array([-0.0192, -0.0231, -0.0318, -0.0059, 0.0002, -0.0020]   )

												assert np.abs(audio_slice.flatten() - expected_slice   ).max() < 1E-2



					def    lowercase__      (	self					:     str   ):
												lowerCamelCase_							  =					torch_device

												lowerCamelCase_							  =					DanceDiffusionPipeline.from_pretrained("""harmonai/maestro-150k"""   ,					torch_dtype=torch.floataa   )
												lowerCamelCase_							  =					pipe.to(__UpperCamelCase   )
												pipe.set_progress_bar_config(disable=__UpperCamelCase   )

												lowerCamelCase_							  =					torch.manual_seed(0   )
												lowerCamelCase_							  =					pipe(generator=__UpperCamelCase   ,					num_inference_steps=1_0_0   ,					audio_length_in_s=4.096   )
												lowerCamelCase_							  =					output.audios

												lowerCamelCase_							  =					audio[0, -3:, -3:]

												assert audio.shape == (1, 2, pipe.unet.sample_size)
												lowerCamelCase_							  =					np.array([-0.0367, -0.0488, -0.0771, -0.0525, -0.0444, -0.0341]   )

												assert np.abs(audio_slice.flatten() - expected_slice   ).max() < 1E-2







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


lowercase        =  {'''configuration_deit''': ['''DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DeiTConfig''', '''DeiTOnnxConfig''']}

try:
		if not is_vision_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase        =  ['''DeiTFeatureExtractor''']
		lowercase        =  ['''DeiTImageProcessor''']

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase        =  [
		    '''DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''DeiTForImageClassification''',
		    '''DeiTForImageClassificationWithTeacher''',
		    '''DeiTForMaskedImageModeling''',
		    '''DeiTModel''',
		    '''DeiTPreTrainedModel''',
		]

try:
		if not is_tf_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase        =  [
		    '''TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''TFDeiTForImageClassification''',
		    '''TFDeiTForImageClassificationWithTeacher''',
		    '''TFDeiTForMaskedImageModeling''',
		    '''TFDeiTModel''',
		    '''TFDeiTPreTrainedModel''',
		]


if TYPE_CHECKING:
		from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig

		try:
				if not is_vision_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .feature_extraction_deit import DeiTFeatureExtractor
				from .image_processing_deit import DeiTImageProcessor

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_deit import (
				    DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    DeiTForImageClassification,
				    DeiTForImageClassificationWithTeacher,
				    DeiTForMaskedImageModeling,
				    DeiTModel,
				    DeiTPreTrainedModel,
				)

		try:
				if not is_tf_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_tf_deit import (
				    TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TFDeiTForImageClassification,
				    TFDeiTForImageClassificationWithTeacher,
				    TFDeiTForMaskedImageModeling,
				    TFDeiTModel,
				    TFDeiTPreTrainedModel,
				)


else:
		import sys

		lowercase        =  _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)





