





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    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							unittest.TestCase    ):







 '''simple docstring'''
 lowercase_		=			StableDiffusionXLImgaImgPipeline
 lowercase_		=			TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
 lowercase_		=			PipelineTesterMixin.required_optional_params - {"latents"}
 lowercase_		=			TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
 lowercase_		=			IMAGE_TO_IMAGE_IMAGE_PARAMS
 lowercase_		=			IMAGE_TO_IMAGE_IMAGE_PARAMS

 def 							SCREAMING_SNAKE_CASE_					(self				:   Union[str, Any])       ->Tuple:



   '''simple docstring'''



   torch.manual_seed(0)
   lowerCamelCase__:      Tuple			  =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=UpperCAmelCase_       , 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       , )
   lowerCamelCase__:      Tuple			  =EulerDiscreteScheduler(
       beta_start=0.0_0085       , beta_end=0.012       , steps_offset=1       , beta_schedule="scaled_linear"       , timestep_spacing="leading"       , )
   torch.manual_seed(0)
   lowerCamelCase__:      Tuple			  =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)
   lowerCamelCase__:      Union[str, Any]			  =CLIPTextConfig(
       bos_token_id=0       , eos_token_id=2       , hidden_size=32       , intermediate_size=37       , layer_norm_eps=1E-0_5       , num_attention_heads=4       , num_hidden_layers=5       , pad_token_id=1       , vocab_size=1_000       , hidden_act="gelu"       , projection_dim=32       , )
   lowerCamelCase__:      Optional[Any]			  =CLIPTextModel(UpperCAmelCase_)
   lowerCamelCase__:      List[str]			  =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       , local_files_only=UpperCAmelCase_)

   lowerCamelCase__:      Union[str, Any]			  =CLIPTextModelWithProjection(UpperCAmelCase_)
   lowerCamelCase__:      Optional[int]			  =CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       , local_files_only=UpperCAmelCase_)

   lowerCamelCase__:      int			  ={
       "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 							SCREAMING_SNAKE_CASE_					(self				:   Tuple       , UpperCAmelCase_				:   Union[str, Any]       , UpperCAmelCase_				:   Optional[int]=0)       ->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:      Optional[Any]			  =floats_tensor((1, 3, 32, 32)       , rng=random.Random(UpperCAmelCase_)).to(UpperCAmelCase_)
   lowerCamelCase__:      Any			  =image / 2 + 0.5
   if str(UpperCAmelCase_).startswith("mps"):
     lowerCamelCase__:      str			  =torch.manual_seed(UpperCAmelCase_)
   else:
     lowerCamelCase__:      List[str]			  =torch.Generator(device=UpperCAmelCase_).manual_seed(UpperCAmelCase_)
   lowerCamelCase__:      Any			  ={
       "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.75,
   }
   return inputs

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str])       ->Dict:



   '''simple docstring'''



   lowerCamelCase__:      str			  ="cpu"  # ensure determinism for the device-dependent torch.Generator
   lowerCamelCase__:      List[str]			  =self.get_dummy_components()
   lowerCamelCase__:      Union[str, Any]			  =StableDiffusionXLImgaImgPipeline(**UpperCAmelCase_)
   lowerCamelCase__:      Dict			  =sd_pipe.to(UpperCAmelCase_)
   sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_)

   lowerCamelCase__:      Dict			  =self.get_dummy_inputs(UpperCAmelCase_)
   lowerCamelCase__:      Union[str, Any]			  =sd_pipe(**UpperCAmelCase_).images
   lowerCamelCase__:      int			  =image[0, -3:, -3:, -1]

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

   lowerCamelCase__:      List[Any]			  =np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165])

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

 def 							SCREAMING_SNAKE_CASE_					(self				:   Tuple)       ->List[str]:



   '''simple docstring'''



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

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



   '''simple docstring'''



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

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str])       ->List[Any]:



   '''simple docstring'''



   pass







 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any])       ->Dict:



   '''simple docstring'''



   lowerCamelCase__:      Optional[int]			  =self.get_dummy_components()
   lowerCamelCase__:      Dict			  =StableDiffusionXLImgaImgPipeline(**UpperCAmelCase_)
   lowerCamelCase__:      str			  =sd_pipe.to(UpperCAmelCase_)
   lowerCamelCase__:      List[Any]			  =sd_pipe.to(UpperCAmelCase_)
   sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_)

   # forward without prompt embeds
   lowerCamelCase__:      int			  =self.get_dummy_inputs(UpperCAmelCase_)
   lowerCamelCase__:      List[Any]			  =3 * ["this is a negative prompt"]
   lowerCamelCase__:      Tuple			  =negative_prompt
   lowerCamelCase__:      int			  =3 * [inputs["prompt"]]

   lowerCamelCase__:      Tuple			  =sd_pipe(**UpperCAmelCase_)
   lowerCamelCase__:      Tuple			  =output.images[0, -3:, -3:, -1]

   # forward with prompt embeds
   lowerCamelCase__:      Union[str, Any]			  =self.get_dummy_inputs(UpperCAmelCase_)
   lowerCamelCase__:      Dict			  =3 * ["this is a negative prompt"]
   lowerCamelCase__:      Any			  =3 * [inputs.pop("prompt")]

   (
       (
       lowerCamelCase__
   )  ,					(
       lowerCamelCase__
   )  ,					(
       lowerCamelCase__
   )  ,					(
       lowerCamelCase__
   )  ,					
   ):      Tuple			  =sd_pipe.encode_prompt(UpperCAmelCase_       , negative_prompt=UpperCAmelCase_)

   lowerCamelCase__:      int			  =sd_pipe(
       **UpperCAmelCase_       , prompt_embeds=UpperCAmelCase_       , negative_prompt_embeds=UpperCAmelCase_       , pooled_prompt_embeds=UpperCAmelCase_       , negative_pooled_prompt_embeds=UpperCAmelCase_       , )
   lowerCamelCase__:      Optional[int]			  =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    _SCREAMING_SNAKE_CASE						(	unittest.TestCase    ):







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[str])       ->Optional[Any]:



   '''simple docstring'''



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

 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[int]       , UpperCAmelCase_				:   List[Any]       , UpperCAmelCase_				:   Optional[Any]="cpu"       , UpperCAmelCase_				:   Optional[int]=torch.floataa       , UpperCAmelCase_				:   Any=0)       ->Tuple:



   '''simple docstring'''



   lowerCamelCase__:      Optional[int]			  =torch.Generator(device=UpperCAmelCase_).manual_seed(UpperCAmelCase_)
   lowerCamelCase__:      Union[str, Any]			  =np.random.RandomState(UpperCAmelCase_).standard_normal((1, 4, 64, 64))
   lowerCamelCase__:      Union[str, Any]			  =torch.from_numpy(UpperCAmelCase_).to(device=UpperCAmelCase_       , dtype=UpperCAmelCase_)
   lowerCamelCase__:      Any			  ={
       "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 							SCREAMING_SNAKE_CASE_					(self				:   int)       ->List[str]:



   '''simple docstring'''



   lowerCamelCase__:      List[str]			  =DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base")
   pipe.to(UpperCAmelCase_)
   pipe.set_progress_bar_config(disable=UpperCAmelCase_)

   lowerCamelCase__:      int			  =self.get_inputs(UpperCAmelCase_)
   lowerCamelCase__:      str			  =pipe(**UpperCAmelCase_).images
   lowerCamelCase__:      Tuple			  =image[0, -3:, -3:, -1].flatten()

   assert image.shape == (1, 512, 512, 3)
   lowerCamelCase__:      int			  =np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506])
   assert np.abs(image_slice - expected_slice).max() < 7E-3








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 PoolFormerImageProcessor



class    _SCREAMING_SNAKE_CASE						(	unittest.TestCase    ):







 '''simple docstring'''

 def __init__(self				:   List[Any]       , UpperCAmelCase_				:   Any       , UpperCAmelCase_				:   Dict=7       , UpperCAmelCase_				:   List[str]=3       , UpperCAmelCase_				:   str=30       , UpperCAmelCase_				:   List[str]=400       , UpperCAmelCase_				:   Optional[int]=True       , UpperCAmelCase_				:   Optional[int]=None       , UpperCAmelCase_				:   Tuple=0.9       , UpperCAmelCase_				:   str=None       , UpperCAmelCase_				:   int=True       , UpperCAmelCase_				:   Union[str, Any]=[0.5, 0.5, 0.5]       , UpperCAmelCase_				:   Optional[Any]=[0.5, 0.5, 0.5]       , )       ->str:



   '''simple docstring'''



   lowerCamelCase__:      List[Any]			  =size if size is not None else {"shortest_edge": 30}
   lowerCamelCase__:      Dict			  =crop_size if crop_size is not None else {"height": 30, "width": 30}
   lowerCamelCase__:      Any			  =parent
   lowerCamelCase__:      Any			  =batch_size
   lowerCamelCase__:      Optional[Any]			  =num_channels
   lowerCamelCase__:      Tuple			  =min_resolution
   lowerCamelCase__:      Union[str, Any]			  =max_resolution
   lowerCamelCase__:      Union[str, Any]			  =do_resize_and_center_crop
   lowerCamelCase__:      Optional[int]			  =size
   lowerCamelCase__:      str			  =crop_pct
   lowerCamelCase__:      Any			  =crop_size
   lowerCamelCase__:      List[str]			  =do_normalize
   lowerCamelCase__:      List[str]			  =image_mean
   lowerCamelCase__:      Tuple			  =image_std







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



   '''simple docstring'''



   return {
       "size": self.size,
       "do_resize_and_center_crop": self.do_resize_and_center_crop,
       "crop_pct": self.crop_pct,
       "crop_size": self.crop_size,
       "do_normalize": self.do_normalize,
       "image_mean": self.image_mean,
       "image_std": self.image_std,
   }



@require_torch
@require_vision
class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ,							unittest.TestCase    ):







 '''simple docstring'''
 lowercase_		=			PoolFormerImageProcessor if is_vision_available() else None

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



   '''simple docstring'''



   lowerCamelCase__:      Optional[int]			  =PoolFormerImageProcessingTester(self)

 @property
 def 							SCREAMING_SNAKE_CASE_					(self				:   str)       ->int:



   '''simple docstring'''



   return self.image_processor_tester.prepare_image_processor_dict()

 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any])       ->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__:      Any			  =self.image_processing_class(**self.image_processor_dict)
   self.assertTrue(hasattr(UpperCAmelCase_       , "do_resize_and_center_crop"))
   self.assertTrue(hasattr(UpperCAmelCase_       , "size"))
   self.assertTrue(hasattr(UpperCAmelCase_       , "crop_pct"))
   self.assertTrue(hasattr(UpperCAmelCase_       , "do_normalize"))
   self.assertTrue(hasattr(UpperCAmelCase_       , "image_mean"))
   self.assertTrue(hasattr(UpperCAmelCase_       , "image_std"))

 def 							SCREAMING_SNAKE_CASE_					(self				:   Any)       ->List[str]:



   '''simple docstring'''



   lowerCamelCase__:      List[str]			  =self.image_processing_class.from_dict(self.image_processor_dict)
   self.assertEqual(image_processor.size       , {"shortest_edge": 30})
   self.assertEqual(image_processor.crop_size       , {"height": 30, "width": 30})

   lowerCamelCase__:      Union[str, Any]			  =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 							SCREAMING_SNAKE_CASE_					(self				:   int)       ->Optional[Any]:



   '''simple docstring'''



   pass

 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any])       ->Any:



   '''simple docstring'''



   lowerCamelCase__:      Union[str, Any]			  =self.image_processing_class(**self.image_processor_dict)
   # create random PIL images
   lowerCamelCase__:      Union[str, Any]			  =prepare_image_inputs(self.image_processor_tester       , equal_resolution=UpperCAmelCase_)
   for image in image_inputs:
     self.assertIsInstance(UpperCAmelCase_       , Image.Image)

   # Test not batched input
   lowerCamelCase__:      Dict			  =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
   lowerCamelCase__:      int			  =image_processing(UpperCAmelCase_       , 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 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any])       ->Dict:



   '''simple docstring'''



   lowerCamelCase__:      Any			  =self.image_processing_class(**self.image_processor_dict)
   # create random numpy tensors
   lowerCamelCase__:      Tuple			  =prepare_image_inputs(self.image_processor_tester       , equal_resolution=UpperCAmelCase_       , numpify=UpperCAmelCase_)
   for image in image_inputs:
     self.assertIsInstance(UpperCAmelCase_       , np.ndarray)

   # Test not batched input
   lowerCamelCase__:      Union[str, Any]			  =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
   lowerCamelCase__:      List[str]			  =image_processing(UpperCAmelCase_       , 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 							SCREAMING_SNAKE_CASE_					(self				:   Union[str, Any])       ->Any:



   '''simple docstring'''



   lowerCamelCase__:      Optional[int]			  =self.image_processing_class(**self.image_processor_dict)
   # create random PyTorch tensors
   lowerCamelCase__:      Any			  =prepare_image_inputs(self.image_processor_tester       , equal_resolution=UpperCAmelCase_       , torchify=UpperCAmelCase_)
   for image in image_inputs:
     self.assertIsInstance(UpperCAmelCase_       , torch.Tensor)

   # Test not batched input
   lowerCamelCase__:      Any			  =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
   lowerCamelCase__:      str			  =image_processing(UpperCAmelCase_       , 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"],
       )       , )

