





'''simple docstring'''







import unittest

import numpy as np
import PIL
import torch

from diffusers.image_processor import VaeImageProcessor


class        __a   (unittest.TestCase  ):

							@property
							def      UpperCAmelCase__						(				self				:  Dict )       ->							str:







													"""simple docstring"""
													UpperCAmelCase_      :   List[Any]      =	1
													UpperCAmelCase_      :   List[Any]      =	3
													UpperCAmelCase_      :   Dict      =	8
													UpperCAmelCase_      :   List[str]      =	8

													UpperCAmelCase_      :   Any      =	torch.rand((batch_size, num_channels, height, width) )

													return sample

							def      UpperCAmelCase__						(				self				:  List[str]							,  __magic_name__				:  Tuple )       ->							Any:







													"""simple docstring"""
													if isinstance(image[0]							,  PIL.Image.Image ):
																			return np.stack([np.array(_lowerCamelCase ) for i in image]							,  axis=0 )
													elif isinstance(_lowerCamelCase							,  torch.Tensor ):
																			return image.cpu().numpy().transpose(0							,  2							,  3							,  1 )
													return image

							def      UpperCAmelCase__						(				self				:  Dict )       ->							str:







													"""simple docstring"""
													UpperCAmelCase_      :   Any      =	VaeImageProcessor(do_resize=_lowerCamelCase							,  do_normalize=_lowerCamelCase )

													UpperCAmelCase_      :   Tuple      =	self.dummy_sample
													UpperCAmelCase_      :   int      =	self.to_np(_lowerCamelCase )

													for output_type in ["pt", "np", "pil"]:
																			UpperCAmelCase_      :   Tuple      =	image_processor.postprocess(
																			    image_processor.preprocess(_lowerCamelCase )							,  output_type=_lowerCamelCase							,  )
																			UpperCAmelCase_      :   List[str]      =	self.to_np(_lowerCamelCase )
																			UpperCAmelCase_      :   Optional[int]      =	(input_np * 2_55).round() if output_type == 'pil' else input_np
																			assert (
																			    np.abs(in_np - out_np ).max() < 1E-6
																			), F"""decoded output does not match input for output_type {output_type}"""

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







													"""simple docstring"""
													UpperCAmelCase_      :   Any      =	VaeImageProcessor(do_resize=_lowerCamelCase							,  do_normalize=_lowerCamelCase )
													UpperCAmelCase_      :   List[Any]      =	self.dummy_sample.cpu().numpy().transpose(0							,  2							,  3							,  1 )

													for output_type in ["pt", "np", "pil"]:
																			UpperCAmelCase_      :   int      =	image_processor.postprocess(image_processor.preprocess(_lowerCamelCase )							,  output_type=_lowerCamelCase )

																			UpperCAmelCase_      :   Tuple      =	self.to_np(_lowerCamelCase )
																			UpperCAmelCase_      :   List[Any]      =	(input_np * 2_55).round() if output_type == 'pil' else input_np
																			assert (
																			    np.abs(in_np - out_np ).max() < 1E-6
																			), F"""decoded output does not match input for output_type {output_type}"""

							def      UpperCAmelCase__						(				self				:  Tuple )       ->							Dict:







													"""simple docstring"""
													UpperCAmelCase_      :   List[str]      =	VaeImageProcessor(do_resize=_lowerCamelCase							,  do_normalize=_lowerCamelCase )

													UpperCAmelCase_      :   Optional[Any]      =	self.dummy_sample.cpu().numpy().transpose(0							,  2							,  3							,  1 )
													UpperCAmelCase_      :   List[Any]      =	image_processor.numpy_to_pil(_lowerCamelCase )

													for output_type in ["pt", "np", "pil"]:
																			UpperCAmelCase_      :   str      =	image_processor.postprocess(image_processor.preprocess(_lowerCamelCase )							,  output_type=_lowerCamelCase )
																			for i, o in zip(_lowerCamelCase							,  _lowerCamelCase ):
																									UpperCAmelCase_      :   str      =	np.array(_lowerCamelCase )
																									UpperCAmelCase_      :   int      =	self.to_np(_lowerCamelCase ) if output_type == 'pil' else (self.to_np(_lowerCamelCase ) * 2_55).round()
																									assert (
																									    np.abs(in_np - out_np ).max() < 1E-6
																									), F"""decoded output does not match input for output_type {output_type}"""

							def      UpperCAmelCase__						(				self				:  Optional[Any] )       ->							Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_      :   Optional[int]      =	VaeImageProcessor(do_resize=_lowerCamelCase							,  do_normalize=_lowerCamelCase )

													UpperCAmelCase_      :   Any      =	self.dummy_sample
													UpperCAmelCase_      :   Optional[Any]      =	input_pt_ad.squeeze(0 )

													UpperCAmelCase_      :   Dict      =	image_processor.postprocess(
													    image_processor.preprocess(_lowerCamelCase )							,  output_type='''np'''							,  )
													UpperCAmelCase_      :   List[Any]      =	image_processor.postprocess(
													    image_processor.preprocess(_lowerCamelCase )							,  output_type='''np'''							,  )

													UpperCAmelCase_      :   Dict      =	self.to_np(self.dummy_sample )
													UpperCAmelCase_      :   Any      =	input_np_ad.squeeze(0 )

													UpperCAmelCase_      :   int      =	image_processor.postprocess(
													    image_processor.preprocess(_lowerCamelCase )							,  output_type='''np'''							,  )
													UpperCAmelCase_      :   Union[str, Any]      =	image_processor.postprocess(
													    image_processor.preprocess(_lowerCamelCase )							,  output_type='''np'''							,  )

													assert np.abs(out_pt_ad - out_pt_ad ).max() < 1E-6
													assert np.abs(out_np_ad - out_np_ad ).max() < 1E-6



							def      UpperCAmelCase__						(				self				:  List[str] )       ->							Optional[int]:







													"""simple docstring"""
													UpperCAmelCase_      :   Tuple      =	VaeImageProcessor(do_resize=_lowerCamelCase							,  do_normalize=_lowerCamelCase )

													UpperCAmelCase_      :   Optional[int]      =	self.dummy_sample
													UpperCAmelCase_      :   Dict      =	list(_lowerCamelCase )

													UpperCAmelCase_      :   Dict      =	image_processor.postprocess(
													    image_processor.preprocess(_lowerCamelCase )							,  output_type='''np'''							,  )

													UpperCAmelCase_      :   int      =	image_processor.postprocess(
													    image_processor.preprocess(_lowerCamelCase )							,  output_type='''np'''							,  )

													UpperCAmelCase_      :   int      =	self.to_np(self.dummy_sample )
													list(_lowerCamelCase )

													UpperCAmelCase_      :   Dict      =	image_processor.postprocess(
													    image_processor.preprocess(_lowerCamelCase )							,  output_type='''np'''							,  )

													UpperCAmelCase_      :   str      =	image_processor.postprocess(
													    image_processor.preprocess(_lowerCamelCase )							,  output_type='''np'''							,  )

													assert np.abs(out_pt_ad - out_pt_list ).max() < 1E-6
													assert np.abs(out_np_ad - out_np_list ).max() < 1E-6






'''simple docstring'''
import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, LDMSuperResolutionPipeline, UNetaDModel, VQModel
from diffusers.utils import PIL_INTERPOLATION, floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch


enable_full_determinism()






class       __lowercase		(    unittest.TestCase    ):







     """simple docstring"""






     @property
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Dict		     =	1
         __UpperCamelCase						:						Union[str, Any]		     =	3
         __UpperCamelCase						:						Tuple		     =	(3_2, 3_2)

         __UpperCamelCase						:						List[Any]		     =	floats_tensor((batch_size, num_channels) + sizes  ,      rng=random.Random(0     )     ).to(_lowerCamelCase     )
         return image







     @property
     def lowerCAmelCase  (		self     ):
         torch.manual_seed(0     )
         __UpperCamelCase						:						Dict		     =	UNetaDModel(
             block_out_channels=(3_2, 6_4)  ,      layers_per_block=2  ,      sample_size=3_2  ,      in_channels=6  ,      out_channels=3  ,      down_block_types=('DownBlock2D', 'AttnDownBlock2D')  ,      up_block_types=('AttnUpBlock2D', 'UpBlock2D')  ,      )
         return model







     @property
     def lowerCAmelCase  (		self     ):
         torch.manual_seed(0     )
         __UpperCamelCase						:						List[str]		     =	VQModel(
             block_out_channels=[3_2, 6_4]  ,      in_channels=3  ,      out_channels=3  ,      down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']  ,      up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']  ,      latent_channels=3  ,      )
         return model







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Tuple		     =	'cpu'
         __UpperCamelCase						:						Union[str, Any]		     =	self.dummy_uncond_unet
         __UpperCamelCase						:						List[str]		     =	DDIMScheduler()
         __UpperCamelCase						:						Any		     =	self.dummy_vq_model

         __UpperCamelCase						:						Tuple		     =	LDMSuperResolutionPipeline(unet=_lowerCamelCase  ,      vqvae=_lowerCamelCase  ,      scheduler=_lowerCamelCase     )
         ldm.to(_lowerCamelCase     )
         ldm.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase						:						int		     =	self.dummy_image.to(_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	torch.Generator(device=_lowerCamelCase     ).manual_seed(0     )
         __UpperCamelCase						:						Union[str, Any]		     =	ldm(image=_lowerCamelCase  ,      generator=_lowerCamelCase  ,      num_inference_steps=2  ,      output_type='numpy'     ).images

         __UpperCamelCase						:						str		     =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 6_4, 6_4, 3)
         __UpperCamelCase						:						str		     =	np.array([0.8_6_7_8, 0.8_2_4_5, 0.6_3_8_1, 0.6_8_3_0, 0.4_3_8_5, 0.5_5_9_9, 0.4_6_4_1, 0.6_2_0_1, 0.5_1_5_0]     )

         assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2







     @unittest.skipIf(torch_device != 'cuda'  ,      'This test requires a GPU'     )
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[Any]		     =	self.dummy_uncond_unet
         __UpperCamelCase						:						Optional[int]		     =	DDIMScheduler()
         __UpperCamelCase						:						Any		     =	self.dummy_vq_model

         # put models in fp16
         __UpperCamelCase						:						str		     =	unet.half()
         __UpperCamelCase						:						Optional[Any]		     =	vqvae.half()

         __UpperCamelCase						:						Optional[int]		     =	LDMSuperResolutionPipeline(unet=_lowerCamelCase  ,      vqvae=_lowerCamelCase  ,      scheduler=_lowerCamelCase     )
         ldm.to(_lowerCamelCase     )
         ldm.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase						:						Dict		     =	self.dummy_image.to(_lowerCamelCase     )

         __UpperCamelCase						:						Optional[Any]		     =	ldm(_lowerCamelCase  ,      num_inference_steps=2  ,      output_type='numpy'     ).images

         assert image.shape == (1, 6_4, 6_4, 3)






@slow
@require_torch
class       __lowercase		(    unittest.TestCase    ):







     """simple docstring"""






     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						List[Any]		     =	load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/vq_diffusion/teddy_bear_pool.png'     )
         __UpperCamelCase						:						List[Any]		     =	init_image.resize((6_4, 6_4)  ,      resample=PIL_INTERPOLATION['lanczos']     )

         __UpperCamelCase						:						List[str]		     =	LDMSuperResolutionPipeline.from_pretrained('duongna/ldm-super-resolution'  ,      device_map='auto'     )
         ldm.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	torch.manual_seed(0     )
         __UpperCamelCase						:						Dict		     =	ldm(image=_lowerCamelCase  ,      generator=_lowerCamelCase  ,      num_inference_steps=2_0  ,      output_type='numpy'     ).images

         __UpperCamelCase						:						List[Any]		     =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 2_5_6, 2_5_6, 3)
         __UpperCamelCase						:						str		     =	np.array([0.7_6_4_4, 0.7_6_7_9, 0.7_6_4_2, 0.7_6_3_3, 0.7_6_6_6, 0.7_5_6_0, 0.7_4_2_5, 0.7_2_5_7, 0.6_9_0_7]     )

         assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2



