


'''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      a    (		unittest.TestCase	):


     """simple docstring"""






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

     @property
     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							List[Any]:
          torch.manual_seed(0      )
          __UpperCAmelCase     :			str  							=      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 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							int:
          torch.manual_seed(0      )
          __UpperCAmelCase     :			Dict  							=      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 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							str:
          torch.manual_seed(0      )
          __UpperCAmelCase     :			Union[str, 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''')							,			)
          __UpperCAmelCase     :			List[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 			lowerCamelCase__			(    self					:		Optional[int]      )						->							List[Any]:
          __UpperCAmelCase     :			List[str]  							=      '''cpu'''  # ensure determinism for the device-dependent torch.Generator
          __UpperCAmelCase     :			List[str]  							=      Mel(
              x_res=self.dummy_unet.config.sample_size[1]							,			y_res=self.dummy_unet.config.sample_size[0]							,			)

          __UpperCAmelCase     :			Dict  							=      DDPMScheduler()
          __UpperCAmelCase     :			Optional[Any]  							=      AudioDiffusionPipeline(vqvae=snake_case							,			unet=self.dummy_unet							,			mel=snake_case							,			scheduler=snake_case      )
          __UpperCAmelCase     :			Union[str, Any]  							=      pipe.to(snake_case      )
          pipe.set_progress_bar_config(disable=snake_case      )

          __UpperCAmelCase     :			Tuple  							=      torch.Generator(device=snake_case      ).manual_seed(42      )
          __UpperCAmelCase     :			Union[str, Any]  							=      pipe(generator=snake_case							,			steps=4      )
          __UpperCAmelCase     :			Any  							=      output.audios[0]
          __UpperCAmelCase     :			Optional[Any]  							=      output.images[0]

          __UpperCAmelCase     :			Dict  							=      torch.Generator(device=snake_case      ).manual_seed(42      )
          __UpperCAmelCase     :			List[Any]  							=      pipe(generator=snake_case							,			steps=4							,			return_dict=snake_case      )
          __UpperCAmelCase     :			Optional[Any]  							=      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]
          )
          __UpperCAmelCase     :			Union[str, Any]  							=      np.frombuffer(image.tobytes()							,			dtype='''uint8'''      )[:10]
          __UpperCAmelCase     :			List[str]  							=      np.frombuffer(image_from_tuple.tobytes()							,			dtype='''uint8'''      )[:10]
          __UpperCAmelCase     :			str  							=      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

          __UpperCAmelCase     :			List[Any]  							=      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]							,			)

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

          np.random.seed(0      )
          __UpperCAmelCase     :			Optional[Any]  							=      np.random.uniform(-1							,			1							,			((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,)      )
          __UpperCAmelCase     :			Optional[int]  							=      torch.Generator(device=snake_case      ).manual_seed(42      )
          __UpperCAmelCase     :			List[str]  							=      pipe(raw_audio=snake_case							,			generator=snake_case							,			start_step=5							,			steps=10      )
          __UpperCAmelCase     :			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]
          )
          __UpperCAmelCase     :			str  							=      np.frombuffer(image.tobytes()							,			dtype='''uint8'''      )[:10]
          __UpperCAmelCase     :			Union[str, Any]  							=      np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121]      )

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

          __UpperCAmelCase     :			List[Any]  							=      self.dummy_unet_condition
          __UpperCAmelCase     :			int  							=      AudioDiffusionPipeline(
              vqvae=self.dummy_vqvae_and_unet[0]							,			unet=snake_case							,			mel=snake_case							,			scheduler=snake_case      )
          __UpperCAmelCase     :			int  							=      pipe.to(snake_case      )
          pipe.set_progress_bar_config(disable=snake_case      )

          np.random.seed(0      )
          __UpperCAmelCase     :			int  							=      torch.rand((1, 1, 10)      )
          __UpperCAmelCase     :			List[str]  							=      pipe(generator=snake_case							,			encoding=snake_case      )
          __UpperCAmelCase     :			List[str]  							=      output.images[0]
          __UpperCAmelCase     :			Optional[int]  							=      np.frombuffer(image.tobytes()							,			dtype='''uint8'''      )[:10]
          __UpperCAmelCase     :			List[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      a    (		unittest.TestCase	):


     """simple docstring"""






     def 			lowerCamelCase__			(    self					:		Dict      )						->							int:
          # clean up the VRAM after each test
          super().tearDown()
          gc.collect()
          torch.cuda.empty_cache()






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

          __UpperCAmelCase     :			Tuple  							=      DiffusionPipeline.from_pretrained('''teticio/audio-diffusion-ddim-256'''      )
          __UpperCAmelCase     :			Union[str, Any]  							=      pipe.to(snake_case      )
          pipe.set_progress_bar_config(disable=snake_case      )

          __UpperCAmelCase     :			Any  							=      torch.Generator(device=snake_case      ).manual_seed(42      )
          __UpperCAmelCase     :			List[Any]  							=      pipe(generator=snake_case      )
          __UpperCAmelCase     :			int  							=      output.audios[0]
          __UpperCAmelCase     :			Tuple  							=      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]
          __UpperCAmelCase     :			int  							=      np.frombuffer(image.tobytes()							,			dtype='''uint8'''      )[:10]
          __UpperCAmelCase     :			Dict  							=      np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26]      )

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



'''simple docstring'''



import os
import sys
import unittest


__UpperCAmelCase      :Optional[int]			    =       os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__UpperCAmelCase      :Dict			    =       os.path.join(git_repo_path, "src", "diffusers")



class      a    (		unittest.TestCase	):


     """simple docstring"""






     def 			lowerCamelCase__			(    self					:		Any      )						->							int:
          __UpperCAmelCase     :			Optional[Any]  							=      find_backend('''    if not is_torch_available():'''      )
          self.assertEqual(snake_case							,			'''torch'''      )

          # backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
          # self.assertEqual(backend_with_underscore, "tensorflow_text")

          __UpperCAmelCase     :			Union[str, Any]  							=      find_backend('''    if not (is_torch_available() and is_transformers_available()):'''      )
          self.assertEqual(snake_case							,			'''torch_and_transformers'''      )

          # double_backend_with_underscore = find_backend(
          #    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
          # )
          # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

          __UpperCAmelCase     :			List[str]  							=      find_backend(
              '''    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):'''      )
          self.assertEqual(snake_case							,			'''torch_and_transformers_and_onnx'''      )

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							int:
          __UpperCAmelCase     :			Tuple  							=      read_init()
          # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
          self.assertIn('''torch'''							,			snake_case      )
          self.assertIn('''torch_and_transformers'''							,			snake_case      )
          self.assertIn('''flax_and_transformers'''							,			snake_case      )
          self.assertIn('''torch_and_transformers_and_onnx'''							,			snake_case      )

          # Likewise, we can't assert on the exact content of a key
          self.assertIn('''UNet2DModel'''							,			objects['''torch''']      )
          self.assertIn('''FlaxUNet2DConditionModel'''							,			objects['''flax''']      )
          self.assertIn('''StableDiffusionPipeline'''							,			objects['''torch_and_transformers''']      )
          self.assertIn('''FlaxStableDiffusionPipeline'''							,			objects['''flax_and_transformers''']      )
          self.assertIn('''LMSDiscreteScheduler'''							,			objects['''torch_and_scipy''']      )
          self.assertIn('''OnnxStableDiffusionPipeline'''							,			objects['''torch_and_transformers_and_onnx''']      )

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							List[Any]:
          __UpperCAmelCase     :			str  							=      create_dummy_object('''CONSTANT'''							,			'''\'torch\''''      )
          self.assertEqual(snake_case							,			'''\nCONSTANT = None\n'''      )

          __UpperCAmelCase     :			Union[str, Any]  							=      create_dummy_object('''function'''							,			'''\'torch\''''      )
          self.assertEqual(
              snake_case							,			'''\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n'''      )

          __UpperCAmelCase     :			Optional[int]  							=      '''
class FakeClass(metaclass=DummyObject):
    _backends = \'torch\'

    def __init__(self, *args, **kwargs):
        requires_backends(self, \'torch\')

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, \'torch\')

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, \'torch\')
'''
          __UpperCAmelCase     :			Optional[Any]  							=      create_dummy_object('''FakeClass'''							,			'''\'torch\''''      )
          self.assertEqual(snake_case							,			snake_case      )






     def 			lowerCamelCase__			(    self					:		int      )						->							List[Any]:
          __UpperCAmelCase     :			List[str]  							=      '''# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, ["torch"])


class FakeClass(metaclass=DummyObject):
    _backends = ["torch"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, ["torch"])

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, ["torch"])

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, ["torch"])
'''
          __UpperCAmelCase     :			Optional[int]  							=      create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']}      )
          self.assertEqual(dummy_files['''torch''']							,			snake_case      )