






"""simple docstring"""
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	):
	__magic_name__       =							StableDiffusionXLImgaImgPipeline
	__magic_name__       =							TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
	__magic_name__       =							PipelineTesterMixin.required_optional_params - {'''latents'''}
	__magic_name__       =							TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	__magic_name__       =							IMAGE_TO_IMAGE_IMAGE_PARAMS
	__magic_name__       =							IMAGE_TO_IMAGE_IMAGE_PARAMS





	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     Optional[int]:
				torch.manual_seed(0		)
				UpperCAmelCase_	:					int     	=   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      ,      )
				UpperCAmelCase_	:					int     	=   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		)
				UpperCAmelCase_	:					List[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		)
				UpperCAmelCase_	:					Tuple     	=   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      ,      )
				UpperCAmelCase_	:					Union[str, Any]     	=   CLIPTextModel(lowerCAmelCase_		)
				UpperCAmelCase_	:					Union[str, Any]     	=   CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"      ,      local_files_only=lowerCAmelCase_		)

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

				UpperCAmelCase_	:					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 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]      ,      lowerCAmelCase_   :					Dict      ,      lowerCAmelCase_   :					List[str]=0		)		->     int:
				UpperCAmelCase_	:					Tuple     	=   floats_tensor((1, 3, 32, 32)      ,      rng=random.Random(lowerCAmelCase_		)		).to(lowerCAmelCase_		)
				UpperCAmelCase_	:					Optional[int]     	=   image / 2 + 0.5
				if str(lowerCAmelCase_		).startswith("mps"		):
							UpperCAmelCase_	:					str     	=   torch.manual_seed(lowerCAmelCase_		)
				else:
							UpperCAmelCase_	:					Optional[Any]     	=   torch.Generator(device=lowerCAmelCase_		).manual_seed(lowerCAmelCase_		)
				UpperCAmelCase_	:					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.7_5,
				}
				return inputs





	def 	_SCREAMING_SNAKE_CASE ( self   :					Any		)		->     Optional[int]:
				UpperCAmelCase_	:					List[str]     	=   "cpu"  # ensure determinism for the device-dependent torch.Generator
				UpperCAmelCase_	:					Optional[int]     	=   self.get_dummy_components()
				UpperCAmelCase_	:					Optional[int]     	=   StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_		)
				UpperCAmelCase_	:					Optional[Any]     	=   sd_pipe.to(lowerCAmelCase_		)
				sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_		)

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

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

				UpperCAmelCase_	:					List[Any]     	=   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 	_SCREAMING_SNAKE_CASE ( self   :					Dict		)		->     int:
				super().test_attention_slicing_forward_pass(expected_max_diff=3e-3		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     Optional[int]:
				super().test_inference_batch_single_identical(expected_max_diff=3e-3		)





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





	def 	_SCREAMING_SNAKE_CASE ( self   :					Any		)		->     Any:
				UpperCAmelCase_	:					List[str]     	=   self.get_dummy_components()
				UpperCAmelCase_	:					Tuple     	=   StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_		)
				UpperCAmelCase_	:					Union[str, Any]     	=   sd_pipe.to(lowerCAmelCase_		)
				UpperCAmelCase_	:					int     	=   sd_pipe.to(lowerCAmelCase_		)
				sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_		)

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

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

				# forward with prompt embeds
				UpperCAmelCase_	:					Dict     	=   self.get_dummy_inputs(lowerCAmelCase_		)
				UpperCAmelCase_	:					List[Any]     	=   3 * ["this is a negative prompt"]
				UpperCAmelCase_	:					int     	=   3 * [inputs.pop("prompt"		)]

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

				UpperCAmelCase_	:					str     	=   sd_pipe(
				    **lowerCAmelCase_      ,      prompt_embeds=lowerCAmelCase_      ,      negative_prompt_embeds=lowerCAmelCase_      ,      pooled_prompt_embeds=lowerCAmelCase_      ,      negative_pooled_prompt_embeds=lowerCAmelCase_      ,      )
				UpperCAmelCase_	:					Tuple     	=   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	):





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]		)		->     Dict:
				super().tearDown()
				gc.collect()
				torch.cuda.empty_cache()





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

				UpperCAmelCase_	:					List[Any]     	=   self.get_inputs(lowerCAmelCase_		)
				UpperCAmelCase_	:					Dict     	=   pipe(**lowerCAmelCase_		).images
				UpperCAmelCase_	:					Optional[int]     	=   image[0, -3:, -3:, -1].flatten()

				assert image.shape == (1, 512, 512, 3)
				UpperCAmelCase_	:					Any     	=   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 importlib.metadata
import operator
import re
import sys
from typing import Optional

from packaging import version


lowerCamelCase_							      = {
    '''<''': operator.lt,
    '''<=''': operator.le,
    '''==''': operator.eq,
    '''!=''': operator.ne,
    '''>=''': operator.ge,
    '''>''': operator.gt,
}

def 							snake_case (  A__      ,A__      ,A__      ,A__      ,A__      ,A__		):
			if got_ver is None or want_ver is None:
						raise ValueError(
						    F"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider"""
						    F""" reinstalling {pkg}."""		)
			if not ops[op](version.parse(A__		)      ,version.parse(A__		)		):
						raise ImportError(
						    F"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}"""		)

def 							snake_case (  A__      ,A__ = None		):
			UpperCAmelCase_	:					int     	=   F"""\n{hint}""" if hint is not None else ""

			# non-versioned check
			if re.match(r"^[\w_\-\d]+$"      ,A__		):
						UpperCAmelCase_	,      UpperCAmelCase_	,      UpperCAmelCase_	:					Optional[Any]     	=   requirement, None, None
			else:
						UpperCAmelCase_	:					Optional[int]     	=   re.findall(r"^([^!=<>\s]+)([\s!=<>]{1,2}.+)"      ,A__		)
						if not match:
									raise ValueError(
									    "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but"
									    F""" got {requirement}"""		)
						UpperCAmelCase_	,      UpperCAmelCase_	:					List[str]     	=   match[0]
						UpperCAmelCase_	:					Optional[Any]     	=   want_full.split(","		)  # there could be multiple requirements
						UpperCAmelCase_	:					int     	=   {}
						for w in want_range:
									UpperCAmelCase_	:					str     	=   re.findall(r"^([\s!=<>]{1,2})(.+)"      ,A__		)
									if not match:
												raise ValueError(
												    "requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,"
												    F""" but got {requirement}"""		)
									UpperCAmelCase_	,      UpperCAmelCase_	:					Any     	=   match[0]
									UpperCAmelCase_	:					Union[str, Any]     	=   want_ver
									if op not in ops:
												raise ValueError(F"""{requirement}: need one of {list(ops.keys()		)}, but got {op}"""		)

    # special case
			if pkg == "python":
						UpperCAmelCase_	:					List[Any]     	=   ".".join([str(A__		) for x in sys.version_info[:3]]		)
						for op, want_ver in wanted.items():
									_compare_versions(A__      ,A__      ,A__      ,A__      ,A__      ,A__		)
						return

			# check if any version is installed
			try:
						UpperCAmelCase_	:					str     	=   importlib.metadata.version(A__		)
			except importlib.metadata.PackageNotFoundError:
						raise importlib.metadata.PackageNotFoundError(
						    F"""The '{requirement}' distribution was not found and is required by this application. {hint}"""		)

			# check that the right version is installed if version number or a range was provided
			if want_ver is not None:
						for op, want_ver in wanted.items():
									_compare_versions(A__      ,A__      ,A__      ,A__      ,A__      ,A__		)




def 							snake_case (  A__		):
			UpperCAmelCase_	:					Any     	=   "Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main"
			return require_version(A__      ,A__		)



