






import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import 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 PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


_UpperCAmelCase :			Tuple              =	False


@skip_mps
class     lowercase (		_SCREAMING_SNAKE_CASE  ,       _SCREAMING_SNAKE_CASE  ,       _SCREAMING_SNAKE_CASE  ,       unittest.TestCase       ):
		__lowercase	:	Optional[Any]     					=    StableDiffusionAttendAndExcitePipeline
		__lowercase	:	Optional[Any]     					=    False
		__lowercase	:	Dict     					=    TEXT_TO_IMAGE_PARAMS
		__lowercase	:	int     					=    TEXT_TO_IMAGE_BATCH_PARAMS.union({"token_indices"}       )
		__lowercase	:	Union[str, Any]     					=    TEXT_TO_IMAGE_IMAGE_PARAMS
		__lowercase	:	List[Any]     					=    TEXT_TO_IMAGE_IMAGE_PARAMS



		@classmethod
		def __UpperCamelCase			(			cls	)  -> Union[str, Any]:
				"""simple docstring"""
				super().setUpClass()
				torch.use_deterministic_algorithms(__lowerCAmelCase	)



		@classmethod
		def __UpperCamelCase			(			cls	)  -> List[str]:
				"""simple docstring"""
				super().tearDownClass()
				torch.use_deterministic_algorithms(__lowerCAmelCase	)



		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				torch.manual_seed(0	)
				UpperCamelCase          =					UNetaDConditionModel(
				    block_out_channels=(32, 64)    ,				layers_per_block=1    ,				sample_size=32    ,				in_channels=4    ,				out_channels=4    ,				down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')    ,				up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')    ,				cross_attention_dim=32    ,				attention_head_dim=(2, 4)    ,				use_linear_projection=__lowerCAmelCase    ,				)
				UpperCamelCase          =					DDIMScheduler(
				    beta_start=0.0_0085    ,				beta_end=0.012    ,				beta_schedule='scaled_linear'    ,				clip_sample=__lowerCAmelCase    ,				set_alpha_to_one=__lowerCAmelCase    ,				)
				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=1_000    ,				hidden_act='gelu'    ,				projection_dim=512    ,				)
				UpperCamelCase          =					CLIPTextModel(__lowerCAmelCase	)
				UpperCamelCase          =					CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'	)

				UpperCamelCase          =					{
				    'unet': unet,
				    'scheduler': scheduler,
				    'vae': vae,
				    'text_encoder': text_encoder,
				    'tokenizer': tokenizer,
				    'safety_checker': None,
				    'feature_extractor': None,
				}

				return components



		def __UpperCamelCase			(			self    ,				A_    ,				A_=0	)  -> Tuple:
				"""simple docstring"""



				if str(__lowerCAmelCase	).startswith('mps'	):
						UpperCamelCase          =					torch.manual_seed(__lowerCAmelCase	)
				else:
						UpperCamelCase          =					torch.Generator(device=__lowerCAmelCase	).manual_seed(__lowerCAmelCase	)
				UpperCamelCase          =					UpperCamelCase          =					{
				    'prompt': 'a cat and a frog',
				    'token_indices': [2, 5],
				    'generator': generator,
				    'num_inference_steps': 1,
				    'guidance_scale': 6.0,
				    'output_type': 'numpy',
				    'max_iter_to_alter': 2,
				    'thresholds': {0: 0.7},
				}
				return inputs



		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				UpperCamelCase          =					'cpu'

				UpperCamelCase          =					self.get_dummy_components()
				UpperCamelCase          =					self.pipeline_class(**__lowerCAmelCase	)
				pipe.to(__lowerCAmelCase	)
				pipe.set_progress_bar_config(disable=__lowerCAmelCase	)

				UpperCamelCase          =					self.get_dummy_inputs(__lowerCAmelCase	)
				UpperCamelCase          =					pipe(**__lowerCAmelCase	).images
				UpperCamelCase          =					image[0, -3:, -3:, -1]

				self.assertEqual(image.shape    ,				(1, 64, 64, 3)	)
				UpperCamelCase          =					np.array(
				    [0.6390_5364, 0.6289_7307, 0.4859_9017, 0.513_3624, 0.555_0048, 0.4576_9516, 0.5032_6973, 0.502_3139, 0.4538_4496]	)
				UpperCamelCase          =					np.abs(image_slice.flatten() - expected_slice	).max()
				self.assertLessEqual(__lowerCAmelCase    ,				1e-3	)



		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				super().test_cpu_offload_forward_pass(expected_max_diff=5e-4	)



		def __UpperCamelCase			(			self	)  -> Tuple:
				"""simple docstring"""
				self._test_inference_batch_consistent(batch_sizes=[1, 2]	)



		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				self._test_inference_batch_single_identical(batch_size=2    ,				expected_max_diff=7e-4	)



		def __UpperCamelCase			(			self	)  -> str:
				"""simple docstring"""
				super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3	)



		def __UpperCamelCase			(			self	)  -> Any:
				"""simple docstring"""
				super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4	)



		def __UpperCamelCase			(			self	)  -> Optional[Any]:
				"""simple docstring"""
				super().test_save_load_local(expected_max_difference=5e-4	)



		def __UpperCamelCase			(			self	)  -> Union[str, Any]:
				"""simple docstring"""
				super().test_save_load_optional_components(expected_max_difference=4e-4	)






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



		@classmethod
		def __UpperCamelCase			(			cls	)  -> Any:
				"""simple docstring"""
				super().setUpClass()
				torch.use_deterministic_algorithms(__lowerCAmelCase	)



		@classmethod
		def __UpperCamelCase			(			cls	)  -> List[str]:
				"""simple docstring"""
				super().tearDownClass()
				torch.use_deterministic_algorithms(__lowerCAmelCase	)



		def __UpperCamelCase			(			self	)  -> str:
				"""simple docstring"""
				super().tearDown()
				gc.collect()
				torch.cuda.empty_cache()



		def __UpperCamelCase			(			self	)  -> Union[str, Any]:
				"""simple docstring"""
				UpperCamelCase          =					torch.manual_seed(51	)

				UpperCamelCase          =					StableDiffusionAttendAndExcitePipeline.from_pretrained(
				    'CompVis/stable-diffusion-v1-4'    ,				safety_checker=__lowerCAmelCase    ,				torch_dtype=torch.floataa	)
				pipe.to('cuda'	)

				UpperCamelCase          =					'a painting of an elephant with glasses'
				UpperCamelCase          =					[5, 7]

				UpperCamelCase          =					pipe(
				    prompt=__lowerCAmelCase    ,				token_indices=__lowerCAmelCase    ,				guidance_scale=7.5    ,				generator=__lowerCAmelCase    ,				num_inference_steps=5    ,				max_iter_to_alter=5    ,				output_type='numpy'    ,				).images[0]

				UpperCamelCase          =					load_numpy(
				    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy'	)
				assert np.abs((expected_image - image).max()	) < 5e-1


_UpperCAmelCase :			str              =	[
    999,
    800,
    799,
    600,
    599,
    500,
    400,
    399,
    377,
    355,
    333,
    311,
    288,
    266,
    244,
    222,
    200,
    199,
    177,
    155,
    133,
    111,
    88,
    66,
    44,
    22,
    0,
]

_UpperCAmelCase :			Any              =	[
    999,
    976,
    952,
    928,
    905,
    882,
    858,
    857,
    810,
    762,
    715,
    714,
    572,
    429,
    428,
    286,
    285,
    238,
    190,
    143,
    142,
    118,
    95,
    71,
    47,
    24,
    0,
]

_UpperCAmelCase :			List[Any]              =	[
    999,
    988,
    977,
    966,
    955,
    944,
    933,
    922,
    911,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    350,
    300,
    299,
    266,
    233,
    200,
    199,
    179,
    159,
    140,
    120,
    100,
    99,
    88,
    77,
    66,
    55,
    44,
    33,
    22,
    11,
    0,
]

_UpperCAmelCase :			Tuple              =	[
    999,
    995,
    992,
    989,
    985,
    981,
    978,
    975,
    971,
    967,
    964,
    961,
    957,
    956,
    951,
    947,
    942,
    937,
    933,
    928,
    923,
    919,
    914,
    913,
    908,
    903,
    897,
    892,
    887,
    881,
    876,
    871,
    870,
    864,
    858,
    852,
    846,
    840,
    834,
    828,
    827,
    820,
    813,
    806,
    799,
    792,
    785,
    784,
    777,
    770,
    763,
    756,
    749,
    742,
    741,
    733,
    724,
    716,
    707,
    699,
    698,
    688,
    677,
    666,
    656,
    655,
    645,
    634,
    623,
    613,
    612,
    598,
    584,
    570,
    569,
    555,
    541,
    527,
    526,
    505,
    484,
    483,
    462,
    440,
    439,
    396,
    395,
    352,
    351,
    308,
    307,
    264,
    263,
    220,
    219,
    176,
    132,
    88,
    44,
    0,
]

_UpperCAmelCase :			Union[str, Any]              =	[
    999,
    997,
    995,
    992,
    990,
    988,
    986,
    984,
    981,
    979,
    977,
    975,
    972,
    970,
    968,
    966,
    964,
    961,
    959,
    957,
    956,
    954,
    951,
    949,
    946,
    944,
    941,
    939,
    936,
    934,
    931,
    929,
    926,
    924,
    921,
    919,
    916,
    914,
    913,
    910,
    907,
    905,
    902,
    899,
    896,
    893,
    891,
    888,
    885,
    882,
    879,
    877,
    874,
    871,
    870,
    867,
    864,
    861,
    858,
    855,
    852,
    849,
    846,
    843,
    840,
    837,
    834,
    831,
    828,
    827,
    824,
    821,
    817,
    814,
    811,
    808,
    804,
    801,
    798,
    795,
    791,
    788,
    785,
    784,
    780,
    777,
    774,
    770,
    766,
    763,
    760,
    756,
    752,
    749,
    746,
    742,
    741,
    737,
    733,
    730,
    726,
    722,
    718,
    714,
    710,
    707,
    703,
    699,
    698,
    694,
    690,
    685,
    681,
    677,
    673,
    669,
    664,
    660,
    656,
    655,
    650,
    646,
    641,
    636,
    632,
    627,
    622,
    618,
    613,
    612,
    607,
    602,
    596,
    591,
    586,
    580,
    575,
    570,
    569,
    563,
    557,
    551,
    545,
    539,
    533,
    527,
    526,
    519,
    512,
    505,
    498,
    491,
    484,
    483,
    474,
    466,
    457,
    449,
    440,
    439,
    428,
    418,
    407,
    396,
    395,
    381,
    366,
    352,
    351,
    330,
    308,
    307,
    286,
    264,
    263,
    242,
    220,
    219,
    176,
    175,
    132,
    131,
    88,
    44,
    0,
]

_UpperCAmelCase :			List[str]              =	[
    999,
    991,
    982,
    974,
    966,
    958,
    950,
    941,
    933,
    925,
    916,
    908,
    900,
    899,
    874,
    850,
    825,
    800,
    799,
    700,
    600,
    500,
    400,
    300,
    200,
    100,
    0,
]

_UpperCAmelCase :			Tuple              =	[
    999,
    992,
    985,
    978,
    971,
    964,
    957,
    949,
    942,
    935,
    928,
    921,
    914,
    907,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    300,
    299,
    200,
    199,
    100,
    99,
    0,
]

_UpperCAmelCase :			Dict              =	[
    999,
    996,
    992,
    989,
    985,
    982,
    979,
    975,
    972,
    968,
    965,
    961,
    958,
    955,
    951,
    948,
    944,
    941,
    938,
    934,
    931,
    927,
    924,
    920,
    917,
    914,
    910,
    907,
    903,
    900,
    899,
    891,
    884,
    876,
    869,
    861,
    853,
    846,
    838,
    830,
    823,
    815,
    808,
    800,
    799,
    788,
    777,
    766,
    755,
    744,
    733,
    722,
    711,
    700,
    699,
    688,
    677,
    666,
    655,
    644,
    633,
    622,
    611,
    600,
    599,
    585,
    571,
    557,
    542,
    528,
    514,
    500,
    499,
    485,
    471,
    457,
    442,
    428,
    414,
    400,
    399,
    379,
    359,
    340,
    320,
    300,
    299,
    279,
    259,
    240,
    220,
    200,
    199,
    166,
    133,
    100,
    99,
    66,
    33,
    0,
]
