



'''simple docstring'''

import gc
import unittest

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

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

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class 			__magic_name__		(					_UpperCAmelCase    ,		_UpperCAmelCase    ,		unittest.TestCase     ):
							lowerCAmelCase :					Optional[int]            =      StableDiffusionXLPipeline
							lowerCAmelCase :					int            =      TEXT_TO_IMAGE_PARAMS
							lowerCAmelCase :					int            =      TEXT_TO_IMAGE_BATCH_PARAMS
							lowerCAmelCase :					Any            =      TEXT_TO_IMAGE_IMAGE_PARAMS
							lowerCAmelCase :					int            =      TEXT_TO_IMAGE_IMAGE_PARAMS







							def 							__lowercase    (							self      : List[Any]	):
									torch.manual_seed(0	)
									_a  :   str				 =							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			,)
									_a  :   Optional[Any]				 =							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	)
									_a  :   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	)
									_a  :   Optional[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			,)
									_a  :   Union[str, Any]				 =							CLIPTextModel(_UpperCAmelCase	)
									_a  :   List[Any]				 =							CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'			,local_files_only=_UpperCAmelCase	)

									_a  :   int				 =							CLIPTextModelWithProjection(_UpperCAmelCase	)
									_a  :   Dict				 =							CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'			,local_files_only=_UpperCAmelCase	)

									_a  :   Union[str, 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 							__lowercase    (							self      : Dict			,_UpperCAmelCase      : Optional[int]			,_UpperCAmelCase      : Optional[int]=0	):






									if str(_UpperCAmelCase	).startswith('mps'	):
											_a  :   str				 =							torch.manual_seed(_UpperCAmelCase	)
									else:
											_a  :   Optional[int]				 =							torch.Generator(device=_UpperCAmelCase	).manual_seed(_UpperCAmelCase	)
									_a  :   Optional[int]				 =							{
									    'prompt': 'A painting of a squirrel eating a burger',
									    'generator': generator,
									    'num_inference_steps': 2,
									    'guidance_scale': 5.0,
									    'output_type': 'numpy',
									}
									return inputs







							def 							__lowercase    (							self      : Optional[int]	):
									_a  :   Optional[int]				 =							'cpu'  # ensure determinism for the device-dependent torch.Generator
									_a  :   int				 =							self.get_dummy_components()
									_a  :   Optional[int]				 =							StableDiffusionXLPipeline(**_UpperCAmelCase	)
									_a  :   Union[str, Any]				 =							sd_pipe.to(_UpperCAmelCase	)
									sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase	)

									_a  :   Dict				 =							self.get_dummy_inputs(_UpperCAmelCase	)
									_a  :   Dict				 =							sd_pipe(**_UpperCAmelCase	).images
									_a  :   Any				 =							image[0, -3:, -3:, -1]

									assert image.shape == (1, 64, 64, 3)
									_a  :   List[str]				 =							np.array([0.58_73, 0.61_28, 0.47_97, 0.51_22, 0.56_74, 0.46_39, 0.52_27, 0.51_49, 0.47_47]	)

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







							def 							__lowercase    (							self      : Dict	):
									_a  :   Optional[int]				 =							self.get_dummy_components()
									_a  :   Dict				 =							StableDiffusionXLPipeline(**_UpperCAmelCase	)
									_a  :   str				 =							sd_pipe.to(_UpperCAmelCase	)
									_a  :   List[Any]				 =							sd_pipe.to(_UpperCAmelCase	)
									sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase	)

									# forward without prompt embeds
									_a  :   Dict				 =							self.get_dummy_inputs(_UpperCAmelCase	)
									_a  :   Tuple				 =							3 * ['this is a negative prompt']
									_a  :   str				 =							negative_prompt
									_a  :   str				 =							3 * [inputs['prompt']]

									_a  :   List[str]				 =							sd_pipe(**_UpperCAmelCase	)
									_a  :   str				 =							output.images[0, -3:, -3:, -1]

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

									(
									    (
									    _a       
									) ,      (
									    _a       
									) ,      (
									    _a       
									) ,      (
									    _a       
									) ,             
									)  :   Union[str, Any]				 =							sd_pipe.encode_prompt(_UpperCAmelCase			,negative_prompt=_UpperCAmelCase	)

									_a  :   Tuple				 =							sd_pipe(
									    **_UpperCAmelCase			,prompt_embeds=_UpperCAmelCase			,negative_prompt_embeds=_UpperCAmelCase			,pooled_prompt_embeds=_UpperCAmelCase			,negative_pooled_prompt_embeds=_UpperCAmelCase			,)
									_a  :   List[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







							def 							__lowercase    (							self      : Optional[Any]	):
									super().test_attention_slicing_forward_pass(expected_max_diff=3E-3	)







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

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







							def 							__lowercase    (							self      : Union[str, Any]	):
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()







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

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

									assert image.shape == (1, 512, 512, 3)
									_a  :   Dict				 =							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









'''simple docstring'''

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 (
    get_resize_output_image_size,
    normalize,
    pad,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging
from ...utils.import_utils import is_vision_available


__lowerCAmelCase		    =     logging.get_logger(__name__)


if is_vision_available():
							import PIL

class 			__magic_name__		(					_UpperCamelCase     ):
							lowerCAmelCase :					List[str]            =      ['pixel_values']







							def __init__(							self      : int			,_UpperCAmelCase      : bool = True			,_UpperCAmelCase      : Dict[str, int] = None			,_UpperCAmelCase      : PILImageResampling = PILImageResampling.BILINEAR			,_UpperCAmelCase      : bool = True			,_UpperCAmelCase      : bool = False			,_UpperCAmelCase      : bool = True			,_UpperCAmelCase      : bool = True			,_UpperCAmelCase      : Union[int, float] = 1 / 255			,_UpperCAmelCase      : bool = True			,_UpperCAmelCase      : Optional[Union[float, List[float]]] = None			,_UpperCAmelCase      : Optional[Union[float, List[float]]] = None			,**_UpperCAmelCase      : Optional[Any]			,):
									super().__init__(**_UpperCAmelCase	)

									_a  :   Union[str, Any]				 =							size if size is not None else {'height': 2560, 'width': 1920}
									if isinstance(_UpperCAmelCase			,(tuple, list)	):
											# The previous feature extractor size parameter was in (width, height) format
											_a  :   Union[str, Any]				 =							size[::-1]
									_a  :   Dict				 =							get_size_dict(_UpperCAmelCase	)

									_a  :   int				 =							do_resize
									_a  :   Any				 =							size
									_a  :   Any				 =							resample
									_a  :   int				 =							do_thumbnail
									_a  :   Tuple				 =							do_align_long_axis
									_a  :   Optional[Any]				 =							do_pad
									_a  :   Any				 =							do_rescale
									_a  :   List[str]				 =							rescale_factor
									_a  :   Any				 =							do_normalize
									_a  :   Union[str, Any]				 =							image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
									_a  :   Any				 =							image_std if image_std is not None else IMAGENET_STANDARD_STD







							def 							__lowercase    (							self      : Optional[Any]			,_UpperCAmelCase      : np.ndarray			,_UpperCAmelCase      : Dict[str, int]			,_UpperCAmelCase      : Optional[Union[str, ChannelDimension]] = None	):
									_a ,      _a  :   List[Any]				 =							get_image_size(_UpperCAmelCase	)
									_a ,      _a  :   List[str]				 =							size['height'], size['width']

									if (output_width < output_height and input_width > input_height) or (
									    output_width > output_height and input_width < input_height
									):
											_a  :   Optional[int]				 =							np.rotaa(_UpperCAmelCase			,3	)

									if data_format is not None:
											_a  :   Any				 =							to_channel_dimension_format(_UpperCAmelCase			,_UpperCAmelCase	)

									return image







							def 							__lowercase    (							self      : Any			,_UpperCAmelCase      : np.ndarray			,_UpperCAmelCase      : Dict[str, int]			,_UpperCAmelCase      : bool = False			,_UpperCAmelCase      : Optional[Union[str, ChannelDimension]] = None			,):
									_a ,      _a  :   List[Any]				 =							size['height'], size['width']
									_a ,      _a  :   str				 =							get_image_size(_UpperCAmelCase	)

									_a  :   List[str]				 =							output_width - input_width
									_a  :   Union[str, Any]				 =							output_height - input_height

									if random_padding:
											_a  :   Union[str, Any]				 =							np.random.randint(low=0			,high=delta_height + 1	)
											_a  :   Any				 =							np.random.randint(low=0			,high=delta_width + 1	)
									else:
											_a  :   Tuple				 =							delta_height // 2
											_a  :   List[Any]				 =							delta_width // 2

									_a  :   Dict				 =							delta_height - pad_top
									_a  :   Optional[int]				 =							delta_width - pad_left

									_a  :   int				 =							((pad_top, pad_bottom), (pad_left, pad_right))
									return pad(_UpperCAmelCase			,_UpperCAmelCase			,data_format=_UpperCAmelCase	)







							def 							__lowercase    (							self      : List[Any]			,*_UpperCAmelCase      : int			,**_UpperCAmelCase      : List[str]	):
									logger.info('pad is deprecated and will be removed in version 4.27. Please use pad_image instead.'	)
									return self.pad_image(*_UpperCAmelCase			,**_UpperCAmelCase	)







							def 							__lowercase    (							self      : Dict			,_UpperCAmelCase      : np.ndarray			,_UpperCAmelCase      : Dict[str, int]			,_UpperCAmelCase      : PILImageResampling = PILImageResampling.BICUBIC			,_UpperCAmelCase      : Optional[Union[str, ChannelDimension]] = None			,**_UpperCAmelCase      : Union[str, Any]			,):
									_a ,      _a  :   Any				 =							get_image_size(_UpperCAmelCase	)
									_a ,      _a  :   Union[str, Any]				 =							size['height'], size['width']

									# We always resize to the smallest of either the input or output size.
									_a  :   Dict				 =							min(_UpperCAmelCase			,_UpperCAmelCase	)
									_a  :   List[Any]				 =							min(_UpperCAmelCase			,_UpperCAmelCase	)

									if height == input_height and width == input_width:
											return image

									if input_height > input_width:
											_a  :   Any				 =							int(input_width * height / input_height	)
									elif input_width > input_height:
											_a  :   int				 =							int(input_height * width / input_width	)

									return resize(
									    _UpperCAmelCase			,size=(height, width)			,resample=_UpperCAmelCase			,reducing_gap=2.0			,data_format=_UpperCAmelCase			,**_UpperCAmelCase	)







							def 							__lowercase    (							self      : List[str]			,_UpperCAmelCase      : np.ndarray			,_UpperCAmelCase      : Dict[str, int]			,_UpperCAmelCase      : PILImageResampling = PILImageResampling.BICUBIC			,_UpperCAmelCase      : Optional[Union[str, ChannelDimension]] = None			,**_UpperCAmelCase      : List[Any]			,):
									_a  :   List[Any]				 =							get_size_dict(_UpperCAmelCase	)
									_a  :   int				 =							min(size['height']			,size['width']	)
									_a  :   Dict				 =							get_resize_output_image_size(_UpperCAmelCase			,size=_UpperCAmelCase			,default_to_square=_UpperCAmelCase	)
									_a  :   int				 =							resize(_UpperCAmelCase			,size=_UpperCAmelCase			,resample=_UpperCAmelCase			,data_format=_UpperCAmelCase			,**_UpperCAmelCase	)
									return resized_image







							def 							__lowercase    (							self      : int			,_UpperCAmelCase      : np.ndarray			,_UpperCAmelCase      : Union[int, float]			,_UpperCAmelCase      : Optional[Union[str, ChannelDimension]] = None			,**_UpperCAmelCase      : Optional[Any]			,):
									return rescale(_UpperCAmelCase			,scale=_UpperCAmelCase			,data_format=_UpperCAmelCase			,**_UpperCAmelCase	)







							def 							__lowercase    (							self      : List[str]			,_UpperCAmelCase      : np.ndarray			,_UpperCAmelCase      : Union[float, List[float]]			,_UpperCAmelCase      : Union[float, List[float]]			,_UpperCAmelCase      : Optional[Union[str, ChannelDimension]] = None			,**_UpperCAmelCase      : Dict			,):
									return normalize(_UpperCAmelCase			,mean=_UpperCAmelCase			,std=_UpperCAmelCase			,data_format=_UpperCAmelCase			,**_UpperCAmelCase	)







							def 							__lowercase    (							self      : Optional[int]			,_UpperCAmelCase      : ImageInput			,_UpperCAmelCase      : bool = None			,_UpperCAmelCase      : Dict[str, int] = None			,_UpperCAmelCase      : PILImageResampling = None			,_UpperCAmelCase      : bool = None			,_UpperCAmelCase      : bool = None			,_UpperCAmelCase      : bool = None			,_UpperCAmelCase      : bool = False			,_UpperCAmelCase      : bool = None			,_UpperCAmelCase      : float = None			,_UpperCAmelCase      : bool = None			,_UpperCAmelCase      : Optional[Union[float, List[float]]] = None			,_UpperCAmelCase      : Optional[Union[float, List[float]]] = None			,_UpperCAmelCase      : Optional[Union[str, TensorType]] = None			,_UpperCAmelCase      : Optional[ChannelDimension] = ChannelDimension.FIRST			,**_UpperCAmelCase      : int			,):
									_a  :   List[str]				 =							do_resize if do_resize is not None else self.do_resize
									_a  :   Optional[Any]				 =							size if size is not None else self.size
									if isinstance(_UpperCAmelCase			,(tuple, list)	):
											# Previous feature extractor had size in (width, height) format
											_a  :   Optional[int]				 =							size[::-1]
									_a  :   Tuple				 =							get_size_dict(_UpperCAmelCase	)
									_a  :   Optional[int]				 =							resample if resample is not None else self.resample
									_a  :   Union[str, Any]				 =							do_thumbnail if do_thumbnail is not None else self.do_thumbnail
									_a  :   int				 =							do_align_long_axis if do_align_long_axis is not None else self.do_align_long_axis
									_a  :   Optional[Any]				 =							do_pad if do_pad is not None else self.do_pad
									_a  :   str				 =							do_rescale if do_rescale is not None else self.do_rescale
									_a  :   Dict				 =							rescale_factor if rescale_factor is not None else self.rescale_factor
									_a  :   Dict				 =							do_normalize if do_normalize is not None else self.do_normalize
									_a  :   Optional[int]				 =							image_mean if image_mean is not None else self.image_mean
									_a  :   Dict				 =							image_std if image_std is not None else self.image_std

									_a  :   Optional[Any]				 =							make_list_of_images(_UpperCAmelCase	)

									if not valid_images(_UpperCAmelCase	):
											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:
											raise ValueError('Size must be specified if do_resize is True.'	)

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

									if do_pad and size is None:
											raise ValueError('Size must be specified if do_pad 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.
									_a  :   Dict				 =							[to_numpy_array(_UpperCAmelCase	) for image in images]

									if do_align_long_axis:
											_a  :   Optional[Any]				 =							[self.align_long_axis(_UpperCAmelCase			,size=_UpperCAmelCase	) for image in images]

									if do_resize:
											_a  :   List[Any]				 =							[self.resize(image=_UpperCAmelCase			,size=_UpperCAmelCase			,resample=_UpperCAmelCase	) for image in images]

									if do_thumbnail:
											_a  :   Dict				 =							[self.thumbnail(image=_UpperCAmelCase			,size=_UpperCAmelCase	) for image in images]

									if do_pad:
											_a  :   List[str]				 =							[self.pad_image(image=_UpperCAmelCase			,size=_UpperCAmelCase			,random_padding=_UpperCAmelCase	) for image in images]

									if do_rescale:
											_a  :   List[str]				 =							[self.rescale(image=_UpperCAmelCase			,scale=_UpperCAmelCase	) for image in images]

									if do_normalize:
											_a  :   List[str]				 =							[self.normalize(image=_UpperCAmelCase			,mean=_UpperCAmelCase			,std=_UpperCAmelCase	) for image in images]

									_a  :   Optional[Any]				 =							[to_channel_dimension_format(_UpperCAmelCase			,_UpperCAmelCase	) for image in images]

									_a  :   List[Any]				 =							{'pixel_values': images}
									return BatchFeature(data=_UpperCAmelCase			,tensor_type=_UpperCAmelCase	)




