


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        _UpperCamelCase			(   SCREAMING_SNAKE_CASE_      ,				unittest.TestCase						):







							'''simple docstring'''
							_A						=	DanceDiffusionPipeline
							_A						=	UNCONDITIONAL_AUDIO_GENERATION_PARAMS
							_A						=	PipelineTesterMixin.required_optional_params - {
							    "callback",
							    "latents",
							    "callback_steps",
							    "output_type",
							    "num_images_per_prompt",
							}
							_A						=	UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
							_A						=	False
							_A						=	False







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

													_a     			=      {
													    'unet': unet,
													    'scheduler': scheduler,
													}
													return components







							def 		_UpperCAmelCase						(		self	:					List[str]		,					SCREAMING_SNAKE_CASE_	:					List[str]		,					SCREAMING_SNAKE_CASE_	:					List[Any]=0		):

													if str(snake_case__		).startswith('mps'		):
																			_a     			=      torch.manual_seed(snake_case__		)
													else:
																			_a     			=      torch.Generator(device=snake_case__		).manual_seed(snake_case__		)
													_a     			=      {
													    'batch_size': 1,
													    'generator': generator,
													    'num_inference_steps': 4,
													}
													return inputs







							def 		_UpperCAmelCase						(		self	:					Union[str, Any]		):
													_a     			=      'cpu'  # ensure determinism for the device-dependent torch.Generator
													_a     			=      self.get_dummy_components()
													_a     			=      DanceDiffusionPipeline(**snake_case__		)
													_a     			=      pipe.to(snake_case__		)
													pipe.set_progress_bar_config(disable=snake_case__		)

													_a     			=      self.get_dummy_inputs(snake_case__		)
													_a     			=      pipe(**snake_case__		)
													_a     			=      output.audios

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

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







							@skip_mps
							def 		_UpperCAmelCase						(		self	:					str		):
													return super().test_attention_slicing_forward_pass()







							def 		_UpperCAmelCase						(		self	:					Dict		):
													super().test_inference_batch_single_identical(expected_max_diff=3e-3		)




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







							'''simple docstring'''







							def 		_UpperCAmelCase						(		self	:					Union[str, Any]		):
													super().tearDown()
													gc.collect()
													torch.cuda.empty_cache()







							def 		_UpperCAmelCase						(		self	:					Union[str, Any]		):
													_a     			=      torch_device

													_a     			=      DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'		)
													_a     			=      pipe.to(snake_case__		)
													pipe.set_progress_bar_config(disable=snake_case__		)

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

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

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

													_a     			=      DanceDiffusionPipeline.from_pretrained('harmonai/maestro-150k'		,					torch_dtype=torch.floataa		)
													_a     			=      pipe.to(snake_case__		)
													pipe.set_progress_bar_config(disable=snake_case__		)

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

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

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






'''simple docstring'''







import argparse
from collections import defaultdict

import yaml


lowerCAmelCase     :  Dict											=    """docs/source/en/_toctree.yml"""






def       lowercase					(_A       ):







       """simple docstring"""







       _lowerCAmelCase     :				Optional[int]       =							defaultdict(_A       )
       _lowerCAmelCase     :				Tuple       =							[]
       _lowerCAmelCase     :				Dict       =							[]
       for doc in doc_list:
              if "local" in doc:
                     counts[doc["local"]] += 1

              if doc["title"].lower() == "overview":
                     overview_doc.append({'local': doc['local'], 'title': doc['title']}       )
              else:
                     new_doc_list.append(_A       )

       _lowerCAmelCase     :				str       =							new_doc_list
       _lowerCAmelCase     :				List[Any]       =							[key for key, value in counts.items() if value > 1]

       _lowerCAmelCase     :				List[str]       =							[]
       for duplicate_key in duplicates:
              _lowerCAmelCase     :				Any       =							list({doc['title'] for doc in doc_list if doc['local'] == duplicate_key}       )
              if len(_A       ) > 1:
                     raise ValueError(
                         f'{duplicate_key} is present several times in the documentation table of content at '
                         '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '
                         'others.'       )
              # Only add this once
              new_doc.append({'local': duplicate_key, 'title': titles[0]}       )

       # Add none duplicate-keys
       new_doc.extend([doc for doc in doc_list if 'local' not in counts or counts[doc['local']] == 1]       )
       _lowerCAmelCase     :				Any       =							sorted(_A ,    key=lambda _A       : s["title"].lower()       )

       # "overview" gets special treatment and is always first
       if len(_A       ) > 1:
              raise ValueError('{doc_list} has two \'overview\' docs which is not allowed.'       )

       overview_doc.extend(_A       )

       # Sort
       return overview_doc






def       lowercase					(_A=False       ):







       """simple docstring"""







       with open(_A ,    encoding='utf-8'       ) as f:
              _lowerCAmelCase     :				Union[str, Any]       =							yaml.safe_load(f.read()       )

       # Get to the API doc
       _lowerCAmelCase     :				Tuple       =							0
       while content[api_idx]["title"] != "API":
              api_idx += 1
       _lowerCAmelCase     :				str       =							content[api_idx]['sections']

       # Then to the model doc
       _lowerCAmelCase     :				Dict       =							0
       while api_doc[scheduler_idx]["title"] != "Schedulers":
              scheduler_idx += 1

       _lowerCAmelCase     :				Optional[int]       =							api_doc[scheduler_idx]['sections']
       _lowerCAmelCase     :				Any       =							clean_doc_toc(_A       )

       _lowerCAmelCase     :				int       =							False
       if new_scheduler_doc != scheduler_doc:
              _lowerCAmelCase     :				str       =							True
              if overwrite:
                     _lowerCAmelCase     :				int       =							new_scheduler_doc

       if diff:
              if overwrite:
                     _lowerCAmelCase     :				Dict       =							api_doc
                     with open(_A ,    'w' ,    encoding='utf-8'       ) as f:
                            f.write(yaml.dump(_A ,    allow_unicode=_A       )       )
              else:
                     raise ValueError(
                         'The model doc part of the table of content is not properly sorted, run `make style` to fix this.'       )






def       lowercase					(_A=False       ):







       """simple docstring"""







       with open(_A ,    encoding='utf-8'       ) as f:
              _lowerCAmelCase     :				Optional[Any]       =							yaml.safe_load(f.read()       )

       # Get to the API doc
       _lowerCAmelCase     :				Optional[Any]       =							0
       while content[api_idx]["title"] != "API":
              api_idx += 1
       _lowerCAmelCase     :				Union[str, Any]       =							content[api_idx]['sections']

       # Then to the model doc
       _lowerCAmelCase     :				Optional[int]       =							0
       while api_doc[pipeline_idx]["title"] != "Pipelines":
              pipeline_idx += 1

       _lowerCAmelCase     :				List[Any]       =							False
       _lowerCAmelCase     :				List[Any]       =							api_doc[pipeline_idx]['sections']
       _lowerCAmelCase     :				Union[str, Any]       =							[]

       # sort sub pipeline docs
       for pipeline_doc in pipeline_docs:
              if "section" in pipeline_doc:
                     _lowerCAmelCase     :				Tuple       =							pipeline_doc['section']
                     _lowerCAmelCase     :				Optional[int]       =							clean_doc_toc(_A       )
                     if overwrite:
                            _lowerCAmelCase     :				str       =							new_sub_pipeline_doc
              new_pipeline_docs.append(_A       )

       # sort overall pipeline doc
       _lowerCAmelCase     :				str       =							clean_doc_toc(_A       )

       if new_pipeline_docs != pipeline_docs:
              _lowerCAmelCase     :				Any       =							True
              if overwrite:
                     _lowerCAmelCase     :				Optional[int]       =							new_pipeline_docs

       if diff:
              if overwrite:
                     _lowerCAmelCase     :				str       =							api_doc
                     with open(_A ,    'w' ,    encoding='utf-8'       ) as f:
                            f.write(yaml.dump(_A ,    allow_unicode=_A       )       )
              else:
                     raise ValueError(
                         'The model doc part of the table of content is not properly sorted, run `make style` to fix this.'       )


if __name__ == "__main__":
       lowerCAmelCase     :  Tuple											=    argparse.ArgumentParser()
       parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
       lowerCAmelCase     :  List[Any]											=    parser.parse_args()

       check_scheduler_doc(args.fix_and_overwrite)
       check_pipeline_doc(args.fix_and_overwrite)

