





"""simple docstring"""




import copy
import re



class     _UpperCAmelCase   :

  """simple docstring"""


  a_      =			'''hp'''
  a_      =			{}
  a_      =			None






  @classmethod
  def     lowercase		(    cls			:		str ,  lowerCAmelCase_			:		Optional[int] ,  lowerCAmelCase_			:		Dict					)							->						Optional[Any]:
     __lowerCAmelCase							     =     prefix
     __lowerCAmelCase							     =     defaults
     cls.build_naming_info()






  @staticmethod
  def     lowercase		(    lowerCAmelCase_			:		List[str] ,  lowerCAmelCase_			:		int					)							->						Optional[Any]:






     if len(_a					) == 0:
        return ""
     __lowerCAmelCase							     =     None
     if any(char.isdigit() for char in word					):
        raise Exception(f"""Parameters should not contain numbers: '{word}' contains a number"""					)
     if word in info["short_word"]:
        return info["short_word"][word]
     for prefix_len in range(1 ,  len(_a					) + 1					):
        __lowerCAmelCase							     =     word[:prefix_len]
        if prefix in info["reverse_short_word"]:
           continue
        else:
           __lowerCAmelCase							     =     prefix
           break

     if short_word is None:
        # Paranoid fallback
        def int_to_alphabetic(lowerCAmelCase_			:		Optional[Any]					):
           __lowerCAmelCase							     =     ''
           while integer != 0:
              __lowerCAmelCase							     =     chr(ord('A'					) + integer % 1_0					) + s
              integer //= 1_0
           return s

        __lowerCAmelCase							     =     0
        while True:
           __lowerCAmelCase							     =     word + '#' + int_to_alphabetic(_a					)
           if sword in info["reverse_short_word"]:
              continue
           else:
              __lowerCAmelCase							     =     sword
              break

     __lowerCAmelCase							     =     short_word
     __lowerCAmelCase							     =     word
     return short_word






  @staticmethod
  def     lowercase		(    lowerCAmelCase_			:		int ,  lowerCAmelCase_			:		Dict					)							->						Union[str, Any]:
     __lowerCAmelCase							     =     param_name.split('_'					)

     __lowerCAmelCase							     =     [TrialShortNamer.shortname_for_word(_a ,  _a					) for word in words]

     # We try to create a separatorless short name, but if there is a collision we have to fallback
     # to a separated short name
     __lowerCAmelCase							     =     ['', '_']

     for separator in separators:
        __lowerCAmelCase							     =     separator.join(_a					)
        if shortname not in info["reverse_short_param"]:
           __lowerCAmelCase							     =     shortname
           __lowerCAmelCase							     =     param_name
           return shortname

     return param_name






  @staticmethod
  def     lowercase		(    lowerCAmelCase_			:		Optional[Any] ,  lowerCAmelCase_			:		Any					)							->						Optional[int]:
     __lowerCAmelCase							     =     TrialShortNamer.shortname_for_key(_a ,  _a					)
     __lowerCAmelCase							     =     short_name
     __lowerCAmelCase							     =     param_name






  @classmethod
  def     lowercase		(    cls			:		Any					)							->						Dict:






     if cls.NAMING_INFO is not None:
        return

     __lowerCAmelCase							     =     {
         'short_word': {},
         'reverse_short_word': {},
         'short_param': {},
         'reverse_short_param': {},
     }

     __lowerCAmelCase							     =     list(cls.DEFAULTS.keys()					)

     for k in field_keys:
        cls.add_new_param_name(_a ,  _a					)

     __lowerCAmelCase							     =     info






  @classmethod
  def     lowercase		(    cls			:		List[str] ,  lowerCAmelCase_			:		Tuple					)							->						int:
     cls.build_naming_info()
     assert cls.PREFIX is not None
     __lowerCAmelCase							     =     [copy.copy(cls.PREFIX					)]

     for k, v in params.items():
        if k not in cls.DEFAULTS:
           raise Exception(f"""You should provide a default value for the param name {k} with value {v}"""					)
        if v == cls.DEFAULTS[k]:
           # The default value is not added to the name
           continue

        __lowerCAmelCase							     =     cls.NAMING_INFO['short_param'][k]

        if isinstance(_a ,  _a					):
           __lowerCAmelCase							     =     1 if v else 0

        __lowerCAmelCase							     =     '' if isinstance(_a ,  (int, float)					) else '-'
        __lowerCAmelCase							     =     f"""{key}{sep}{v}"""
        name.append(_a					)

     return "_".join(_a					)






  @classmethod
  def     lowercase		(    cls			:		List[str] ,  lowerCAmelCase_			:		str					)							->						List[str]:
     __lowerCAmelCase							     =     repr[len(cls.PREFIX					) + 1 :]
     if repr == "":
        __lowerCAmelCase							     =     []
     else:
        __lowerCAmelCase							     =     repr.split('_'					)

     __lowerCAmelCase							     =     {}

     for value in values:
        if "-" in value:
           __lowerCAmelCase							     =     value.split('-'					)
        else:
           __lowerCAmelCase							     =     re.sub('[0-9.]' ,  '' ,  _a					)
           __lowerCAmelCase							     =     float(re.sub('[^0-9.]' ,  '' ,  _a					)					)

        __lowerCAmelCase							     =     cls.NAMING_INFO['reverse_short_param'][p_k]

        __lowerCAmelCase							     =     p_v

     for k in cls.DEFAULTS:
        if k not in parameters:
           __lowerCAmelCase							     =     cls.DEFAULTS[k]

     return parameters








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

  """simple docstring"""


  def     lowercase		(    self			:		List[str]					)							->						int:
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()






  @property
  def     lowercase		(    self			:		Union[str, Any]					)							->						Any:
     torch.manual_seed(0					)
     __lowerCAmelCase							     =     UNetaDModel(
         sample_size=(3_2, 6_4) ,  in_channels=1 ,  out_channels=1 ,  layers_per_block=2 ,  block_out_channels=(1_2_8, 1_2_8) ,  down_block_types=('AttnDownBlock2D', 'DownBlock2D') ,  up_block_types=('UpBlock2D', 'AttnUpBlock2D') ,  )
     return model






  @property
  def     lowercase		(    self			:		Optional[Any]					)							->						List[Any]:
     torch.manual_seed(0					)
     __lowerCAmelCase							     =     UNetaDConditionModel(
         sample_size=(6_4, 3_2) ,  in_channels=1 ,  out_channels=1 ,  layers_per_block=2 ,  block_out_channels=(1_2_8, 1_2_8) ,  down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') ,  up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') ,  cross_attention_dim=1_0 ,  )
     return model






  @property
  def     lowercase		(    self			:		Dict					)							->						Optional[Any]:
     torch.manual_seed(0					)
     __lowerCAmelCase							     =     AutoencoderKL(
         sample_size=(1_2_8, 6_4) ,  in_channels=1 ,  out_channels=1 ,  latent_channels=1 ,  layers_per_block=2 ,  block_out_channels=(1_2_8, 1_2_8) ,  down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') ,  up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') ,  )
     __lowerCAmelCase							     =     UNetaDModel(
         sample_size=(6_4, 3_2) ,  in_channels=1 ,  out_channels=1 ,  layers_per_block=2 ,  block_out_channels=(1_2_8, 1_2_8) ,  down_block_types=('AttnDownBlock2D', 'DownBlock2D') ,  up_block_types=('UpBlock2D', 'AttnUpBlock2D') ,  )
     return vqvae, unet






  @slow
  def     lowercase		(    self			:		Dict					)							->						Optional[Any]:
     __lowerCAmelCase							     =     'cpu'  # ensure determinism for the device-dependent torch.Generator
     __lowerCAmelCase							     =     Mel(
         x_res=self.dummy_unet.config.sample_size[1] ,  y_res=self.dummy_unet.config.sample_size[0] ,  )

     __lowerCAmelCase							     =     DDPMScheduler()
     __lowerCAmelCase							     =     AudioDiffusionPipeline(vqvae=lowerCAmelCase_ ,  unet=self.dummy_unet ,  mel=lowerCAmelCase_ ,  scheduler=lowerCAmelCase_					)
     __lowerCAmelCase							     =     pipe.to(lowerCAmelCase_					)
     pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

     __lowerCAmelCase							     =     torch.Generator(device=lowerCAmelCase_					).manual_seed(4_2					)
     __lowerCAmelCase							     =     pipe(generator=lowerCAmelCase_ ,  steps=4					)
     __lowerCAmelCase							     =     output.audios[0]
     __lowerCAmelCase							     =     output.images[0]

     __lowerCAmelCase							     =     torch.Generator(device=lowerCAmelCase_					).manual_seed(4_2					)
     __lowerCAmelCase							     =     pipe(generator=lowerCAmelCase_ ,  steps=4 ,  return_dict=lowerCAmelCase_					)
     __lowerCAmelCase							     =     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]
     )
     __lowerCAmelCase							     =     np.frombuffer(image.tobytes() ,  dtype='uint8'					)[:1_0]
     __lowerCAmelCase							     =     np.frombuffer(image_from_tuple.tobytes() ,  dtype='uint8'					)[:1_0]
     __lowerCAmelCase							     =     np.array([6_9, 2_5_5, 2_5_5, 2_5_5, 0, 0, 7_7, 1_8_1, 1_2, 1_2_7]					)

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

     __lowerCAmelCase							     =     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] ,  )

     __lowerCAmelCase							     =     DDIMScheduler()
     __lowerCAmelCase							     =     self.dummy_vqvae_and_unet
     __lowerCAmelCase							     =     AudioDiffusionPipeline(
         vqvae=self.dummy_vqvae_and_unet[0] ,  unet=dummy_vqvae_and_unet[1] ,  mel=lowerCAmelCase_ ,  scheduler=lowerCAmelCase_					)
     __lowerCAmelCase							     =     pipe.to(lowerCAmelCase_					)
     pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

     np.random.seed(0					)
     __lowerCAmelCase							     =     np.random.uniform(-1 ,  1 ,  ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,)					)
     __lowerCAmelCase							     =     torch.Generator(device=lowerCAmelCase_					).manual_seed(4_2					)
     __lowerCAmelCase							     =     pipe(raw_audio=lowerCAmelCase_ ,  generator=lowerCAmelCase_ ,  start_step=5 ,  steps=1_0					)
     __lowerCAmelCase							     =     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]
     )
     __lowerCAmelCase							     =     np.frombuffer(image.tobytes() ,  dtype='uint8'					)[:1_0]
     __lowerCAmelCase							     =     np.array([1_2_0, 1_1_7, 1_1_0, 1_0_9, 1_3_8, 1_6_7, 1_3_8, 1_4_8, 1_3_2, 1_2_1]					)

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

     __lowerCAmelCase							     =     self.dummy_unet_condition
     __lowerCAmelCase							     =     AudioDiffusionPipeline(
         vqvae=self.dummy_vqvae_and_unet[0] ,  unet=lowerCAmelCase_ ,  mel=lowerCAmelCase_ ,  scheduler=lowerCAmelCase_					)
     __lowerCAmelCase							     =     pipe.to(lowerCAmelCase_					)
     pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

     np.random.seed(0					)
     __lowerCAmelCase							     =     torch.rand((1, 1, 1_0)					)
     __lowerCAmelCase							     =     pipe(generator=lowerCAmelCase_ ,  encoding=lowerCAmelCase_					)
     __lowerCAmelCase							     =     output.images[0]
     __lowerCAmelCase							     =     np.frombuffer(image.tobytes() ,  dtype='uint8'					)[:1_0]
     __lowerCAmelCase							     =     np.array([1_0_7, 1_0_3, 1_2_0, 1_2_7, 1_4_2, 1_2_2, 1_1_3, 1_2_2, 9_7, 1_1_1]					)

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





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

  """simple docstring"""


  def     lowercase		(    self			:		List[Any]					)							->						Optional[int]:
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()






  def     lowercase		(    self			:		Union[str, Any]					)							->						Optional[int]:
     __lowerCAmelCase							     =     torch_device

     __lowerCAmelCase							     =     DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256'					)
     __lowerCAmelCase							     =     pipe.to(lowerCAmelCase_					)
     pipe.set_progress_bar_config(disable=lowerCAmelCase_					)

     __lowerCAmelCase							     =     torch.Generator(device=lowerCAmelCase_					).manual_seed(4_2					)
     __lowerCAmelCase							     =     pipe(generator=lowerCAmelCase_					)
     __lowerCAmelCase							     =     output.audios[0]
     __lowerCAmelCase							     =     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]
     __lowerCAmelCase							     =     np.frombuffer(image.tobytes() ,  dtype='uint8'					)[:1_0]
     __lowerCAmelCase							     =     np.array([1_5_1, 1_6_7, 1_5_4, 1_4_4, 1_2_2, 1_3_4, 1_2_1, 1_0_5, 7_0, 2_6]					)

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

