


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



  """simple docstring"""



  _lowercase									=		DanceDiffusionPipeline
  _lowercase									=		UNCONDITIONAL_AUDIO_GENERATION_PARAMS
  _lowercase									=		PipelineTesterMixin.required_optional_params - {
      'callback',
      'latents',
      'callback_steps',
      'output_type',
      'num_images_per_prompt',
  }
  _lowercase									=		UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
  _lowercase									=		False
  _lowercase									=		False

  def    _UpperCamelCase( self			:  Optional[Any]       ):
        torch.manual_seed(0       )
        a__	:  int     =   UNetaDModel(
            block_out_channels=(32, 32, 64)				,				extra_in_channels=16				,				sample_size=512				,				sample_rate=16_000				,				in_channels=2				,				out_channels=2				,				flip_sin_to_cos=lowerCamelCase__				,				use_timestep_embedding=lowerCamelCase__				,				time_embedding_type="fourier"				,				mid_block_type="UNetMidBlock1D"				,				down_block_types=("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")				,				up_block_types=("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")				,				)
        a__	:  List[Any]     =   IPNDMScheduler()

        a__	:  List[str]     =   {
            """unet""": unet,
            """scheduler""": scheduler,
        }
        return components

  def    _UpperCamelCase( self			:  List[Any]				,				lowerCamelCase__			:  int				,				lowerCamelCase__			:  int=0       ):







        if str(lowerCamelCase__       ).startswith("mps"       ):
              a__	:  Optional[int]     =   torch.manual_seed(lowerCamelCase__       )
        else:
              a__	:  Any     =   torch.Generator(device=lowerCamelCase__       ).manual_seed(lowerCamelCase__       )
        a__	:  Optional[Any]     =   {
            """batch_size""": 1,
            """generator""": generator,
            """num_inference_steps""": 4,
        }
        return inputs

  def    _UpperCamelCase( self			:  Dict       ):
        a__	:  Tuple     =   """cpu"""  # ensure determinism for the device-dependent torch.Generator
        a__	:  int     =   self.get_dummy_components()
        a__	:  str     =   DanceDiffusionPipeline(**lowerCamelCase__       )
        a__	:  Optional[Any]     =   pipe.to(lowerCamelCase__       )
        pipe.set_progress_bar_config(disable=lowerCamelCase__       )

        a__	:  Dict     =   self.get_dummy_inputs(lowerCamelCase__       )
        a__	:  Any     =   pipe(**lowerCamelCase__       )
        a__	:  Tuple     =   output.audios

        a__	:  Tuple     =   audio[0, -3:, -3:]

        assert audio.shape == (1, 2, components["unet"].sample_size)
        a__	:  int     =   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    _UpperCamelCase( self			:  Optional[int]       ):
        return super().test_save_load_local()

  @skip_mps
  def    _UpperCamelCase( self			:  int       ):
        return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3       )

  @skip_mps
  def    _UpperCamelCase( self			:  List[str]       ):
        return super().test_save_load_optional_components()

  @skip_mps
  def    _UpperCamelCase( self			:  Tuple       ):
        return super().test_attention_slicing_forward_pass()

  def    _UpperCamelCase( self			:  Any       ):
        super().test_inference_batch_single_identical(expected_max_diff=3E-3       )




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



  """simple docstring"""



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

  def    _UpperCamelCase( self			:  Tuple       ):
        a__	:  Optional[Any]     =   torch_device

        a__	:  Union[str, Any]     =   DanceDiffusionPipeline.from_pretrained("harmonai/maestro-150k"       )
        a__	:  Any     =   pipe.to(lowerCamelCase__       )
        pipe.set_progress_bar_config(disable=lowerCamelCase__       )

        a__	:  Optional[int]     =   torch.manual_seed(0       )
        a__	:  str     =   pipe(generator=lowerCamelCase__				,				num_inference_steps=100				,				audio_length_in_s=4.096       )
        a__	:  Optional[int]     =   output.audios

        a__	:  Dict     =   audio[0, -3:, -3:]

        assert audio.shape == (1, 2, pipe.unet.sample_size)
        a__	:  int     =   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    _UpperCamelCase( self			:  Optional[int]       ):
        a__	:  Optional[Any]     =   torch_device

        a__	:  Any     =   DanceDiffusionPipeline.from_pretrained("harmonai/maestro-150k"				,				torch_dtype=torch.floataa       )
        a__	:  List[str]     =   pipe.to(lowerCamelCase__       )
        pipe.set_progress_bar_config(disable=lowerCamelCase__       )

        a__	:  Any     =   torch.manual_seed(0       )
        a__	:  Any     =   pipe(generator=lowerCamelCase__				,				num_inference_steps=100				,				audio_length_in_s=4.096       )
        a__	:  List[Any]     =   output.audios

        a__	:  Tuple     =   audio[0, -3:, -3:]

        assert audio.shape == (1, 2, pipe.unet.sample_size)
        a__	:  Dict     =   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







def 				A__ (snake_case   :		int				)     ->						bool:
					if number < 0:
										raise ValueError("""number must not be negative"""				)
					return number & (number - 1) == 0


if __name__ == "__main__":
	import doctest

	doctest.testmod()






