


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




 '''simple docstring'''


 def  snake_case__   (      self						):

  """simple docstring"""







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


 @property
 def  snake_case__   (      self						):

  """simple docstring"""







  torch.manual_seed(0						)
  __A  :		Optional[int]       =			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  snake_case__   (      self						):

  """simple docstring"""







  torch.manual_seed(0						)
  __A  :		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  snake_case__   (      self						):

  """simple docstring"""







  torch.manual_seed(0						)
  __A  :		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')      ,      )
  __A  :		Union[str, 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  snake_case__   (      self						):

  """simple docstring"""







  __A  :		str       =			'cpu'  # ensure determinism for the device-dependent torch.Generator
  __A  :		int       =			Mel(
      x_res=self.dummy_unet.config.sample_size[1]      ,      y_res=self.dummy_unet.config.sample_size[0]      ,      )

  __A  :		Tuple       =			DDPMScheduler()
  __A  :		Optional[int]       =			AudioDiffusionPipeline(vqvae=__lowercase      ,      unet=self.dummy_unet      ,      mel=__lowercase      ,      scheduler=__lowercase						)
  __A  :		Dict       =			pipe.to(__lowercase						)
  pipe.set_progress_bar_config(disable=__lowercase						)

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

  __A  :		Optional[Any]       =			torch.Generator(device=__lowercase						).manual_seed(42						)
  __A  :		Optional[int]       =			pipe(generator=__lowercase      ,      steps=4      ,      return_dict=__lowercase						)
  __A  :		int       =			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  :		List[Any]       =			np.frombuffer(image_from_tuple.tobytes()      ,      dtype='uint8'						)[:10]
  __A  :		Optional[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[Any]       =			self.dummy_vqvae_and_unet
  __A  :		int       =			AudioDiffusionPipeline(
      vqvae=self.dummy_vqvae_and_unet[0]      ,      unet=dummy_vqvae_and_unet[1]      ,      mel=__lowercase      ,      scheduler=__lowercase						)
  __A  :		Dict       =			pipe.to(__lowercase						)
  pipe.set_progress_bar_config(disable=__lowercase						)

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

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

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

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




 '''simple docstring'''


 def  snake_case__   (      self						):

  """simple docstring"""







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







 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Union[str, Any]       =			torch_device

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

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

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










'''simple docstring'''
from __future__ import annotations

import math
import random
from collections.abc import Collection
from typing import overload

class 						_lowerCamelCase					:




 '''simple docstring'''


 def __init__(      self      ,      __lowercase = None						):

  """simple docstring"""







  if components is None:
   __A  :		Optional[int]       =			[]
  __A  :		Dict       =			list(__lowercase						)


 def __len__(      self						):

  """simple docstring"""







  return len(self.__components						)


 def __str__(      self						):

  """simple docstring"""







  return "(" + ",".join(map(__lowercase      ,      self.__components						)						) + ")"


 def __add__(      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		Union[str, Any]       =			len(self						)
  if size == len(__lowercase						):
   __A  :		Dict       =			[self.__components[i] + other.component(__lowercase						) for i in range(__lowercase						)]
   return Vector(__lowercase						)
  else:
   raise Exception('must have the same size'						)


 def __sub__(      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		int       =			len(self						)
  if size == len(__lowercase						):
   __A  :		str       =			[self.__components[i] - other.component(__lowercase						) for i in range(__lowercase						)]
   return Vector(__lowercase						)
  else:  # error case
   raise Exception('must have the same size'						)


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  if isinstance(__lowercase      ,      (float, int)						):
   __A  :		Dict       =			[c * other for c in self.__components]
   return Vector(__lowercase						)
  elif isinstance(__lowercase      ,      __lowercase						) and len(self						) == len(__lowercase						):
   __A  :		Optional[Any]       =			len(self						)
   __A  :		Optional[int]       =			[self.__components[i] * other.component(__lowercase						) for i in range(__lowercase						)]
   return sum(__lowercase						)
  else:  # error case
   raise Exception('invalid operand!'						)


 def  snake_case__   (      self						):

  """simple docstring"""







  return Vector(self.__components						)


 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  if isinstance(__lowercase      ,      __lowercase						) and -len(self.__components						) <= i < len(self.__components						):
   return self.__components[i]
  else:
   raise Exception('index out of range'						)


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  assert -len(self.__components						) <= pos < len(self.__components						)
  __A  :		str       =			value


 def  snake_case__   (      self						):

  """simple docstring"""







  if len(self.__components						) == 0:
   raise Exception('Vector is empty'						)
  __A  :		List[Any]       =			[c**2 for c in self.__components]
  return math.sqrt(sum(__lowercase						)						)







 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase = False						):

  """simple docstring"""







  __A  :		List[Any]       =			self * other
  __A  :		Any       =			self.euclidean_length() * other.euclidean_length()
  if deg:
   return math.degrees(math.acos(num / den						)						)
  else:
   return math.acos(num / den						)


def 			_lowercase       (				UpperCamelCase__       :					int			):
 assert isinstance(UpperCamelCase__,				UpperCamelCase__			)
 return Vector([0] * dimension			)


def 			_lowercase       (				UpperCamelCase__       :					int,				UpperCamelCase__       :					int			):
 assert isinstance(UpperCamelCase__,				UpperCamelCase__			) and (isinstance(UpperCamelCase__,				UpperCamelCase__			))
 __A  :		List[str]       =			[0] * dimension
 __A  :		Tuple       =			1
 return Vector(UpperCamelCase__			)


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					Vector,				UpperCamelCase__       :					Vector			):
 assert (
     isinstance(UpperCamelCase__,				UpperCamelCase__			)
     and isinstance(UpperCamelCase__,				UpperCamelCase__			)
     and (isinstance(UpperCamelCase__,				(int, float)			))
 )
 return x * scalar + y


def 			_lowercase       (				UpperCamelCase__       :					int,				UpperCamelCase__       :					int,				UpperCamelCase__       :					int			):
 random.seed(UpperCamelCase__			)
 __A  :		Any       =			[random.randint(UpperCamelCase__,				UpperCamelCase__			) for _ in range(UpperCamelCase__			)]
 return Vector(UpperCamelCase__			)

class 						_lowerCamelCase					:




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  __A  :		str       =			matrix
  __A  :		str       =			w
  __A  :		Dict       =			h


 def __str__(      self						):

  """simple docstring"""







  __A  :		Tuple       =			''
  for i in range(self.__height						):
   ans += "|"
   for j in range(self.__width						):
    if j < self.__width - 1:
     ans += str(self.__matrix[i][j]						) + ","
    else:
     ans += str(self.__matrix[i][j]						) + "|\n"
  return ans


 def __add__(      self      ,      __lowercase						):

  """simple docstring"""







  if self.__width == other.width() and self.__height == other.height():
   __A  :		Union[str, Any]       =			[]
   for i in range(self.__height						):
    __A  :		List[Any]       =			[
        self.__matrix[i][j] + other.component(__lowercase      ,      __lowercase						)
        for j in range(self.__width						)
    ]
    matrix.append(__lowercase						)
   return Matrix(__lowercase      ,      self.__width      ,      self.__height						)
  else:
   raise Exception('matrix must have the same dimension!'						)


 def __sub__(      self      ,      __lowercase						):

  """simple docstring"""







  if self.__width == other.width() and self.__height == other.height():
   __A  :		Dict       =			[]
   for i in range(self.__height						):
    __A  :		str       =			[
        self.__matrix[i][j] - other.component(__lowercase      ,      __lowercase						)
        for j in range(self.__width						)
    ]
    matrix.append(__lowercase						)
   return Matrix(__lowercase      ,      self.__width      ,      self.__height						)
  else:
   raise Exception('matrices must have the same dimension!'						)


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  if isinstance(__lowercase      ,      __lowercase						):  # matrix-vector
   if len(__lowercase						) == self.__width:
    __A  :		Tuple       =			zero_vector(self.__height						)
    for i in range(self.__height						):
     __A  :		Any       =			[
         self.__matrix[i][j] * other.component(__lowercase						)
         for j in range(self.__width						)
     ]
     ans.change_component(__lowercase      ,      sum(__lowercase						)						)
    return ans
   else:
    raise Exception(
        'vector must have the same size as the '
        'number of columns of the matrix!'						)
  elif isinstance(__lowercase      ,      (int, float)						):  # matrix-scalar
   __A  :		Optional[Any]       =			[
       [self.__matrix[i][j] * other for j in range(self.__width						)]
       for i in range(self.__height						)
   ]
   return Matrix(__lowercase      ,      self.__width      ,      self.__height						)
  return None


 def  snake_case__   (      self						):

  """simple docstring"""







  return self.__height


 def  snake_case__   (      self						):

  """simple docstring"""







  return self.__width


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if 0 <= x < self.__height and 0 <= y < self.__width:
   return self.__matrix[x][y]
  else:
   raise Exception('change_component: indices out of bounds'						)


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if 0 <= x < self.__height and 0 <= y < self.__width:
   __A  :		Dict       =			value
  else:
   raise Exception('change_component: indices out of bounds'						)


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if self.__height != self.__width:
   raise Exception('Matrix is not square'						)
  __A  :		Union[str, Any]       =			self.__matrix[:x] + self.__matrix[x + 1 :]
  for i in range(len(__lowercase						)						):
   __A  :		Dict       =			minor[i][:y] + minor[i][y + 1 :]
  return Matrix(__lowercase      ,      self.__width - 1      ,      self.__height - 1						).determinant()


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if self.__height != self.__width:
   raise Exception('Matrix is not square'						)
  if 0 <= x < self.__height and 0 <= y < self.__width:
   return (-1) ** (x + y) * self.minor(__lowercase      ,      __lowercase						)
  else:
   raise Exception('Indices out of bounds'						)







 def  snake_case__   (      self						):

  """simple docstring"""







  if self.__height != self.__width:
   raise Exception('Matrix is not square'						)
  if self.__height < 1:
   raise Exception('Matrix has no element'						)
  elif self.__height == 1:
   return self.__matrix[0][0]
  elif self.__height == 2:
   return (
       self.__matrix[0][0] * self.__matrix[1][1]
       - self.__matrix[0][1] * self.__matrix[1][0]
   )
  else:
   __A  :		List[str]       =			[
       self.__matrix[0][y] * self.cofactor(0      ,      __lowercase						) for y in range(self.__width						)
   ]
   return sum(__lowercase						)


def 			_lowercase       (				UpperCamelCase__       :					int			):
 __A  :		list[list[float]]       =			[[0] * n for _ in range(UpperCamelCase__			)]
 return Matrix(UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__			)


def 			_lowercase       (				UpperCamelCase__       :					int,				UpperCamelCase__       :					int,				UpperCamelCase__       :					int,				UpperCamelCase__       :					int			):
 random.seed(UpperCamelCase__			)
 __A  :		list[list[float]]       =			[
     [random.randint(UpperCamelCase__,				UpperCamelCase__			) for _ in range(UpperCamelCase__			)] for _ in range(UpperCamelCase__			)
 ]
 return Matrix(UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__			)






