






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       (			_a		,   _a		,   unittest.TestCase      ):
	snake_case__							:     Any     	=  StableDiffusionXLImgaImgPipeline
	snake_case__							:     Tuple     	=  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
	snake_case__							:     Tuple     	=  PipelineTesterMixin.required_optional_params - {"""latents"""}
	snake_case__							:     Any     	=  TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	snake_case__							:     List[str]     	=  IMAGE_TO_IMAGE_IMAGE_PARAMS
	snake_case__							:     Tuple     	=  IMAGE_TO_IMAGE_IMAGE_PARAMS





	def 						_A (		self				:					int	):
		torch.manual_seed(0	)
		UpperCamelCase     :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=__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     :Tuple          =	EulerDiscreteScheduler(
		    beta_start=0.00085 ,  beta_end=0.012 ,  steps_offset=1 ,  beta_schedule="""scaled_linear""" ,  timestep_spacing="""leading""" ,  )
		torch.manual_seed(0	)
		UpperCamelCase     :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	)
		UpperCamelCase     :Optional[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=1_000 ,  hidden_act="""gelu""" ,  projection_dim=32 ,  )
		UpperCamelCase     :Any          =	CLIPTextModel(__lowerCamelCase	)
		UpperCamelCase     :List[Any]          =	CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ,  local_files_only=__lowerCamelCase	)

		UpperCamelCase     :List[Any]          =	CLIPTextModelWithProjection(__lowerCamelCase	)
		UpperCamelCase     :int          =	CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ,  local_files_only=__lowerCamelCase	)

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

		UpperCamelCase     :Optional[Any]          =	self.get_dummy_inputs(__lowerCamelCase	)
		UpperCamelCase     :Union[str, Any]          =	sd_pipe(**__lowerCamelCase	).images
		UpperCamelCase     :Union[str, Any]          =	image[0, -3:, -3:, -1]

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

		UpperCamelCase     :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 						_A (		self				:					Dict	):
		super().test_attention_slicing_forward_pass(expected_max_diff=3E-3	)





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





	def 						_A (		self				:					Union[str, Any]	):
		pass





	def 						_A (		self				:					Optional[int]	):
		UpperCamelCase     :Union[str, Any]          =	self.get_dummy_components()
		UpperCamelCase     :Dict          =	StableDiffusionXLImgaImgPipeline(**__lowerCamelCase	)
		UpperCamelCase     :List[Any]          =	sd_pipe.to(__lowerCamelCase	)
		UpperCamelCase     :List[str]          =	sd_pipe.to(__lowerCamelCase	)
		sd_pipe.set_progress_bar_config(disable=__lowerCamelCase	)

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

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

		# forward with prompt embeds
		UpperCamelCase     :Union[str, Any]          =	self.get_dummy_inputs(__lowerCamelCase	)
		UpperCamelCase     :Optional[int]          =	3 * ["""this is a negative prompt"""]
		UpperCamelCase     :Union[str, Any]          =	3 * [inputs.pop("""prompt"""	)]

		(
		    (
		    UpperCamelCase
		)     ,      (
		    UpperCamelCase
		)     ,      (
		    UpperCamelCase
		)     ,      (
		    UpperCamelCase
		)     ,      
		)     :Union[str, Any]          =	sd_pipe.encode_prompt(__lowerCamelCase ,  negative_prompt=__lowerCamelCase	)

		UpperCamelCase     :Dict          =	sd_pipe(
		    **__lowerCamelCase ,  prompt_embeds=__lowerCamelCase ,  negative_prompt_embeds=__lowerCamelCase ,  pooled_prompt_embeds=__lowerCamelCase ,  negative_pooled_prompt_embeds=__lowerCamelCase ,  )
		UpperCamelCase     :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     _SCREAMING_SNAKE_CASE       (			unittest.TestCase      ):





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





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

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

		assert image.shape == (1, 512, 512, 3)
		UpperCamelCase     :Union[str, Any]          =	np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506]	)
		assert np.abs(image_slice - expected_slice	).max() < 7E-3




"""simple docstring"""
import pytest

import datasets


# Import fixture modules as plugins
SCREAMING_SNAKE_CASE :    List[Any]									=				["""tests.fixtures.files""", """tests.fixtures.hub""", """tests.fixtures.fsspec"""]






def 		lowercase							(     _snake_case						:      Optional[int]     ,   _snake_case						:      Optional[int]     )     ->Tuple:
	"""simple docstring"""





	for item in items:
		if any(marker in item.keywords for marker in ['''integration''', '''unit''']     ):
			continue
		item.add_marker(pytest.mark.unit     )






def 		lowercase							(     _snake_case						:      List[str]     )     ->Optional[int]:
	"""simple docstring"""





	config.addinivalue_line('''markers'''     ,   '''torchaudio_latest: mark test to run with torchaudio>=0.12'''     )






@pytest.fixture(autouse=_snake_case     )
def 		lowercase							(     _snake_case						:      Optional[Any]     ,   _snake_case						:      Dict     )     ->Any:
	"""simple docstring"""





	__snake_case	:						List[Any]						=				tmp_path_factory.getbasetemp() / '''cache'''
	__snake_case	:						int						=				test_hf_cache_home / '''datasets'''
	__snake_case	:						Tuple						=				test_hf_cache_home / '''metrics'''
	__snake_case	:						List[str]						=				test_hf_cache_home / '''modules'''
	monkeypatch.setattr('''datasets.config.HF_DATASETS_CACHE'''     ,   str(_snake_case     )     )
	monkeypatch.setattr('''datasets.config.HF_METRICS_CACHE'''     ,   str(_snake_case     )     )
	monkeypatch.setattr('''datasets.config.HF_MODULES_CACHE'''     ,   str(_snake_case     )     )
	__snake_case	:						Optional[int]						=				test_hf_datasets_cache / '''downloads'''
	monkeypatch.setattr('''datasets.config.DOWNLOADED_DATASETS_PATH'''     ,   str(_snake_case     )     )
	__snake_case	:						Tuple						=				test_hf_datasets_cache / '''downloads''' / '''extracted'''
	monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH'''     ,   str(_snake_case     )     )






@pytest.fixture(autouse=_snake_case     ,   scope='''session'''     )
def 		lowercase							(     )     ->Any:
	"""simple docstring"""





	datasets.disable_progress_bar()






@pytest.fixture(autouse=_snake_case     )
def 		lowercase							(     _snake_case						:      Tuple     )     ->Union[str, Any]:
	"""simple docstring"""





	monkeypatch.setattr('''datasets.config.HF_UPDATE_DOWNLOAD_COUNTS'''     ,   _snake_case     )






@pytest.fixture
def 		lowercase							(     _snake_case						:      Any     )     ->Optional[Any]:
	"""simple docstring"""





	monkeypatch.setattr('''sqlalchemy.util.deprecations.SILENCE_UBER_WARNING'''     ,   _snake_case     )





