






"""simple docstring"""




import gc
import unittest

import numpy as np
import torch

from diffusers import (
    AudioDiffusionPipeline,
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    DiffusionPipeline,
    Mel,
    UNetaDConditionModel,
    UNetaDModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()






class 			UpperCamelCase     (      unittest.TestCase ):


 def _lowercase      (	self						:		Any				)   ->			Dict:
   super().tearDown()
   gc.collect()
   torch.cuda.empty_cache()


 @property
 def _lowercase      (	self						:		Union[str, Any]				)   ->			List[str]:
   torch.manual_seed(0				)
   _a    :			List[Any]			 =      UNetaDModel(
       sample_size=(32, 64)				,		in_channels=1				,		out_channels=1				,		layers_per_block=2				,		block_out_channels=(128, 128)				,		down_block_types=("""AttnDownBlock2D""", """DownBlock2D""")				,		up_block_types=("""UpBlock2D""", """AttnUpBlock2D""")				,		)
   return model


 @property
 def _lowercase      (	self						:		Optional[int]				)   ->			Tuple:
   torch.manual_seed(0				)
   _a    :			Any			 =      UNetaDConditionModel(
       sample_size=(64, 32)				,		in_channels=1				,		out_channels=1				,		layers_per_block=2				,		block_out_channels=(128, 128)				,		down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""")				,		up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""")				,		cross_attention_dim=10				,		)
   return model


 @property
 def _lowercase      (	self						:		Union[str, Any]				)   ->			int:
   torch.manual_seed(0				)
   _a    :			List[Any]			 =      AutoencoderKL(
       sample_size=(128, 64)				,		in_channels=1				,		out_channels=1				,		latent_channels=1				,		layers_per_block=2				,		block_out_channels=(128, 128)				,		down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""")				,		up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""")				,		)
   _a    :			Any			 =      UNetaDModel(
       sample_size=(64, 32)				,		in_channels=1				,		out_channels=1				,		layers_per_block=2				,		block_out_channels=(128, 128)				,		down_block_types=("""AttnDownBlock2D""", """DownBlock2D""")				,		up_block_types=("""UpBlock2D""", """AttnUpBlock2D""")				,		)
   return vqvae, unet







 @slow
 def _lowercase      (	self						:		List[str]				)   ->			int:
   _a    :			List[Any]			 =      "cpu"  # ensure determinism for the device-dependent torch.Generator
   _a    :			Dict			 =      Mel(
       x_res=self.dummy_unet.config.sample_size[1]				,		y_res=self.dummy_unet.config.sample_size[0]				,		)

   _a    :			Tuple			 =      DDPMScheduler()
   _a    :			int			 =      AudioDiffusionPipeline(vqvae=snake_case__				,		unet=self.dummy_unet				,		mel=snake_case__				,		scheduler=snake_case__				)
   _a    :			str			 =      pipe.to(snake_case__				)
   pipe.set_progress_bar_config(disable=snake_case__				)

   _a    :			int			 =      torch.Generator(device=snake_case__				).manual_seed(42				)
   _a    :			Optional[int]			 =      pipe(generator=snake_case__				,		steps=4				)
   _a    :			int			 =      output.audios[0]
   _a    :			str			 =      output.images[0]

   _a    :			int			 =      torch.Generator(device=snake_case__				).manual_seed(42				)
   _a    :			int			 =      pipe(generator=snake_case__				,		steps=4				,		return_dict=snake_case__				)
   _a    :			str			 =      output[0][0]

   assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length)
   assert (
       image.height == self.dummy_unet.config.sample_size[0]
       and image.width == self.dummy_unet.config.sample_size[1]
   )
   _a    :			Optional[int]			 =      np.frombuffer(image.tobytes()				,		dtype="""uint8"""				)[:10]
   _a    :			Dict			 =      np.frombuffer(image_from_tuple.tobytes()				,		dtype="""uint8"""				)[:10]
   _a    :			List[Any]			 =      np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127]				)

   assert np.abs(image_slice.flatten() - expected_slice				).max() == 0
   assert np.abs(image_from_tuple_slice.flatten() - expected_slice				).max() == 0

   _a    :			Optional[int]			 =      Mel(
       x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1]				,		y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0]				,		)

   _a    :			Optional[Any]			 =      DDIMScheduler()
   _a    :			List[str]			 =      self.dummy_vqvae_and_unet
   _a    :			List[Any]			 =      AudioDiffusionPipeline(
       vqvae=self.dummy_vqvae_and_unet[0]				,		unet=dummy_vqvae_and_unet[1]				,		mel=snake_case__				,		scheduler=snake_case__				)
   _a    :			List[str]			 =      pipe.to(snake_case__				)
   pipe.set_progress_bar_config(disable=snake_case__				)

   np.random.seed(0				)
   _a    :			int			 =      np.random.uniform(-1				,		1				,		((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,)				)
   _a    :			Union[str, Any]			 =      torch.Generator(device=snake_case__				).manual_seed(42				)
   _a    :			Optional[Any]			 =      pipe(raw_audio=snake_case__				,		generator=snake_case__				,		start_step=5				,		steps=10				)
   _a    :			Optional[Any]			 =      output.images[0]

   assert (
       image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0]
       and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1]
   )
   _a    :			Optional[int]			 =      np.frombuffer(image.tobytes()				,		dtype="""uint8"""				)[:10]
   _a    :			Dict			 =      np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121]				)

   assert np.abs(image_slice.flatten() - expected_slice				).max() == 0

   _a    :			Union[str, Any]			 =      self.dummy_unet_condition
   _a    :			Union[str, Any]			 =      AudioDiffusionPipeline(
       vqvae=self.dummy_vqvae_and_unet[0]				,		unet=snake_case__				,		mel=snake_case__				,		scheduler=snake_case__				)
   _a    :			Union[str, Any]			 =      pipe.to(snake_case__				)
   pipe.set_progress_bar_config(disable=snake_case__				)

   np.random.seed(0				)
   _a    :			Tuple			 =      torch.rand((1, 1, 10)				)
   _a    :			Union[str, Any]			 =      pipe(generator=snake_case__				,		encoding=snake_case__				)
   _a    :			Union[str, Any]			 =      output.images[0]
   _a    :			List[str]			 =      np.frombuffer(image.tobytes()				,		dtype="""uint8"""				)[:10]
   _a    :			Optional[Any]			 =      np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111]				)

   assert np.abs(image_slice.flatten() - expected_slice				).max() == 0







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


 def _lowercase      (	self						:		Union[str, Any]				)   ->			List[Any]:
   super().tearDown()
   gc.collect()
   torch.cuda.empty_cache()







 def _lowercase      (	self						:		List[Any]				)   ->			List[Any]:
   _a    :			str			 =      torch_device

   _a    :			int			 =      DiffusionPipeline.from_pretrained("""teticio/audio-diffusion-ddim-256"""				)
   _a    :			List[Any]			 =      pipe.to(snake_case__				)
   pipe.set_progress_bar_config(disable=snake_case__				)

   _a    :			int			 =      torch.Generator(device=snake_case__				).manual_seed(42				)
   _a    :			Dict			 =      pipe(generator=snake_case__				)
   _a    :			int			 =      output.audios[0]
   _a    :			List[str]			 =      output.images[0]

   assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length)
   assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1]
   _a    :			List[str]			 =      np.frombuffer(image.tobytes()				,		dtype="""uint8"""				)[:10]
   _a    :			List[Any]			 =      np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26]				)

   assert np.abs(image_slice.flatten() - expected_slice				).max() == 0



import math_equivalence  # From: git+https://github.com/hendrycks/math.git

import datasets


__lowerCamelCase				=			"""\
@article{hendrycksmath2021,
  title={Measuring Mathematical Problem Solving With the MATH Dataset},
  author={Dan Hendrycks
    and Collin Burns
    and Saurav Kadavath
    and Akul Arora
    and Steven Basart
    and Eric Tang
    and Dawn Song
    and Jacob Steinhardt},
  journal={arXiv preprint arXiv:2103.03874},
  year={2021}
}
"""


__lowerCamelCase				=			"""\
This metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.
It first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy.
"""


__lowerCamelCase				=			R"""
Calculates accuracy after canonicalizing inputs.

Args:
    predictions: list of predictions to score. Each prediction
        is a string that contains natural language and LaTex.
    references: list of reference for each prediction. Each
        reference is a string that contains natural language
        and LaTex.
Returns:
    accuracy: accuracy after canonicalizing inputs
        (e.g., converting \"1/2\" to \"\\frac{1}{2}\")

Examples:
    >>> metric = datasets.load_metric(\"competition_math\")
    >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"])
    >>> print(results)
    {'accuracy': 1.0}
"""






@datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION			,_KWARGS_DESCRIPTION					)
class     UpperCAmelCase						(		datasets.Metric					):



   def 							_SCREAMING_SNAKE_CASE  (self						:   Optional[int]					)						->      Optional[Any]:


          '''simple docstring'''


          return datasets.MetricInfo(
              description=_DESCRIPTION       ,		citation=_CITATION       ,		inputs_description=_KWARGS_DESCRIPTION       ,		features=datasets.Features(
                  {
                      "predictions": datasets.Value("string"					),
                      "references": datasets.Value("string"					),
                  }					)       ,		homepage="https://github.com/hendrycks/math"       ,		codebase_urls=["https://github.com/hendrycks/math"]       ,		)



   def 							_SCREAMING_SNAKE_CASE  (self						:   Optional[int]       ,		snake_case__						:   str       ,		snake_case__						:   List[Any]					)						->      Optional[Any]:


          '''simple docstring'''


          snake_case			:  Optional[int]     							= 0.0
          for i, j in zip(snake_case__       ,		snake_case__					):
                 n_correct += 1.0 if math_equivalence.is_equiv(snake_case__       ,		snake_case__					) else 0.0
          snake_case			:  Optional[int]     							= n_correct / len(snake_case__					)
          return {
              "accuracy": accuracy,
          }





