
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__    (							SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_   ,		unittest.TestCase    ):

							"""simple docstring"""






							_snake_case     		=  StableDiffusionXLImgaImgPipeline
							_snake_case     		=  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'}
							_snake_case     		=  PipelineTesterMixin.required_optional_params - {'latents'}
							_snake_case     		=  TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
							_snake_case     		=  IMAGE_TO_IMAGE_IMAGE_PARAMS
							_snake_case     		=  IMAGE_TO_IMAGE_IMAGE_PARAMS



							def     A__		(  self			)->   Union[str, Any]:





													'''simple docstring'''






													torch.manual_seed(0			)
													__UpperCamelCase       =			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=SCREAMING_SNAKE_CASE_     ,	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       =			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       =			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       =			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     ,	)
													__UpperCamelCase       =			CLIPTextModel(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''     ,	local_files_only=SCREAMING_SNAKE_CASE_			)

													__UpperCamelCase       =			CLIPTextModelWithProjection(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''     ,	local_files_only=SCREAMING_SNAKE_CASE_			)

													__UpperCamelCase       =			{
													    '''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     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=0			)->   Dict:





													'''simple docstring'''






													__UpperCamelCase       =			floats_tensor((1, 3, 32, 32)     ,	rng=random.Random(SCREAMING_SNAKE_CASE_			)			).to(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			image / 2 + 0.5
													if str(SCREAMING_SNAKE_CASE_			).startswith('''mps'''			):
																			__UpperCamelCase       =			torch.manual_seed(SCREAMING_SNAKE_CASE_			)
													else:
																			__UpperCamelCase       =			torch.Generator(device=SCREAMING_SNAKE_CASE_			).manual_seed(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			{
													    '''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     A__		(  self			)->   Union[str, Any]:





													'''simple docstring'''






													__UpperCamelCase       =			'''cpu'''  # ensure determinism for the device-dependent torch.Generator
													__UpperCamelCase       =			self.get_dummy_components()
													__UpperCamelCase       =			StableDiffusionXLImgaImgPipeline(**SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			sd_pipe.to(SCREAMING_SNAKE_CASE_			)
													sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_			)

													__UpperCamelCase       =			self.get_dummy_inputs(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			sd_pipe(**SCREAMING_SNAKE_CASE_			).images
													__UpperCamelCase       =			image[0, -3:, -3:, -1]

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

													__UpperCamelCase       =			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     A__		(  self			)->   Union[str, Any]:





													'''simple docstring'''






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



							def     A__		(  self			)->   str:





													'''simple docstring'''






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



							def     A__		(  self			)->   List[Any]:





													'''simple docstring'''






													pass



							def     A__		(  self			)->   Tuple:





													'''simple docstring'''






													__UpperCamelCase       =			self.get_dummy_components()
													__UpperCamelCase       =			StableDiffusionXLImgaImgPipeline(**SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			sd_pipe.to(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			sd_pipe.to(SCREAMING_SNAKE_CASE_			)
													sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_			)

													# forward without prompt embeds
													__UpperCamelCase       =			self.get_dummy_inputs(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			3 * ['''this is a negative prompt''']
													__UpperCamelCase       =			negative_prompt
													__UpperCamelCase       =			3 * [inputs['''prompt''']]

													__UpperCamelCase       =			sd_pipe(**SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			output.images[0, -3:, -3:, -1]

													# forward with prompt embeds
													__UpperCamelCase       =			self.get_dummy_inputs(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			3 * ['''this is a negative prompt''']
													__UpperCamelCase       =			3 * [inputs.pop('''prompt'''			)]

													(
													    (
													    __UpperCamelCase
													)  ,							(
													    __UpperCamelCase
													)  ,							(
													    __UpperCamelCase
													)  ,							(
													    __UpperCamelCase
													)  ,							
													)       =			sd_pipe.encode_prompt(SCREAMING_SNAKE_CASE_     ,	negative_prompt=SCREAMING_SNAKE_CASE_			)

													__UpperCamelCase       =			sd_pipe(
													    **SCREAMING_SNAKE_CASE_     ,	prompt_embeds=SCREAMING_SNAKE_CASE_     ,	negative_prompt_embeds=SCREAMING_SNAKE_CASE_     ,	pooled_prompt_embeds=SCREAMING_SNAKE_CASE_     ,	negative_pooled_prompt_embeds=SCREAMING_SNAKE_CASE_     ,	)
													__UpperCamelCase       =			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    ):

							"""simple docstring"""






							def     A__		(  self			)->   Optional[int]:





													'''simple docstring'''






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



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_="cpu"     ,	SCREAMING_SNAKE_CASE_=torch.floataa     ,	SCREAMING_SNAKE_CASE_=0			)->   Any:





													'''simple docstring'''






													__UpperCamelCase       =			torch.Generator(device=SCREAMING_SNAKE_CASE_			).manual_seed(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			np.random.RandomState(SCREAMING_SNAKE_CASE_			).standard_normal((1, 4, 64, 64)			)
													__UpperCamelCase       =			torch.from_numpy(SCREAMING_SNAKE_CASE_			).to(device=SCREAMING_SNAKE_CASE_     ,	dtype=SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			{
													    '''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			)->   Union[str, Any]:





													'''simple docstring'''






													__UpperCamelCase       =			DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''			)
													pipe.to(SCREAMING_SNAKE_CASE_			)
													pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_			)

													__UpperCamelCase       =			self.get_inputs(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			pipe(**SCREAMING_SNAKE_CASE_			).images
													__UpperCamelCase       =			image[0, -3:, -3:, -1].flatten()

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






import os
import re
import shutil
import sys
import tempfile
import unittest

import black


lowercase__							:							Optional[Any]									=			os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_copies  # noqa: E402


# This is the reference code that will be used in the tests.
# If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated.
lowercase__							:							Dict									=			"    \"\"\"\n    Output class for the scheduler's step function output.\n\n    Args:\n        prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n            Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the\n            denoising loop.\n        pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n            The predicted denoised sample (x_{0}) based on the model output from the current timestep.\n            `pred_original_sample` can be used to preview progress or for guidance.\n    \"\"\"\n\n    prev_sample: torch.FloatTensor\n    pred_original_sample: Optional[torch.FloatTensor] = None\n"






class        SCREAMING_SNAKE_CASE__    (							unittest.TestCase    ):

							"""simple docstring"""






							def     A__		(  self			)->   Dict:





													'''simple docstring'''






													__UpperCamelCase       =			tempfile.mkdtemp()
													os.makedirs(os.path.join(self.diffusers_dir     ,	'''schedulers/'''			)			)
													__UpperCamelCase       =			self.diffusers_dir
													shutil.copy(
													    os.path.join(SCREAMING_SNAKE_CASE_     ,	'''src/diffusers/schedulers/scheduling_ddpm.py'''			)     ,	os.path.join(self.diffusers_dir     ,	'''schedulers/scheduling_ddpm.py'''			)     ,	)



							def     A__		(  self			)->   Optional[int]:





													'''simple docstring'''






													__UpperCamelCase       =			'''src/diffusers'''
													shutil.rmtree(self.diffusers_dir			)



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=None			)->   Optional[Any]:





													'''simple docstring'''






													__UpperCamelCase       =			comment + F"\nclass {class_name}(nn.Module):\n" + class_code
													if overwrite_result is not None:
																			__UpperCamelCase       =			comment + F"\nclass {class_name}(nn.Module):\n" + overwrite_result
													__UpperCamelCase       =			black.Mode(target_versions={black.TargetVersion.PYaa}     ,	line_length=119			)
													__UpperCamelCase       =			black.format_str(SCREAMING_SNAKE_CASE_     ,	mode=SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			os.path.join(self.diffusers_dir     ,	'''new_code.py'''			)
													with open(SCREAMING_SNAKE_CASE_     ,	'''w'''     ,	newline='''\n'''			) as f:
																			f.write(SCREAMING_SNAKE_CASE_			)
													if overwrite_result is None:
																			self.assertTrue(len(check_copies.is_copy_consistent(SCREAMING_SNAKE_CASE_			)			) == 0			)
													else:
																			check_copies.is_copy_consistent(f.name     ,	overwrite=SCREAMING_SNAKE_CASE_			)
																			with open(SCREAMING_SNAKE_CASE_     ,	'''r'''			) as f:
																									self.assertTrue(f.read()     ,	SCREAMING_SNAKE_CASE_			)



							def     A__		(  self			)->   List[Any]:





													'''simple docstring'''






													__UpperCamelCase       =			check_copies.find_code_in_diffusers('''schedulers.scheduling_ddpm.DDPMSchedulerOutput'''			)
													self.assertEqual(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)



							def     A__		(  self			)->   List[str]:





													'''simple docstring'''






													self.check_copy_consistency(
													    '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput'''     ,	'''DDPMSchedulerOutput'''     ,	REFERENCE_CODE + '''\n'''     ,	)

													# With no empty line at the end
													self.check_copy_consistency(
													    '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput'''     ,	'''DDPMSchedulerOutput'''     ,	SCREAMING_SNAKE_CASE_     ,	)

													# Copy consistency with rename
													self.check_copy_consistency(
													    '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test'''     ,	'''TestSchedulerOutput'''     ,	re.sub('''DDPM'''     ,	'''Test'''     ,	SCREAMING_SNAKE_CASE_			)     ,	)

													# Copy consistency with a really long name
													__UpperCamelCase       =			'''TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason'''
													self.check_copy_consistency(
													    F"# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}"     ,	F"{long_class_name}SchedulerOutput"     ,	re.sub('''Bert'''     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)     ,	)

													# Copy consistency with overwrite
													self.check_copy_consistency(
													    '''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test'''     ,	'''TestSchedulerOutput'''     ,	SCREAMING_SNAKE_CASE_     ,	overwrite_result=re.sub('''DDPM'''     ,	'''Test'''     ,	SCREAMING_SNAKE_CASE_			)     ,	)




