



import gc
import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class   UpperCAmelCase_    (  __A       ,       __A       ,       unittest.TestCase			):

						'''simple docstring'''




						UpperCamelCase__     :					Optional[int]							    =    StableDiffusionXLImgaImgPipeline
						UpperCamelCase__     :					List[Any]							    =    TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
						UpperCamelCase__     :					List[Any]							    =    PipelineTesterMixin.required_optional_params - {'''latents'''}
						UpperCamelCase__     :					Tuple							    =    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
						UpperCamelCase__     :					Tuple							    =    IMAGE_TO_IMAGE_IMAGE_PARAMS
						UpperCamelCase__     :					List[str]							    =    IMAGE_TO_IMAGE_IMAGE_PARAMS






						def 			_A      (       self						):







													'''simple docstring'''

													torch.manual_seed(0						)
													__SCREAMING_SNAKE_CASE										=   UNetaDConditionModel(
													    block_out_channels=(32, 64) ,				layers_per_block=2 ,				sample_size=32 ,				in_channels=4 ,				out_channels=4 ,				down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,				up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,				attention_head_dim=(2, 4) ,				use_linear_projection=lowerCAmelCase_ ,				addition_embed_type='text_time' ,				addition_time_embed_dim=8 ,				transformer_layers_per_block=(1, 2) ,				projection_class_embeddings_input_dim=80 ,				cross_attention_dim=64 ,				)
													__SCREAMING_SNAKE_CASE										=   EulerDiscreteScheduler(
													    beta_start=0.0_0_0_8_5 ,				beta_end=0.0_1_2 ,				steps_offset=1 ,				beta_schedule='scaled_linear' ,				timestep_spacing='leading' ,				)
													torch.manual_seed(0						)
													__SCREAMING_SNAKE_CASE										=   AutoencoderKL(
													    block_out_channels=[32, 64] ,				in_channels=3 ,				out_channels=3 ,				down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] ,				up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] ,				latent_channels=4 ,				sample_size=128 ,				)
													torch.manual_seed(0						)
													__SCREAMING_SNAKE_CASE										=   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=1_000 ,				hidden_act='gelu' ,				projection_dim=32 ,				)
													__SCREAMING_SNAKE_CASE										=   CLIPTextModel(lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ,				local_files_only=lowerCAmelCase_						)

													__SCREAMING_SNAKE_CASE										=   CLIPTextModelWithProjection(lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ,				local_files_only=lowerCAmelCase_						)

													__SCREAMING_SNAKE_CASE										=   {
													    "unet": unet,
													    "scheduler": scheduler,
													    "vae": vae,
													    "text_encoder": text_encoder,
													    "tokenizer": tokenizer,
													    "text_encoder_2": text_encoder_a,
													    "tokenizer_2": tokenizer_a,
													    # "safety_checker": None,
													    # "feature_extractor": None,
													}
													return components






						def 			_A      (       self ,				_A ,				_A=0						):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE										=   floats_tensor((1, 3, 32, 32) ,				rng=random.Random(lowerCAmelCase_						)						).to(lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   image / 2 + 0.5
													if str(lowerCAmelCase_						).startswith('mps'						):
																				__SCREAMING_SNAKE_CASE										=   torch.manual_seed(lowerCAmelCase_						)
													else:
																				__SCREAMING_SNAKE_CASE										=   torch.Generator(device=lowerCAmelCase_						).manual_seed(lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   {
													    "prompt": "A painting of a squirrel eating a burger",
													    "image": image,
													    "generator": generator,
													    "num_inference_steps": 2,
													    "guidance_scale": 5.0,
													    "output_type": "numpy",
													    "strength": 0.7_5,
													}
													return inputs






						def 			_A      (       self						):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE										=   "cpu"  # ensure determinism for the device-dependent torch.Generator
													__SCREAMING_SNAKE_CASE										=   self.get_dummy_components()
													__SCREAMING_SNAKE_CASE										=   StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   sd_pipe.to(lowerCAmelCase_						)
													sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_						)

													__SCREAMING_SNAKE_CASE										=   self.get_dummy_inputs(lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   sd_pipe(**lowerCAmelCase_						).images
													__SCREAMING_SNAKE_CASE										=   image[0, -3:, -3:, -1]

													assert image.shape == (1, 32, 32, 3)

													__SCREAMING_SNAKE_CASE										=   np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5]						)

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






						def 			_A      (       self						):







													'''simple docstring'''

													super().test_attention_slicing_forward_pass(expected_max_diff=3e-3						)






						def 			_A      (       self						):







													'''simple docstring'''

													super().test_inference_batch_single_identical(expected_max_diff=3e-3						)






						def 			_A      (       self						):







													'''simple docstring'''

													pass






						def 			_A      (       self						):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE										=   self.get_dummy_components()
													__SCREAMING_SNAKE_CASE										=   StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   sd_pipe.to(lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   sd_pipe.to(lowerCAmelCase_						)
													sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_						)

													# forward without prompt embeds
													__SCREAMING_SNAKE_CASE										=   self.get_dummy_inputs(lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   3 * ["this is a negative prompt"]
													__SCREAMING_SNAKE_CASE										=   negative_prompt
													__SCREAMING_SNAKE_CASE										=   3 * [inputs["prompt"]]

													__SCREAMING_SNAKE_CASE										=   sd_pipe(**lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   output.images[0, -3:, -3:, -1]

													# forward with prompt embeds
													__SCREAMING_SNAKE_CASE										=   self.get_dummy_inputs(lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   3 * ["this is a negative prompt"]
													__SCREAMING_SNAKE_CASE										=   3 * [inputs.pop('prompt'						)]

													(
													    __SCREAMING_SNAKE_CASE      
													)										=   sd_pipe.encode_prompt(lowerCAmelCase_ ,				negative_prompt=lowerCAmelCase_						)

													__SCREAMING_SNAKE_CASE										=   sd_pipe(
													    **lowerCAmelCase_ ,				prompt_embeds=lowerCAmelCase_ ,				negative_prompt_embeds=lowerCAmelCase_ ,				pooled_prompt_embeds=lowerCAmelCase_ ,				negative_pooled_prompt_embeds=lowerCAmelCase_ ,				)
													__SCREAMING_SNAKE_CASE										=   output.images[0, -3:, -3:, -1]

													# make sure that it's equal
													assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()						).max() < 1e-4







@slow
@require_torch_gpu
class   UpperCAmelCase_    (  unittest.TestCase			):

						'''simple docstring'''




						def 			_A      (       self						):







													'''simple docstring'''

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






						def 			_A      (       self ,				_A ,				_A="cpu" ,				_A=torch.floataa ,				_A=0						):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE										=   torch.Generator(device=lowerCAmelCase_						).manual_seed(lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   np.random.RandomState(lowerCAmelCase_						).standard_normal((1, 4, 64, 64)						)
													__SCREAMING_SNAKE_CASE										=   torch.from_numpy(lowerCAmelCase_						).to(device=lowerCAmelCase_ ,				dtype=lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   {
													    "prompt": "a photograph of an astronaut riding a horse",
													    "latents": latents,
													    "generator": generator,
													    "num_inference_steps": 3,
													    "guidance_scale": 7.5,
													    "output_type": "numpy",
													}
													return inputs






						def 			_A      (       self						):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE										=   DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base'						)
													pipe.to(lowerCAmelCase_						)
													pipe.set_progress_bar_config(disable=lowerCAmelCase_						)

													__SCREAMING_SNAKE_CASE										=   self.get_inputs(lowerCAmelCase_						)
													__SCREAMING_SNAKE_CASE										=   pipe(**lowerCAmelCase_						).images
													__SCREAMING_SNAKE_CASE										=   image[0, -3:, -3:, -1].flatten()

													assert image.shape == (1, 512, 512, 3)
													__SCREAMING_SNAKE_CASE										=   np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6]						)
													assert np.abs(image_slice - expected_slice						).max() < 7e-3














"""simple docstring"""
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, prepare_image_inputs


if is_torch_available():
			import torch

if is_vision_available():
			from PIL import Image

			from transformers import ViTImageProcessor







class      UpperCamelCase_			(unittest.TestCase	):





	def __init__( self   :					Optional[int]      ,      lowerCAmelCase_   :					Tuple      ,      lowerCAmelCase_   :					List[str]=13      ,      lowerCAmelCase_   :					Union[str, Any]=3      ,      lowerCAmelCase_   :					Union[str, Any]=224      ,      lowerCAmelCase_   :					List[Any]=30      ,      lowerCAmelCase_   :					Any=400      ,      lowerCAmelCase_   :					Any=True      ,      lowerCAmelCase_   :					Dict=None      ,      lowerCAmelCase_   :					int=True      ,      lowerCAmelCase_   :					Any=[0.5, 0.5, 0.5]      ,      lowerCAmelCase_   :					str=[0.5, 0.5, 0.5]      ,      )		->     Dict:
				UpperCAmelCase_	:					int     	=   size if size is not None else {"height": 18, "width": 18}
				UpperCAmelCase_	:					List[Any]     	=   parent
				UpperCAmelCase_	:					int     	=   batch_size
				UpperCAmelCase_	:					Optional[int]     	=   num_channels
				UpperCAmelCase_	:					Dict     	=   image_size
				UpperCAmelCase_	:					Union[str, Any]     	=   min_resolution
				UpperCAmelCase_	:					List[str]     	=   max_resolution
				UpperCAmelCase_	:					Dict     	=   do_resize
				UpperCAmelCase_	:					Optional[int]     	=   size
				UpperCAmelCase_	:					List[str]     	=   do_normalize
				UpperCAmelCase_	:					List[Any]     	=   image_mean
				UpperCAmelCase_	:					Dict     	=   image_std





	def 	_SCREAMING_SNAKE_CASE ( self   :					int		)		->     Union[str, Any]:
				return {
				    "image_mean": self.image_mean,
				    "image_std": self.image_std,
				    "do_normalize": self.do_normalize,
				    "do_resize": self.do_resize,
				    "size": self.size,
				}







@require_torch
@require_vision
class      UpperCamelCase_			(__A							,		unittest.TestCase	):
	__magic_name__       =							ViTImageProcessor if is_vision_available() else None





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]		)		->     Optional[Any]:
				UpperCAmelCase_	:					Optional[Any]     	=   EfficientFormerImageProcessorTester(self		)





	@property
	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     List[Any]:
				return self.image_proc_tester.prepare_image_processor_dict()





	def 	_SCREAMING_SNAKE_CASE ( self   :					Tuple		)		->     str:
				UpperCAmelCase_	:					Tuple     	=   self.image_processing_class(**self.image_processor_dict		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "image_mean"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "image_std"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "do_normalize"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "do_resize"		)		)
				self.assertTrue(hasattr(lowerCAmelCase_      ,      "size"		)		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]		)		->     List[str]:
				pass





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     int:
				# Initialize image_processor
				UpperCAmelCase_	:					str     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random PIL images
				UpperCAmelCase_	:					int     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      Image.Image		)

				# Test not batched input
				UpperCAmelCase_	:					Optional[Any]     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					str     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )





	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     List[Any]:
				# Initialize image_processor
				UpperCAmelCase_	:					List[str]     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random numpy tensors
				UpperCAmelCase_	:					List[str]     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_      ,      numpify=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      np.ndarray		)

				# Test not batched input
				UpperCAmelCase_	:					str     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					Dict     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     List[Any]:
				# Initialize image_processor
				UpperCAmelCase_	:					Optional[Any]     	=   self.image_processing_class(**self.image_processor_dict		)
				# create random PyTorch tensors
				UpperCAmelCase_	:					Dict     	=   prepare_image_inputs(self.image_proc_tester      ,      equal_resolution=lowerCAmelCase_      ,      torchify=lowerCAmelCase_		)
				for image in image_inputs:
							self.assertIsInstance(lowerCAmelCase_      ,      torch.Tensor		)

				# Test not batched input
				UpperCAmelCase_	:					Optional[int]     	=   image_processor(image_inputs[0]      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        1,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )

				# Test batched
				UpperCAmelCase_	:					Optional[int]     	=   image_processor(lowerCAmelCase_      ,      return_tensors="pt"		).pixel_values
				self.assertEqual(
				    encoded_images.shape      ,      (
				        self.image_proc_tester.batch_size,
				        self.image_proc_tester.num_channels,
				        self.image_proc_tester.size["height"],
				        self.image_proc_tester.size["width"],
				    )      ,      )



