






'''simple docstring'''

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_						(      lowerCamelCase     ,	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   A__						(				self				)  ->				List[Any]:



        """simple docstring"""






        torch.manual_seed(0				)
        UpperCamelCase      = 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=_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      = IPNDMScheduler()

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

  def   A__						(				self      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE=0				)  ->				List[str]:



        """simple docstring"""






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

  def   A__						(				self				)  ->				Tuple:



        """simple docstring"""






        UpperCamelCase      = """cpu"""  # ensure determinism for the device-dependent torch.Generator
        UpperCamelCase      = self.get_dummy_components()
        UpperCamelCase      = DanceDiffusionPipeline(**_SCREAMING_SNAKE_CASE				)
        UpperCamelCase      = pipe.to(_SCREAMING_SNAKE_CASE				)
        pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE				)

        UpperCamelCase      = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE				)
        UpperCamelCase      = pipe(**_SCREAMING_SNAKE_CASE				)
        UpperCamelCase      = output.audios

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

        assert audio.shape == (1, 2, components["unet"].sample_size)
        UpperCamelCase      = np.array([-0.7_2_6_5, 1.0_0_0_0, -0.8_3_8_8, 0.1_1_7_5, 0.9_4_9_8, -1.0_0_0_0]				)
        assert np.abs(audio_slice.flatten() - expected_slice				).max() < 1e-2

  @skip_mps
  def   A__						(				self				)  ->				int:



        """simple docstring"""






        return super().test_save_load_local()

  @skip_mps
  def   A__						(				self				)  ->				Tuple:



        """simple docstring"""






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

  @skip_mps
  def   A__						(				self				)  ->				str:



        """simple docstring"""






        return super().test_save_load_optional_components()

  @skip_mps
  def   A__						(				self				)  ->				str:



        """simple docstring"""






        return super().test_attention_slicing_forward_pass()


  def   A__						(				self				)  ->				int:



        """simple docstring"""






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






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

  def   A__						(				self				)  ->				List[str]:



        """simple docstring"""






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

  def   A__						(				self				)  ->				Tuple:



        """simple docstring"""






        UpperCamelCase      = torch_device

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

        UpperCamelCase      = torch.manual_seed(0				)
        UpperCamelCase      = pipe(generator=_SCREAMING_SNAKE_CASE      ,		num_inference_steps=100      ,		audio_length_in_s=4.0_9_6				)
        UpperCamelCase      = output.audios

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

        assert audio.shape == (1, 2, pipe.unet.sample_size)
        UpperCamelCase      = np.array([-0.0_1_9_2, -0.0_2_3_1, -0.0_3_1_8, -0.0_0_5_9, 0.0_0_0_2, -0.0_0_2_0]				)

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


  def   A__						(				self				)  ->				Optional[int]:



        """simple docstring"""






        UpperCamelCase      = torch_device

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

        UpperCamelCase      = torch.manual_seed(0				)
        UpperCamelCase      = pipe(generator=_SCREAMING_SNAKE_CASE      ,		num_inference_steps=100      ,		audio_length_in_s=4.0_9_6				)
        UpperCamelCase      = output.audios

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

        assert audio.shape == (1, 2, pipe.unet.sample_size)
        UpperCamelCase      = np.array([-0.0_3_6_7, -0.0_4_8_8, -0.0_7_7_1, -0.0_5_2_5, -0.0_4_4_4, -0.0_3_4_1]				)

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








'''simple docstring'''

import re
import string

import numpy as np

import datasets


SCREAMING_SNAKE_CASE__     =       '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n'

SCREAMING_SNAKE_CASE__     =       '\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results["exact_match"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    33.3\n\n'

SCREAMING_SNAKE_CASE__     =       '\n'






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,	_KWARGS_DESCRIPTION    )
class     a_						(      datasets.Metric    ):

  def   A__						(				self				)  ->				Optional[Any]:



        """simple docstring"""






        return datasets.MetricInfo(
            description=_DESCRIPTION      ,		citation=_CITATION      ,		inputs_description=_KWARGS_DESCRIPTION      ,		features=datasets.Features(
                {
                    """predictions""": datasets.Value("""string"""      ,		id="""sequence"""				),
                    """references""": datasets.Value("""string"""      ,		id="""sequence"""				),
                }				)      ,		reference_urls=[]      ,		)


  def   A__						(				self      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE      ,		_SCREAMING_SNAKE_CASE=None      ,		_SCREAMING_SNAKE_CASE=False      ,		_SCREAMING_SNAKE_CASE=False      ,		_SCREAMING_SNAKE_CASE=False      ,		)  ->				List[Any]:



        """simple docstring"""






        if regexes_to_ignore is not None:
              for s in regexes_to_ignore:
                    UpperCamelCase      = np.array([re.sub(_SCREAMING_SNAKE_CASE      ,		""""""      ,		_SCREAMING_SNAKE_CASE				) for x in predictions]				)
                    UpperCamelCase      = np.array([re.sub(_SCREAMING_SNAKE_CASE      ,		""""""      ,		_SCREAMING_SNAKE_CASE				) for x in references]				)
        else:
              UpperCamelCase      = np.asarray(_SCREAMING_SNAKE_CASE				)
              UpperCamelCase      = np.asarray(_SCREAMING_SNAKE_CASE				)

        if ignore_case:
              UpperCamelCase      = np.char.lower(_SCREAMING_SNAKE_CASE				)
              UpperCamelCase      = np.char.lower(_SCREAMING_SNAKE_CASE				)

        if ignore_punctuation:
              UpperCamelCase      = string.punctuation.maketrans(""""""      ,		""""""      ,		string.punctuation				)
              UpperCamelCase      = np.char.translate(_SCREAMING_SNAKE_CASE      ,		table=_SCREAMING_SNAKE_CASE				)
              UpperCamelCase      = np.char.translate(_SCREAMING_SNAKE_CASE      ,		table=_SCREAMING_SNAKE_CASE				)

        if ignore_numbers:
              UpperCamelCase      = string.digits.maketrans(""""""      ,		""""""      ,		string.digits				)
              UpperCamelCase      = np.char.translate(_SCREAMING_SNAKE_CASE      ,		table=_SCREAMING_SNAKE_CASE				)
              UpperCamelCase      = np.char.translate(_SCREAMING_SNAKE_CASE      ,		table=_SCREAMING_SNAKE_CASE				)

        UpperCamelCase      = predictions == references

        return {"exact_match": np.mean(_SCREAMING_SNAKE_CASE				) * 100}
