

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







										'''simple docstring'''


										torch.manual_seed(0	)
										_UpperCAmelCase       :		str 		=    UNetaDModel(
										    block_out_channels=(32, 32, 64)						,					extra_in_channels=16						,					sample_size=512						,					sample_rate=16000						,					in_channels=2						,					out_channels=2						,					flip_sin_to_cos=A_						,					use_timestep_embedding=A_						,					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       :		Union[str, Any] 		=    {
										    "unet": unet,
										    "scheduler": scheduler,
										}
										return components


						def        _UpperCAmelCase				(       self						,					A_						,					A_=0	):







										'''simple docstring'''


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


						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		Union[str, Any] 		=    "cpu"  # ensure determinism for the device-dependent torch.Generator
										_UpperCAmelCase       :		int 		=    self.get_dummy_components()
										_UpperCAmelCase       :		List[str] 		=    DanceDiffusionPipeline(**A_	)
										_UpperCAmelCase       :		str 		=    pipe.to(A_	)
										pipe.set_progress_bar_config(disable=A_	)

										_UpperCAmelCase       :		Any 		=    self.get_dummy_inputs(A_	)
										_UpperCAmelCase       :		Union[str, Any] 		=    pipe(**A_	)
										_UpperCAmelCase       :		int 		=    output.audios

										_UpperCAmelCase       :		List[str] 		=    audio[0, -3:, -3:]

										assert audio.shape == (1, 2, components["unet"].sample_size)
										_UpperCAmelCase       :		Any 		=    np.array([-0.72_65, 1.00_00, -0.83_88, 0.11_75, 0.94_98, -1.00_00]	)
										assert np.abs(audio_slice.flatten() - expected_slice	).max() < 1e-2


						@skip_mps
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										return super().test_save_load_local()


						@skip_mps
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


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


						@skip_mps
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										return super().test_save_load_optional_components()


						@skip_mps
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										return super().test_attention_slicing_forward_pass()





						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


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







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


						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


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


						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		Union[str, Any] 		=    torch_device

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

										_UpperCAmelCase       :		Any 		=    torch.manual_seed(0	)
										_UpperCAmelCase       :		Dict 		=    pipe(generator=A_						,					num_inference_steps=100						,					audio_length_in_s=4.0_96	)
										_UpperCAmelCase       :		Tuple 		=    output.audios

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

										assert audio.shape == (1, 2, pipe.unet.sample_size)
										_UpperCAmelCase       :		str 		=    np.array([-0.01_92, -0.02_31, -0.03_18, -0.00_59, 0.00_02, -0.00_20]	)

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





						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										_UpperCAmelCase       :		Optional[Any] 		=    torch_device

										_UpperCAmelCase       :		List[str] 		=    DanceDiffusionPipeline.from_pretrained("harmonai/maestro-150k"						,					torch_dtype=torch.floataa	)
										_UpperCAmelCase       :		Optional[int] 		=    pipe.to(A_	)
										pipe.set_progress_bar_config(disable=A_	)

										_UpperCAmelCase       :		Optional[Any] 		=    torch.manual_seed(0	)
										_UpperCAmelCase       :		Optional[int] 		=    pipe(generator=A_						,					num_inference_steps=100						,					audio_length_in_s=4.0_96	)
										_UpperCAmelCase       :		Union[str, Any] 		=    output.audios

										_UpperCAmelCase       :		Optional[int] 		=    audio[0, -3:, -3:]

										assert audio.shape == (1, 2, pipe.unet.sample_size)
										_UpperCAmelCase       :		List[str] 		=    np.array([-0.03_67, -0.04_88, -0.07_71, -0.05_25, -0.04_44, -0.03_41]	)

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





import importlib
import math
import os
from dataclasses import dataclass
from enum import Enum
from typing import Any, Dict, Optional, Tuple, Union

import flax
import jax.numpy as jnp

from ..utils import BaseOutput


SCREAMING_SNAKE_CASE_        =      'scheduler_config.json'

class 				a  (	UpperCAmelCase				):
						_lowercase    						=			1
						_lowercase    						=			2
						_lowercase    						=			3
						_lowercase    						=			4
						_lowercase    						=			5







@dataclass
class 				a  (	UpperCAmelCase				):
						_lowercase    						=			42







class 				a  :
						_lowercase    						=			SCHEDULER_CONFIG_NAME
						_lowercase    						=			["dtype"]
						_lowercase    						=			[]
						_lowercase    						=			True


						@classmethod
						def        _UpperCAmelCase				(       cls						,					A_ = None						,					A_ = None						,					A_=False						,					**A_						,					):







										'''simple docstring'''


										_UpperCAmelCase		,							_UpperCAmelCase       :		str 		=    cls.load_config(
										    pretrained_model_name_or_path=A_						,					subfolder=A_						,					return_unused_kwargs=A_						,					**A_						,					)
										_UpperCAmelCase		,							_UpperCAmelCase       :		Optional[int] 		=    cls.from_config(A_						,					return_unused_kwargs=A_						,					**A_	)

										if hasattr(A_						,					"create_state"	) and getattr(A_						,					"has_state"						,					A_	):
														_UpperCAmelCase       :		Union[str, Any] 		=    scheduler.create_state()

										if return_unused_kwargs:
														return scheduler, state, unused_kwargs

										return scheduler, state


						def        _UpperCAmelCase				(       self						,					A_						,					A_ = False						,					**A_	):







										'''simple docstring'''


										self.save_config(save_directory=A_						,					push_to_hub=A_						,					**A_	)


						@property
						def        _UpperCAmelCase				(       self	):







										'''simple docstring'''


										return self._get_compatibles()





						@classmethod
						def        _UpperCAmelCase				(       cls	):







										'''simple docstring'''


										_UpperCAmelCase       :		Union[str, Any] 		=    list(set([cls.__name__] + cls._compatibles	)	)
										_UpperCAmelCase       :		Optional[Any] 		=    importlib.import_module(__name__.split("."	)[0]	)
										_UpperCAmelCase       :		Dict 		=    [
										    getattr(A_						,					A_	) for c in compatible_classes_str if hasattr(A_						,					A_	)
										]
										return compatible_classes







def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  jnp.ndarray  ,      lowerCAmelCase:  Tuple[int] )   ->       jnp.ndarray:
				assert len(lowerCAmelCase ) >= x.ndim
				return jnp.broadcast_to(x.reshape(x.shape + (1,) * (len(lowerCAmelCase ) - x.ndim) )  ,      lowerCAmelCase )

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  int  ,      lowerCAmelCase:  Tuple=0.999  ,      lowerCAmelCase:  int=jnp.floataa )   ->       jnp.ndarray:

				def alpha_bar(lowerCAmelCase:  Union[str, Any] ):
								return math.cos((time_step + 0.008) / 1.008 * math.pi / 2 ) ** 2

				_UpperCAmelCase       :		str 		=    []
				for i in range(lowerCAmelCase ):
								_UpperCAmelCase       :		Optional[int] 		=    i / num_diffusion_timesteps
								_UpperCAmelCase       :		str 		=    (i + 1) / num_diffusion_timesteps
								betas.append(min(1 - alpha_bar(lowerCAmelCase ) / alpha_bar(lowerCAmelCase )  ,      lowerCAmelCase ) )
				return jnp.array(lowerCAmelCase  ,      dtype=lowerCAmelCase )

@flax.struct.dataclass
class 				a  :
						_lowercase    						=			42
						_lowercase    						=			42
						_lowercase    						=			42


						@classmethod
						def        _UpperCAmelCase				(       cls						,					A_	):







										'''simple docstring'''


										_UpperCAmelCase       :		Tuple 		=    scheduler.config

										if config.trained_betas is not None:
														_UpperCAmelCase       :		List[Any] 		=    jnp.asarray(config.trained_betas						,					dtype=scheduler.dtype	)
										elif config.beta_schedule == "linear":
														_UpperCAmelCase       :		List[Any] 		=    jnp.linspace(config.beta_start						,					config.beta_end						,					config.num_train_timesteps						,					dtype=scheduler.dtype	)
										elif config.beta_schedule == "scaled_linear":
														# this schedule is very specific to the latent diffusion model.
														_UpperCAmelCase       :		List[str] 		=    (
														    jnp.linspace(
														        config.beta_start**0.5						,					config.beta_end**0.5						,					config.num_train_timesteps						,					dtype=scheduler.dtype	)
														    ** 2
														)
										elif config.beta_schedule == "squaredcos_cap_v2":
														# Glide cosine schedule
														_UpperCAmelCase       :		str 		=    betas_for_alpha_bar(config.num_train_timesteps						,					dtype=scheduler.dtype	)
										else:
														raise NotImplementedError(
														    f'beta_schedule {config.beta_schedule} is not implemented for scheduler {scheduler.__class__.__name__}'	)

										_UpperCAmelCase       :		Optional[int] 		=    1.0 - betas

										_UpperCAmelCase       :		int 		=    jnp.cumprod(A_						,					axis=0	)

										return cls(
										    alphas=A_						,					betas=A_						,					alphas_cumprod=A_						,					)







def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  CommonSchedulerState  ,      lowerCAmelCase:  jnp.ndarray  ,      lowerCAmelCase:  jnp.ndarray  ,      lowerCAmelCase:  jnp.ndarray )   ->       Union[str, Any]:
				_UpperCAmelCase       :		Optional[int] 		=    state.alphas_cumprod

				_UpperCAmelCase       :		Optional[Any] 		=    alphas_cumprod[timesteps] ** 0.5
				_UpperCAmelCase       :		str 		=    sqrt_alpha_prod.flatten()
				_UpperCAmelCase       :		List[Any] 		=    broadcast_to_shape_from_left(lowerCAmelCase  ,      original_samples.shape )

				_UpperCAmelCase       :		Optional[int] 		=    (1 - alphas_cumprod[timesteps]) ** 0.5
				_UpperCAmelCase       :		List[Any] 		=    sqrt_one_minus_alpha_prod.flatten()
				_UpperCAmelCase       :		int 		=    broadcast_to_shape_from_left(lowerCAmelCase  ,      original_samples.shape )

				return sqrt_alpha_prod, sqrt_one_minus_alpha_prod

def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  CommonSchedulerState  ,      lowerCAmelCase:  jnp.ndarray  ,      lowerCAmelCase:  jnp.ndarray  ,      lowerCAmelCase:  jnp.ndarray )   ->       List[Any]:
				_UpperCAmelCase		,							_UpperCAmelCase       :		Optional[Any] 		=    get_sqrt_alpha_prod(lowerCAmelCase  ,      lowerCAmelCase  ,      lowerCAmelCase  ,      lowerCAmelCase )
				_UpperCAmelCase       :		Any 		=    sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
				return noisy_samples





def 							__SCREAMING_SNAKE_CASE							(				lowerCAmelCase:  CommonSchedulerState  ,      lowerCAmelCase:  jnp.ndarray  ,      lowerCAmelCase:  jnp.ndarray  ,      lowerCAmelCase:  jnp.ndarray )   ->       Dict:
				_UpperCAmelCase		,							_UpperCAmelCase       :		int 		=    get_sqrt_alpha_prod(lowerCAmelCase  ,      lowerCAmelCase  ,      lowerCAmelCase  ,      lowerCAmelCase )
				_UpperCAmelCase       :		Tuple 		=    sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
				return velocity


