






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
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 ChineseCLIPImageProcessor


class      __SCREAMING_SNAKE_CASE(		unittest.TestCase		):
							def __init__(   self:					Union[str, Any]				,		UpperCamelCase:					int				,		UpperCamelCase:					List[Any]=7				,		UpperCamelCase:					Any=3				,		UpperCamelCase:					Optional[Any]=18				,		UpperCamelCase:					Any=30				,		UpperCamelCase:					List[str]=4_00				,		UpperCamelCase:					Dict=True				,		UpperCamelCase:					int=None				,		UpperCamelCase:					Optional[Any]=True				,		UpperCamelCase:					str=None				,		UpperCamelCase:					Optional[int]=True				,		UpperCamelCase:					Any=[0.48_145_466, 0.4_578_275, 0.40_821_073]				,		UpperCamelCase:					str=[0.26_862_954, 0.26_130_258, 0.27_577_711]				,		UpperCamelCase:					Optional[int]=True				,		)						->						str:
											snake_case__													=   size if size is not None else {'height': 2_24, 'width': 2_24}
											snake_case__													=   crop_size if crop_size is not None else {'height': 18, 'width': 18}
											snake_case__													=   parent
											snake_case__													=   batch_size
											snake_case__													=   num_channels
											snake_case__													=   image_size
											snake_case__													=   min_resolution
											snake_case__													=   max_resolution
											snake_case__													=   do_resize
											snake_case__													=   size
											snake_case__													=   do_center_crop
											snake_case__													=   crop_size
											snake_case__													=   do_normalize
											snake_case__													=   image_mean
											snake_case__													=   image_std
											snake_case__													=   do_convert_rgb
							def lowerCAmelCase_       (   self:					Optional[int]  )						->						int:
											return {
											    "do_resize": self.do_resize,
											    "size": self.size,
											    "do_center_crop": self.do_center_crop,
											    "crop_size": self.crop_size,
											    "do_normalize": self.do_normalize,
											    "image_mean": self.image_mean,
											    "image_std": self.image_std,
											    "do_convert_rgb": self.do_convert_rgb,
											}


							def lowerCAmelCase_       (   self:					Optional[int]				,		UpperCamelCase:					Optional[Any]=False				,		UpperCamelCase:					Union[str, Any]=False				,		UpperCamelCase:					int=False  )						->						Dict:
											assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

											if equal_resolution:
															snake_case__													=   []
															for i in range(self.batch_size  ):
																			image_inputs.append(
																			    np.random.randint(
																			        2_55				,		size=(self.num_channels, self.max_resolution, self.max_resolution)				,		dtype=np.uinta  )  )
											else:
															snake_case__													=   []
															for i in range(self.batch_size  ):
																			snake_case__													=   np.random.choice(np.arange(self.min_resolution				,		self.max_resolution  )				,		2  )
																			image_inputs.append(np.random.randint(2_55				,		size=(self.num_channels, width, height)				,		dtype=np.uinta  )  )

											if not numpify and not torchify:
															# PIL expects the channel dimension as last dimension
															snake_case__													=   [Image.fromarray(np.moveaxis(_a				,		0				,		-1  )  ) for x in image_inputs]

											if torchify:
															snake_case__													=   [torch.from_numpy(_a  ) for x in image_inputs]

											return image_inputs


@require_torch
@require_vision
class      __SCREAMING_SNAKE_CASE(		lowercase__			,     unittest.TestCase		):
							_UpperCAmelCase       			=				ChineseCLIPImageProcessor if is_vision_available() else None
							def lowerCAmelCase_       (   self:					Union[str, Any]  )						->						Optional[Any]:
											snake_case__													=   ChineseCLIPImageProcessingTester(self				,		do_center_crop=_a  )
							@property
							def lowerCAmelCase_       (   self:					Tuple  )						->						str:
											return self.image_processor_tester.prepare_image_processor_dict()
							def lowerCAmelCase_       (   self:					List[Any]  )						->						Tuple:
											snake_case__													=   self.image_processing_class(**self.image_processor_dict  )
											self.assertTrue(hasattr(_a				,		'do_resize'  )  )
											self.assertTrue(hasattr(_a				,		'size'  )  )
											self.assertTrue(hasattr(_a				,		'do_center_crop'  )  )
											self.assertTrue(hasattr(_a				,		'center_crop'  )  )
											self.assertTrue(hasattr(_a				,		'do_normalize'  )  )
											self.assertTrue(hasattr(_a				,		'image_mean'  )  )
											self.assertTrue(hasattr(_a				,		'image_std'  )  )
											self.assertTrue(hasattr(_a				,		'do_convert_rgb'  )  )
							def lowerCAmelCase_       (   self:					Tuple  )						->						List[Any]:
											snake_case__													=   self.image_processing_class.from_dict(self.image_processor_dict  )
											self.assertEqual(image_processor.size				,		{'height': 2_24, 'width': 2_24}  )
											self.assertEqual(image_processor.crop_size				,		{'height': 18, 'width': 18}  )

											snake_case__													=   self.image_processing_class.from_dict(self.image_processor_dict				,		size=42				,		crop_size=84  )
											self.assertEqual(image_processor.size				,		{'shortest_edge': 42}  )
											self.assertEqual(image_processor.crop_size				,		{'height': 84, 'width': 84}  )
							def lowerCAmelCase_       (   self:					List[str]  )						->						Any:
											pass
							def lowerCAmelCase_       (   self:					Union[str, Any]  )						->						Optional[int]:
											snake_case__													=   self.image_processing_class(**self.image_processor_dict  )
											# create random PIL images
											snake_case__													=   self.image_processor_tester.prepare_inputs(equal_resolution=_a  )
											for image in image_inputs:
															self.assertIsInstance(_a				,		Image.Image  )

											# Test not batched input
											snake_case__													=   image_processing(image_inputs[0]				,		return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,		(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,		)

											# Test batched
											snake_case__													=   image_processing(_a				,		return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,		(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,		)
							def lowerCAmelCase_       (   self:					List[Any]  )						->						Tuple:
											snake_case__													=   self.image_processing_class(**self.image_processor_dict  )
											# create random numpy tensors
											snake_case__													=   self.image_processor_tester.prepare_inputs(equal_resolution=_a				,		numpify=_a  )
											for image in image_inputs:
															self.assertIsInstance(_a				,		np.ndarray  )

											# Test not batched input
											snake_case__													=   image_processing(image_inputs[0]				,		return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,		(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,		)

											# Test batched
											snake_case__													=   image_processing(_a				,		return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,		(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,		)


							def lowerCAmelCase_       (   self:					Dict  )						->						List[Any]:
											snake_case__													=   self.image_processing_class(**self.image_processor_dict  )
											# create random PyTorch tensors
											snake_case__													=   self.image_processor_tester.prepare_inputs(equal_resolution=_a				,		torchify=_a  )
											for image in image_inputs:
															self.assertIsInstance(_a				,		torch.Tensor  )

											# Test not batched input
											snake_case__													=   image_processing(image_inputs[0]				,		return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,		(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,		)

											# Test batched
											snake_case__													=   image_processing(_a				,		return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,		(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,		)


@require_torch
@require_vision
class      __SCREAMING_SNAKE_CASE(		lowercase__			,     unittest.TestCase		):
							_UpperCAmelCase       			=				ChineseCLIPImageProcessor if is_vision_available() else None
							def lowerCAmelCase_       (   self:					str  )						->						str:
											snake_case__													=   ChineseCLIPImageProcessingTester(self				,		num_channels=4				,		do_center_crop=_a  )
											snake_case__													=   3
							@property
							def lowerCAmelCase_       (   self:					str  )						->						Dict:
											return self.image_processor_tester.prepare_image_processor_dict()
							def lowerCAmelCase_       (   self:					Union[str, Any]  )						->						Optional[int]:
											snake_case__													=   self.image_processing_class(**self.image_processor_dict  )
											self.assertTrue(hasattr(_a				,		'do_resize'  )  )
											self.assertTrue(hasattr(_a				,		'size'  )  )
											self.assertTrue(hasattr(_a				,		'do_center_crop'  )  )
											self.assertTrue(hasattr(_a				,		'center_crop'  )  )
											self.assertTrue(hasattr(_a				,		'do_normalize'  )  )
											self.assertTrue(hasattr(_a				,		'image_mean'  )  )
											self.assertTrue(hasattr(_a				,		'image_std'  )  )
											self.assertTrue(hasattr(_a				,		'do_convert_rgb'  )  )
							def lowerCAmelCase_       (   self:					Tuple  )						->						List[Any]:
											pass


							def lowerCAmelCase_       (   self:					List[str]  )						->						Tuple:
											snake_case__													=   self.image_processing_class(**self.image_processor_dict  )
											# create random PIL images
											snake_case__													=   self.image_processor_tester.prepare_inputs(equal_resolution=_a  )
											for image in image_inputs:
															self.assertIsInstance(_a				,		Image.Image  )

											# Test not batched input
											snake_case__													=   image_processing(image_inputs[0]				,		return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,		(
											        1,
											        self.expected_encoded_image_num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,		)

											# Test batched
											snake_case__													=   image_processing(_a				,		return_tensors='pt'  ).pixel_values
											self.assertEqual(
											    encoded_images.shape				,		(
											        self.image_processor_tester.batch_size,
											        self.expected_encoded_image_num_channels,
											        self.image_processor_tester.crop_size['height'],
											        self.image_processor_tester.crop_size['width'],
											    )				,		)






'''simple docstring'''







import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()







class UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  @property
  def   __lowercase		(		self      :     Union[str, Any]       ):


     '''simple docstring'''






     torch.manual_seed(0       )
     _a				:	Any			=   UNetaDModel(
         block_out_channels=(32, 64)							,layers_per_block=2							,sample_size=32							,in_channels=3							,out_channels=3							,down_block_types=('DownBlock2D', 'AttnDownBlock2D')							,up_block_types=('AttnUpBlock2D', 'UpBlock2D')							,)
     return model


  @property
  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     torch.manual_seed(0       )
     _a				:	Union[str, Any]			=   VQModel(
         block_out_channels=[32, 64]							,in_channels=3							,out_channels=3							,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']							,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']							,latent_channels=3							,)
     return model


  @property
  def   __lowercase		(		self      :     Optional[int]       ):


     '''simple docstring'''






     torch.manual_seed(0       )
     _a				:	Any			=   CLIPTextConfig(
         bos_token_id=0							,eos_token_id=2							,hidden_size=32							,intermediate_size=37							,layer_norm_eps=1E-05							,num_attention_heads=4							,num_hidden_layers=5							,pad_token_id=1							,vocab_size=1000							,)
     return CLIPTextModel(_a       )


  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a				:	Dict			=   self.dummy_uncond_unet
     _a				:	List[Any]			=   DDIMScheduler()
     _a				:	List[Any]			=   self.dummy_vq_model

     _a				:	str			=   LDMPipeline(unet=_a							,vqvae=_a							,scheduler=_a       )
     ldm.to(_a       )
     ldm.set_progress_bar_config(disable=_a       )

     _a				:	List[str]			=   torch.manual_seed(0       )
     _a				:	List[str]			=   ldm(generator=_a							,num_inference_steps=2							,output_type='numpy'       ).images

     _a				:	List[str]			=   torch.manual_seed(0       )
     _a				:	Union[str, Any]			=   ldm(generator=_a							,num_inference_steps=2							,output_type='numpy'							,return_dict=_a       )[0]

     _a				:	Tuple			=   image[0, -3:, -3:, -1]
     _a				:	Optional[Any]			=   image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 64, 64, 3)
     _a				:	int			=   np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172]       )
     _a				:	Any			=   1E-2 if torch_device != 'mps' else 3E-2

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < tolerance
     assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < tolerance







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





  """simple docstring"""

  def   __lowercase		(		self      :     Optional[Any]       ):


     '''simple docstring'''






     _a				:	List[str]			=   LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256'       )
     ldm.to(_a       )
     ldm.set_progress_bar_config(disable=_a       )

     _a				:	Optional[int]			=   torch.manual_seed(0       )
     _a				:	Dict			=   ldm(generator=_a							,num_inference_steps=5							,output_type='numpy'       ).images

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

     assert image.shape == (1, 256, 256, 3)
     _a				:	Optional[int]			=   np.array([0.4399, 0.4_4975, 0.4_6825, 0.474, 0.4359, 0.4581, 0.4_5095, 0.4341, 0.4447]       )
     _a				:	int			=   1E-2 if torch_device != 'mps' else 3E-2

     assert np.abs(image_slice.flatten() - expected_slice       ).max() < tolerance



