from dataclasses import dataclass
from typing import Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin

@dataclass
class    snake_case       (   UpperCamelCase_    ):
  lowercase_								=  42
  lowercase_								=  42
  lowercase_								=  None




class    snake_case       (   UpperCamelCase_ ,    UpperCamelCase_    ):
  lowercase_								=  2




  @register_to_config
  def __init__(   self  :						Optional[Any]  ,			a_  :						float = 0.02  ,			a_  :						float = 100  ,			a_  :						float = 1.007  ,			a_  :						float = 80  ,			a_  :						float = 0.05  ,			a_  :						float = 50  ,			)->							Tuple:




       """simple docstring"""
       # standard deviation of the initial noise distribution
       SCREAMING_SNAKE_CASE__					:					int      =		sigma_max

       # setable values
       SCREAMING_SNAKE_CASE__					:					int      =		None
       SCREAMING_SNAKE_CASE__					:					np.IntTensor      =		None
       SCREAMING_SNAKE_CASE__					:					torch.FloatTensor      =		None  # sigma(t_i)




  def 						__lowercase(   self  :						Optional[Any]  ,			a_  :						torch.FloatTensor  ,			a_  :						Optional[int] = None					)->							torch.FloatTensor:




       """simple docstring"""
       return sample




  def 						__lowercase(   self  :						Any  ,			a_  :						int  ,			a_  :						Union[str, torch.device] = None					)->							Tuple:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__					:					List[str]      =		num_inference_steps
       SCREAMING_SNAKE_CASE__					:					Union[str, Any]      =		np.arange(0  ,			self.num_inference_steps					)[::-1].copy()
       SCREAMING_SNAKE_CASE__					:					Any      =		torch.from_numpy(a_					).to(a_					)
       SCREAMING_SNAKE_CASE__					:					Optional[Any]      =		[
           (
               self.config.sigma_max**2
               * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1))
           )
           for i in self.timesteps
       ]
       SCREAMING_SNAKE_CASE__					:					Dict      =		torch.tensor(a_  ,			dtype=torch.floataa  ,			device=a_					)




  def 						__lowercase(   self  :						Tuple  ,			a_  :						torch.FloatTensor  ,			a_  :						float  ,			a_  :						Optional[torch.Generator] = None					)->							Tuple[torch.FloatTensor, float]:




       """simple docstring"""
       if self.config.s_min <= sigma <= self.config.s_max:
            SCREAMING_SNAKE_CASE__					:					Optional[Any]      =		min(self.config.s_churn / self.num_inference_steps  ,			2**0.5 - 1					)
       else:
            SCREAMING_SNAKE_CASE__					:					Union[str, Any]      =		0

       # sample eps ~ N(0, S_noise^2 * I)
       SCREAMING_SNAKE_CASE__					:					Any      =		self.config.s_noise * randn_tensor(sample.shape  ,			generator=a_					).to(sample.device					)
       SCREAMING_SNAKE_CASE__					:					List[str]      =		sigma + gamma * sigma
       SCREAMING_SNAKE_CASE__					:					Union[str, Any]      =		sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps)

       return sample_hat, sigma_hat




  def 						__lowercase(   self  :						Dict  ,			a_  :						torch.FloatTensor  ,			a_  :						float  ,			a_  :						float  ,			a_  :						torch.FloatTensor  ,			a_  :						bool = True  ,			)->							Union[KarrasVeOutput, Tuple]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__					:					str      =		sample_hat + sigma_hat * model_output
       SCREAMING_SNAKE_CASE__					:					Dict      =		(sample_hat - pred_original_sample) / sigma_hat
       SCREAMING_SNAKE_CASE__					:					Optional[int]      =		sample_hat + (sigma_prev - sigma_hat) * derivative

       if not return_dict:
            return (sample_prev, derivative)

       return KarrasVeOutput(
           prev_sample=a_  ,			derivative=a_  ,			pred_original_sample=a_					)




  def 						__lowercase(   self  :						Optional[int]  ,			a_  :						torch.FloatTensor  ,			a_  :						float  ,			a_  :						float  ,			a_  :						torch.FloatTensor  ,			a_  :						torch.FloatTensor  ,			a_  :						torch.FloatTensor  ,			a_  :						bool = True  ,			)->							Union[KarrasVeOutput, Tuple]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__					:					Optional[Any]      =		sample_prev + sigma_prev * model_output
       SCREAMING_SNAKE_CASE__					:					Dict      =		(sample_prev - pred_original_sample) / sigma_prev
       SCREAMING_SNAKE_CASE__					:					Optional[int]      =		sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr)

       if not return_dict:
            return (sample_prev, derivative)

       return KarrasVeOutput(
           prev_sample=a_  ,			derivative=a_  ,			pred_original_sample=a_					)




  def 						__lowercase(   self  :						Tuple  ,			a_  :						int  ,			a_  :						Tuple  ,			a_  :						Union[str, Any]					)->							Optional[int]:




       """simple docstring"""
       raise NotImplementedError()





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 					_lowerCamelCase			(   UpperCamelCase_						,				unittest.TestCase			):





     """simple docstring"""







     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  __SCREAMING_SNAKE_CASE      (				self	)	-> Any:




           """simple docstring"""







           torch.manual_seed(0	)
           UpperCamelCase__     : List[str]											=					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=__SCREAMING_SNAKE_CASE    ,    use_timestep_embedding=__SCREAMING_SNAKE_CASE    ,    time_embedding_type='''fourier'''    ,    mid_block_type='''UNetMidBlock1D'''    ,    down_block_types=('''DownBlock1DNoSkip''', '''DownBlock1D''', '''AttnDownBlock1D''')    ,    up_block_types=('''AttnUpBlock1D''', '''UpBlock1D''', '''UpBlock1DNoSkip''')    ,    )
           UpperCamelCase__     : Union[str, Any]											=					IPNDMScheduler()

           UpperCamelCase__     : List[str]											=					{
               '''unet''': unet,
               '''scheduler''': scheduler,
           }
           return components






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE=0	)	-> Any:




           """simple docstring"""







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






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> List[Any]:




           """simple docstring"""







           UpperCamelCase__     : str											=					'''cpu'''  # ensure determinism for the device-dependent torch.Generator
           UpperCamelCase__     : Dict											=					self.get_dummy_components()
           UpperCamelCase__     : str											=					DanceDiffusionPipeline(**__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : List[Any]											=					pipe.to(__SCREAMING_SNAKE_CASE	)
           pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE	)

           UpperCamelCase__     : int											=					self.get_dummy_inputs(__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : Dict											=					pipe(**__SCREAMING_SNAKE_CASE	)
           UpperCamelCase__     : List[str]											=					output.audios

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

           assert audio.shape == (1, 2, components["unet"].sample_size)
           UpperCamelCase__     : List[Any]											=					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  __SCREAMING_SNAKE_CASE      (				self	)	-> List[Any]:




           """simple docstring"""







           return super().test_save_load_local()






     @skip_mps
     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Tuple:




           """simple docstring"""







           return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3	)






     @skip_mps
     def  __SCREAMING_SNAKE_CASE      (				self	)	-> str:




           """simple docstring"""







           return super().test_save_load_optional_components()






     @skip_mps
     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Optional[int]:




           """simple docstring"""







           return super().test_attention_slicing_forward_pass()






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Tuple:




           """simple docstring"""







           super().test_inference_batch_single_identical(expected_max_diff=3e-3	)




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





     """simple docstring"""







     def  __SCREAMING_SNAKE_CASE      (				self	)	-> int:




           """simple docstring"""







           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()






     def  __SCREAMING_SNAKE_CASE      (				self	)	-> Union[str, Any]:




           """simple docstring"""







           UpperCamelCase__     : Any											=					torch_device

           UpperCamelCase__     : Any											=					DanceDiffusionPipeline.from_pretrained('''harmonai/maestro-150k'''	)
           UpperCamelCase__     : int											=					pipe.to(__SCREAMING_SNAKE_CASE	)
           pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE	)

           UpperCamelCase__     : int											=					torch.manual_seed(0	)
           UpperCamelCase__     : Optional[Any]											=					pipe(generator=__SCREAMING_SNAKE_CASE    ,    num_inference_steps=1_0_0    ,    audio_length_in_s=4.096	)
           UpperCamelCase__     : str											=					output.audios

           UpperCamelCase__     : List[Any]											=					audio[0, -3:, -3:]

           assert audio.shape == (1, 2, pipe.unet.sample_size)
           UpperCamelCase__     : Tuple											=					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  __SCREAMING_SNAKE_CASE      (				self	)	-> Union[str, Any]:




           """simple docstring"""







           UpperCamelCase__     : Any											=					torch_device

           UpperCamelCase__     : Union[str, Any]											=					DanceDiffusionPipeline.from_pretrained('''harmonai/maestro-150k'''    ,    torch_dtype=torch.floataa	)
           UpperCamelCase__     : Tuple											=					pipe.to(__SCREAMING_SNAKE_CASE	)
           pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE	)

           UpperCamelCase__     : int											=					torch.manual_seed(0	)
           UpperCamelCase__     : Union[str, Any]											=					pipe(generator=__SCREAMING_SNAKE_CASE    ,    num_inference_steps=1_0_0    ,    audio_length_in_s=4.096	)
           UpperCamelCase__     : List[Any]											=					output.audios

           UpperCamelCase__     : List[Any]											=					audio[0, -3:, -3:]

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


