
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					( A_					, A_					, unittest.TestCase      ):
			UpperCamelCase					:List[Any]     =			StableDiffusionXLImgaImgPipeline
			UpperCamelCase					:Optional[Any]     =			TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
			UpperCamelCase					:List[str]     =			PipelineTesterMixin.required_optional_params - {'''latents'''}
			UpperCamelCase					:List[str]     =			TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
			UpperCamelCase					:List[str]     =			IMAGE_TO_IMAGE_IMAGE_PARAMS
			UpperCamelCase					:Union[str, Any]     =			IMAGE_TO_IMAGE_IMAGE_PARAMS





			def        _snake_case    (self				):
						torch.manual_seed(0				)
						lowerCamelCase__ :      List[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=__magic_name__							,    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__ :      Optional[int]								=		EulerDiscreteScheduler(
						    beta_start=0.0_00_85							,    beta_end=0.0_12							,    steps_offset=1							,    beta_schedule="""scaled_linear"""							,    timestep_spacing="""leading"""							,    )
						torch.manual_seed(0				)
						lowerCamelCase__ :      Union[str, Any]								=		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__ :      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							,    hidden_act="""gelu"""							,    projection_dim=32							,    )
						lowerCamelCase__ :      Dict								=		CLIPTextModel(__magic_name__				)
						lowerCamelCase__ :      Dict								=		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""							,    local_files_only=__magic_name__				)

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

						lowerCamelCase__ :      Optional[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							,    __magic_name__							,    __magic_name__=0				):
						lowerCamelCase__ :      Any								=		floats_tensor((1, 3, 32, 32)							,    rng=random.Random(__magic_name__				)				).to(__magic_name__				)
						lowerCamelCase__ :      List[Any]								=		image / 2 + 0.5
						if str(__magic_name__				).startswith("""mps"""				):
									lowerCamelCase__ :      int								=		torch.manual_seed(__magic_name__				)
						else:
									lowerCamelCase__ :      List[str]								=		torch.Generator(device=__magic_name__				).manual_seed(__magic_name__				)
						lowerCamelCase__ :      Optional[int]								=		{
						    """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				):
						lowerCamelCase__ :      Tuple								=		"""cpu"""  # ensure determinism for the device-dependent torch.Generator
						lowerCamelCase__ :      List[Any]								=		self.get_dummy_components()
						lowerCamelCase__ :      str								=		StableDiffusionXLImgaImgPipeline(**__magic_name__				)
						lowerCamelCase__ :      Optional[int]								=		sd_pipe.to(__magic_name__				)
						sd_pipe.set_progress_bar_config(disable=__magic_name__				)

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

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

						lowerCamelCase__ :      Tuple								=		np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65]				)

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





			def        _snake_case    (self				):
						super().test_attention_slicing_forward_pass(expected_max_diff=3E-3				)





			def        _snake_case    (self				):
						super().test_inference_batch_single_identical(expected_max_diff=3E-3				)





			def        _snake_case    (self				):
						pass





			def        _snake_case    (self				):
						lowerCamelCase__ :      Union[str, Any]								=		self.get_dummy_components()
						lowerCamelCase__ :      str								=		StableDiffusionXLImgaImgPipeline(**__magic_name__				)
						lowerCamelCase__ :      List[Any]								=		sd_pipe.to(__magic_name__				)
						lowerCamelCase__ :      Union[str, Any]								=		sd_pipe.to(__magic_name__				)
						sd_pipe.set_progress_bar_config(disable=__magic_name__				)

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

						lowerCamelCase__ :      str								=		sd_pipe(**__magic_name__				)
						lowerCamelCase__ :      Union[str, Any]								=		output.images[0, -3:, -3:, -1]

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

						(
						    lowerCamelCase__
						) :      Any								=		sd_pipe.encode_prompt(__magic_name__							,    negative_prompt=__magic_name__				)

						lowerCamelCase__ :      Union[str, Any]								=		sd_pipe(
						    **__magic_name__							,    prompt_embeds=__magic_name__							,    negative_prompt_embeds=__magic_name__							,    pooled_prompt_embeds=__magic_name__							,    negative_pooled_prompt_embeds=__magic_name__							,    )
						lowerCamelCase__ :      List[str]								=		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      ):





			def        _snake_case    (self				):
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__="cpu"							,    __magic_name__=torch.floataa							,    __magic_name__=0				):
						lowerCamelCase__ :      Any								=		torch.Generator(device=__magic_name__				).manual_seed(__magic_name__				)
						lowerCamelCase__ :      Dict								=		np.random.RandomState(__magic_name__				).standard_normal((1, 4, 64, 64)				)
						lowerCamelCase__ :      Tuple								=		torch.from_numpy(__magic_name__				).to(device=__magic_name__							,    dtype=__magic_name__				)
						lowerCamelCase__ :      List[str]								=		{
						    """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				):
						lowerCamelCase__ :      str								=		DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base"""				)
						pipe.to(__magic_name__				)
						pipe.set_progress_bar_config(disable=__magic_name__				)

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

						assert image.shape == (1, 512, 512, 3)
						lowerCamelCase__ :      List[str]								=		np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]				)
						assert np.abs(image_slice - expected_slice				).max() < 7E-3








from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
				import PIL


_lowercase     							=						logging.get_logger(__name__)
class 				__A					( A_      ):
			UpperCamelCase					:Union[str, Any]     =			['''pixel_values''']





			def __init__(self							,    __magic_name__ = True							,    __magic_name__ = None							,    __magic_name__ = PIL.Image.BICUBIC							,    __magic_name__ = True							,    __magic_name__ = None							,    __magic_name__ = 1 / 255							,    __magic_name__ = True							,    __magic_name__ = True							,    __magic_name__ = None							,    __magic_name__ = None							,    **__magic_name__							,    ):
						super().__init__(**__magic_name__				)
						lowerCamelCase__ :      str								=		size if size is not None else {"""height""": 256, """width""": 256}
						lowerCamelCase__ :      Optional[int]								=		get_size_dict(__magic_name__				)
						lowerCamelCase__ :      Any								=		crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
						lowerCamelCase__ :      Optional[int]								=		get_size_dict(__magic_name__							,    param_name="""crop_size"""				)

						lowerCamelCase__ :      str								=		do_resize
						lowerCamelCase__ :      Any								=		size
						lowerCamelCase__ :      Tuple								=		resample
						lowerCamelCase__ :      Union[str, Any]								=		do_center_crop
						lowerCamelCase__ :      List[str]								=		crop_size
						lowerCamelCase__ :      int								=		do_rescale
						lowerCamelCase__ :      Any								=		rescale_factor
						lowerCamelCase__ :      Dict								=		do_normalize
						lowerCamelCase__ :      Dict								=		image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
						lowerCamelCase__ :      int								=		image_std if image_std is not None else IMAGENET_STANDARD_STD





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__ = PIL.Image.BICUBIC							,    __magic_name__ = None							,    **__magic_name__							,    ):
						lowerCamelCase__ :      Optional[int]								=		get_size_dict(__magic_name__				)
						if "height" not in size or "width" not in size:
									raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"				)
						return resize(
						    __magic_name__							,    size=(size["""height"""], size["""width"""])							,    resample=__magic_name__							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__ = None							,    **__magic_name__							,    ):
						lowerCamelCase__ :      Tuple								=		get_size_dict(__magic_name__				)
						if "height" not in size or "width" not in size:
									raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"				)
						return center_crop(__magic_name__							,    size=(size["""height"""], size["""width"""])							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__ = None							,    **__magic_name__							,    ):
						return rescale(__magic_name__							,    scale=__magic_name__							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__ = None							,    **__magic_name__							,    ):
						return normalize(__magic_name__							,    mean=__magic_name__							,    std=__magic_name__							,    data_format=__magic_name__							,    **__magic_name__				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__=None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = None							,    __magic_name__ = ChannelDimension.FIRST							,    **__magic_name__							,    ):
						lowerCamelCase__ :      Tuple								=		do_resize if do_resize is not None else self.do_resize
						lowerCamelCase__ :      str								=		resample if resample is not None else self.resample
						lowerCamelCase__ :      str								=		do_center_crop if do_center_crop is not None else self.do_center_crop
						lowerCamelCase__ :      Optional[int]								=		do_rescale if do_rescale is not None else self.do_rescale
						lowerCamelCase__ :      str								=		rescale_factor if rescale_factor is not None else self.rescale_factor
						lowerCamelCase__ :      Union[str, Any]								=		do_normalize if do_normalize is not None else self.do_normalize
						lowerCamelCase__ :      Tuple								=		image_mean if image_mean is not None else self.image_mean
						lowerCamelCase__ :      List[Any]								=		image_std if image_std is not None else self.image_std

						lowerCamelCase__ :      str								=		size if size is not None else self.size
						lowerCamelCase__ :      List[str]								=		get_size_dict(__magic_name__				)
						lowerCamelCase__ :      Tuple								=		crop_size if crop_size is not None else self.crop_size
						lowerCamelCase__ :      Optional[Any]								=		get_size_dict(__magic_name__							,    param_name="""crop_size"""				)

						lowerCamelCase__ :      Optional[int]								=		make_list_of_images(__magic_name__				)

						if not valid_images(__magic_name__				):
									raise ValueError(
									    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
									    """torch.Tensor, tf.Tensor or jax.ndarray."""				)

						if do_resize and size is None or resample is None:
									raise ValueError("""Size and resample must be specified if do_resize is True."""				)

						if do_center_crop and crop_size is None:
									raise ValueError("""Crop size must be specified if do_center_crop is True."""				)

						if do_rescale and rescale_factor is None:
									raise ValueError("""Rescale factor must be specified if do_rescale is True."""				)

						if do_normalize and (image_mean is None or image_std is None):
									raise ValueError("""Image mean and std must be specified if do_normalize is True."""				)

						# All transformations expect numpy arrays.
						lowerCamelCase__ :      Optional[int]								=		[to_numpy_array(__magic_name__				) for image in images]

						if do_resize:
									lowerCamelCase__ :      int								=		[self.resize(image=__magic_name__							,    size=__magic_name__							,    resample=__magic_name__				) for image in images]

						if do_center_crop:
									lowerCamelCase__ :      List[Any]								=		[self.center_crop(image=__magic_name__							,    size=__magic_name__				) for image in images]

						if do_rescale:
									lowerCamelCase__ :      Dict								=		[self.rescale(image=__magic_name__							,    scale=__magic_name__				) for image in images]

						if do_normalize:
									lowerCamelCase__ :      Optional[Any]								=		[self.normalize(image=__magic_name__							,    mean=__magic_name__							,    std=__magic_name__				) for image in images]

						lowerCamelCase__ :      List[str]								=		[to_channel_dimension_format(__magic_name__							,    __magic_name__				) for image in images]

						lowerCamelCase__ :      Dict								=		{"""pixel_values""": images}
						return BatchFeature(data=__magic_name__							,    tensor_type=__magic_name__				)



