


'''simple docstring'''
import json
import os
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import ImageGPTImageProcessor

class 						_lowerCamelCase					(    unittest.TestCase				):




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase=7      ,      __lowercase=3      ,      __lowercase=18      ,      __lowercase=30      ,      __lowercase=400      ,      __lowercase=True      ,      __lowercase=None      ,      __lowercase=True      ,      ):

  """simple docstring"""







  __A  :		Any       =			size if size is not None else {'height': 18, 'width': 18}
  __A  :		Optional[Any]       =			parent
  __A  :		int       =			batch_size
  __A  :		str       =			num_channels
  __A  :		List[str]       =			image_size
  __A  :		Optional[int]       =			min_resolution
  __A  :		int       =			max_resolution
  __A  :		int       =			do_resize
  __A  :		Union[str, Any]       =			size
  __A  :		Optional[Any]       =			do_normalize







 def  snake_case__   (      self						):

  """simple docstring"""







  return {
      # here we create 2 clusters for the sake of simplicity
      "clusters": np.asarray(
          [
              [0.8_8_6_6_4_4_3_6_3_4_0_3_3_2_0_3, 0.6_6_1_8_8_2_9_3_6_9_5_4_4_9_8_3, 0.3_8_9_1_7_4_6_4_0_1_7_8_6_8_0_4],
              [-0.6_0_4_2_5_5_9_1_4_6_8_8_1_1_0_4, -0.0_2_2_9_5_0_0_8_8_6_0_5_2_8_4_6_9, 0.5_4_2_3_7_9_7_3_6_9_0_0_3_2_9_6],
          ]						),
      "do_resize": self.do_resize,
      "size": self.size,
      "do_normalize": self.do_normalize,
  }


@require_torch
@require_vision
class 						_lowerCamelCase					(    snake_case_    ,		unittest.TestCase				):




 '''simple docstring'''
 __lowercase				:		int    							=						ImageGPTImageProcessor if is_vision_available() else None


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		str       =			ImageGPTImageProcessingTester(self						)


 @property
 def  snake_case__   (      self						):

  """simple docstring"""







  return self.image_processor_tester.prepare_image_processor_dict()


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Any       =			self.image_processing_class(**self.image_processor_dict						)
  self.assertTrue(hasattr(__lowercase      ,      'clusters'						)						)
  self.assertTrue(hasattr(__lowercase      ,      'do_resize'						)						)
  self.assertTrue(hasattr(__lowercase      ,      'size'						)						)
  self.assertTrue(hasattr(__lowercase      ,      'do_normalize'						)						)


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		List[Any]       =			self.image_processing_class.from_dict(self.image_processor_dict						)
  self.assertEqual(image_processor.size      ,      {'height': 18, 'width': 18}						)

  __A  :		Any       =			self.image_processing_class.from_dict(self.image_processor_dict      ,      size=42						)
  self.assertEqual(image_processor.size      ,      {'height': 42, 'width': 42}						)


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Union[str, Any]       =			self.image_processing_class(**self.image_processor_dict						)
  __A  :		List[str]       =			json.loads(image_processor.to_json_string()						)
  for key, value in self.image_processor_dict.items():
   if key == "clusters":
    self.assertTrue(np.array_equal(__lowercase      ,      obj[key]						)						)
   else:
    self.assertEqual(obj[key]      ,      __lowercase						)


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Optional[Any]       =			self.image_processing_class(**self.image_processor_dict						)

  with tempfile.TemporaryDirectory() as tmpdirname:
   __A  :		Any       =			os.path.join(__lowercase      ,      'image_processor.json'						)
   image_processor_first.to_json_file(__lowercase						)
   __A  :		Any       =			self.image_processing_class.from_json_file(__lowercase						).to_dict()

  __A  :		str       =			image_processor_first.to_dict()
  for key, value in image_processor_first.items():
   if key == "clusters":
    self.assertTrue(np.array_equal(__lowercase      ,      image_processor_second[key]						)						)
   else:
    self.assertEqual(image_processor_first[key]      ,      __lowercase						)


 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Any       =			self.image_processing_class(**self.image_processor_dict						)

  with tempfile.TemporaryDirectory() as tmpdirname:
   image_processor_first.save_pretrained(__lowercase						)
   __A  :		List[Any]       =			self.image_processing_class.from_pretrained(__lowercase						).to_dict()

  __A  :		int       =			image_processor_first.to_dict()
  for key, value in image_processor_first.items():
   if key == "clusters":
    self.assertTrue(np.array_equal(__lowercase      ,      image_processor_second[key]						)						)
   else:
    self.assertEqual(image_processor_first[key]      ,      __lowercase						)







 @unittest.skip('ImageGPT requires clusters at initialization'						)
 def  snake_case__   (      self						):

  """simple docstring"""







  pass


def 			_lowercase       (				):
 __A  :		Optional[Any]       =			load_dataset('hf-internal-testing/fixtures_image_utils',				split='test'			)

 __A  :		Any       =			Image.open(dataset[4]['file']			)
 __A  :		Tuple       =			Image.open(dataset[5]['file']			)

 __A  :		Union[str, Any]       =			[imagea, imagea]

 return images


@require_vision
@require_torch
class 						_lowerCamelCase					(    unittest.TestCase				):




 '''simple docstring'''


 @slow
 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Any       =			ImageGPTImageProcessor.from_pretrained('openai/imagegpt-small'						)

  __A  :		Union[str, Any]       =			prepare_images()

  # test non-batched
  __A  :		str       =			image_processing(images[0]      ,      return_tensors='pt'						)

  self.assertIsInstance(encoding.input_ids      ,      torch.LongTensor						)
  self.assertEqual(encoding.input_ids.shape      ,      (1, 1_024)						)

  __A  :		str       =			[306, 191, 191]
  self.assertEqual(encoding.input_ids[0, :3].tolist()      ,      __lowercase						)

  # test batched
  __A  :		str       =			image_processing(__lowercase      ,      return_tensors='pt'						)

  self.assertIsInstance(encoding.input_ids      ,      torch.LongTensor						)
  self.assertEqual(encoding.input_ids.shape      ,      (2, 1_024)						)

  __A  :		Any       =			[303, 13, 13]
  self.assertEqual(encoding.input_ids[1, -3:].tolist()      ,      __lowercase						)










'''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






