





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       __A							(   lowerCamelCase__			,lowerCamelCase__			,unittest.TestCase	):




      """simple docstring"""







      UpperCAmelCase__							=   StableDiffusionXLImgaImgPipeline
      UpperCAmelCase__							=   TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
      UpperCAmelCase__							=   PipelineTesterMixin.required_optional_params - {"""latents"""}
      UpperCAmelCase__							=   TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
      UpperCAmelCase__							=   IMAGE_TO_IMAGE_IMAGE_PARAMS
      UpperCAmelCase__							=   IMAGE_TO_IMAGE_IMAGE_PARAMS


      def 					__snake_case      (		self):



             """simple docstring"""





             torch.manual_seed(0)
             _lowerCamelCase				:  Optional[Any]						=		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=a__   ,				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				:  Dict						=		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				:  List[str]						=		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				:  int						=		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   ,				hidden_act='''gelu'''   ,				projection_dim=32   ,				)
             _lowerCamelCase				:  Optional[int]						=		CLIPTextModel(a__)
             _lowerCamelCase				:  int						=		CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   ,				local_files_only=a__)

             _lowerCamelCase				:  Tuple						=		CLIPTextModelWithProjection(a__)
             _lowerCamelCase				:  List[Any]						=		CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   ,				local_files_only=a__)

             _lowerCamelCase				:  List[Any]						=		{
                 '''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 					__snake_case      (		self   ,				a__   ,				a__=0):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		floats_tensor((1, 3, 32, 32)   ,				rng=random.Random(a__)).to(a__)
             _lowerCamelCase				:  Any						=		image / 2 + 0.5
             if str(a__).startswith('''mps'''):
                    _lowerCamelCase				:  Optional[Any]						=		torch.manual_seed(a__)
             else:
                    _lowerCamelCase				:  Dict						=		torch.Generator(device=a__).manual_seed(a__)
             _lowerCamelCase				:  Optional[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 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Any						=		'''cpu'''  # ensure determinism for the device-dependent torch.Generator
             _lowerCamelCase				:  Dict						=		self.get_dummy_components()
             _lowerCamelCase				:  int						=		StableDiffusionXLImgaImgPipeline(**a__)
             _lowerCamelCase				:  Tuple						=		sd_pipe.to(a__)
             sd_pipe.set_progress_bar_config(disable=a__)

             _lowerCamelCase				:  Dict						=		self.get_dummy_inputs(a__)
             _lowerCamelCase				:  str						=		sd_pipe(**a__).images
             _lowerCamelCase				:  List[str]						=		image[0, -3:, -3:, -1]

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

             _lowerCamelCase				:  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 					__snake_case      (		self):



             """simple docstring"""





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


      def 					__snake_case      (		self):



             """simple docstring"""





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


      def 					__snake_case      (		self):



             """simple docstring"""





             pass



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  int						=		self.get_dummy_components()
             _lowerCamelCase				:  Any						=		StableDiffusionXLImgaImgPipeline(**a__)
             _lowerCamelCase				:  Union[str, Any]						=		sd_pipe.to(a__)
             _lowerCamelCase				:  Optional[Any]						=		sd_pipe.to(a__)
             sd_pipe.set_progress_bar_config(disable=a__)

             # forward without prompt embeds
             _lowerCamelCase				:  int						=		self.get_dummy_inputs(a__)
             _lowerCamelCase				:  Tuple						=		3 * ['''this is a negative prompt''']
             _lowerCamelCase				:  List[str]						=		negative_prompt
             _lowerCamelCase				:  List[Any]						=		3 * [inputs['''prompt''']]

             _lowerCamelCase				:  Union[str, Any]						=		sd_pipe(**a__)
             _lowerCamelCase				:  Dict						=		output.images[0, -3:, -3:, -1]

             # forward with prompt embeds
             _lowerCamelCase				:  Tuple						=		self.get_dummy_inputs(a__)
             _lowerCamelCase				:  Any						=		3 * ['''this is a negative prompt''']
             _lowerCamelCase				:  int						=		3 * [inputs.pop('''prompt''')]

             (
                 (
                 _lowerCamelCase
             ),	(
                 _lowerCamelCase
             ),	(
                 _lowerCamelCase
             ),	(
                 _lowerCamelCase
             ),	
             )				:  Union[str, Any]						=		sd_pipe.encode_prompt(a__   ,				negative_prompt=a__)

             _lowerCamelCase				:  Any						=		sd_pipe(
                 **a__   ,				prompt_embeds=a__   ,				negative_prompt_embeds=a__   ,				pooled_prompt_embeds=a__   ,				negative_pooled_prompt_embeds=a__   ,				)
             _lowerCamelCase				:  Union[str, Any]						=		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       __A							(   unittest.TestCase	):




      """simple docstring"""







      def 					__snake_case      (		self):



             """simple docstring"""





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


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



             """simple docstring"""





             _lowerCamelCase				:  str						=		torch.Generator(device=a__).manual_seed(a__)
             _lowerCamelCase				:  Any						=		np.random.RandomState(a__).standard_normal((1, 4, 64, 64))
             _lowerCamelCase				:  Optional[Any]						=		torch.from_numpy(a__).to(device=a__   ,				dtype=a__)
             _lowerCamelCase				:  Optional[int]						=		{
                 '''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 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''')
             pipe.to(a__)
             pipe.set_progress_bar_config(disable=a__)

             _lowerCamelCase				:  Union[str, Any]						=		self.get_inputs(a__)
             _lowerCamelCase				:  List[Any]						=		pipe(**a__).images
             _lowerCamelCase				:  Dict						=		image[0, -3:, -3:, -1].flatten()

             assert image.shape == (1, 512, 512, 3)
             _lowerCamelCase				:  str						=		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
import requests

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

       from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
       _lowerCamelCase      							=   False

if is_vision_available():
       from PIL import Image

       from transformers import PixaStructImageProcessor







class       __A							(   unittest.TestCase	):




      """simple docstring"""







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



             """simple docstring"""





             _lowerCamelCase				:  str						=		size if size is not None else {'''height''': 20, '''width''': 20}
             _lowerCamelCase				:  int						=		parent
             _lowerCamelCase				:  Tuple						=		batch_size
             _lowerCamelCase				:  Union[str, Any]						=		num_channels
             _lowerCamelCase				:  Tuple						=		image_size
             _lowerCamelCase				:  Dict						=		min_resolution
             _lowerCamelCase				:  int						=		max_resolution
             _lowerCamelCase				:  Dict						=		size
             _lowerCamelCase				:  Dict						=		do_normalize
             _lowerCamelCase				:  List[Any]						=		do_convert_rgb
             _lowerCamelCase				:  Optional[int]						=		[512, 1024, 2048, 4096]
             _lowerCamelCase				:  Optional[int]						=		patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}


      def 					__snake_case      (		self):



             """simple docstring"""





             return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Dict						=		'''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
             _lowerCamelCase				:  Union[str, Any]						=		Image.open(requests.get(a__   ,				stream=a__).raw).convert('''RGB''')
             return raw_image







@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11			,reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""			,)
@require_torch
@require_vision
class       __A							(   lowerCamelCase__			,unittest.TestCase	):




      """simple docstring"""







      UpperCAmelCase__							=   PixaStructImageProcessor if is_vision_available() else None


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  int						=		PixaStructImageProcessingTester(self)


      @property
      def 					__snake_case      (		self):



             """simple docstring"""





             return self.image_processor_tester.prepare_image_processor_dict()


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  int						=		self.image_processing_class(**self.image_processor_dict)
             self.assertTrue(hasattr(a__   ,				'''do_normalize'''))
             self.assertTrue(hasattr(a__   ,				'''do_convert_rgb'''))


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Any						=		self.image_processor_tester.prepare_dummy_image()

             _lowerCamelCase				:  List[Any]						=		self.image_processing_class(**self.image_processor_dict)
             _lowerCamelCase				:  Optional[int]						=		2048

             _lowerCamelCase				:  Any						=		image_processor(a__   ,				return_tensors='''pt'''   ,				max_patches=a__)
             self.assertTrue(torch.allclose(inputs.flattened_patches.mean()   ,				torch.tensor(0.0606)   ,				atol=1e-3   ,				rtol=1e-3))


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Dict						=		self.image_processing_class(**self.image_processor_dict)
             # create random PIL images
             _lowerCamelCase				:  Any						=		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=a__)
             for image in image_inputs:
                    self.assertIsInstance(a__   ,				Image.Image)

             # Test not batched input
             _lowerCamelCase				:  Optional[Any]						=		(
                 (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
                 * self.image_processor_tester.num_channels
             ) + 2

             for max_patch in self.image_processor_tester.max_patches:
                    # Test not batched input
                    _lowerCamelCase				:  Optional[int]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Dict						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Dict						=		self.image_processing_class(**self.image_processor_dict)
             # create random PIL images
             _lowerCamelCase				:  Optional[int]						=		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=a__)
             for image in image_inputs:
                    self.assertIsInstance(a__   ,				Image.Image)

             # Test not batched input
             _lowerCamelCase				:  List[str]						=		(
                 (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
                 * self.image_processor_tester.num_channels
             ) + 2

             _lowerCamelCase				:  Dict						=		True

             for max_patch in self.image_processor_tester.max_patches:
                    # Test not batched input
                    with self.assertRaises(a__):
                           _lowerCamelCase				:  List[Any]						=		image_processor(
                               image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches

                    _lowerCamelCase				:  List[Any]						=		'''Hello'''

                    _lowerCamelCase				:  int						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__   ,				header_text=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Dict						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__   ,				header_text=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)


      def 					__snake_case      (		self):



             """simple docstring"""





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

             _lowerCamelCase				:  Any						=		(
                 (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
                 * self.image_processor_tester.num_channels
             ) + 2

             for max_patch in self.image_processor_tester.max_patches:
                    # Test not batched input
                    _lowerCamelCase				:  List[str]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Tuple						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)



      def 					__snake_case      (		self):



             """simple docstring"""





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

             # Test not batched input
             _lowerCamelCase				:  Tuple						=		(
                 (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
                 * self.image_processor_tester.num_channels
             ) + 2

             for max_patch in self.image_processor_tester.max_patches:
                    # Test not batched input
                    _lowerCamelCase				:  Optional[int]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  List[str]						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)







@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11			,reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""			,)
@require_torch
@require_vision
class       __A							(   lowerCamelCase__			,unittest.TestCase	):




      """simple docstring"""







      UpperCAmelCase__							=   PixaStructImageProcessor if is_vision_available() else None


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Optional[Any]						=		PixaStructImageProcessingTester(self   ,				num_channels=4)
             _lowerCamelCase				:  Union[str, Any]						=		3


      @property
      def 					__snake_case      (		self):



             """simple docstring"""





             return self.image_processor_tester.prepare_image_processor_dict()


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  str						=		self.image_processing_class(**self.image_processor_dict)
             self.assertTrue(hasattr(a__   ,				'''do_normalize'''))
             self.assertTrue(hasattr(a__   ,				'''do_convert_rgb'''))



      def 					__snake_case      (		self):



             """simple docstring"""





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

             # Test not batched input
             _lowerCamelCase				:  List[Any]						=		(
                 (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
                 * (self.image_processor_tester.num_channels - 1)
             ) + 2

             for max_patch in self.image_processor_tester.max_patches:
                    # Test not batched input
                    _lowerCamelCase				:  Union[str, Any]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Union[str, Any]						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)

