






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


__a      :       Union[str, Any]				  =   False


@skip_mps
class       __lowercase      (	lowercase_			,      lowercase_			,      lowercase_			,      unittest.TestCase  ):







     '''simple docstring'''
     SCREAMING_SNAKE_CASE   						=				StableDiffusionAttendAndExcitePipeline
     SCREAMING_SNAKE_CASE   						=				False
     SCREAMING_SNAKE_CASE   						=				TEXT_TO_IMAGE_PARAMS
     SCREAMING_SNAKE_CASE   						=				TEXT_TO_IMAGE_BATCH_PARAMS.union({"token_indices"}  )
     SCREAMING_SNAKE_CASE   						=				TEXT_TO_IMAGE_IMAGE_PARAMS
     SCREAMING_SNAKE_CASE   						=				TEXT_TO_IMAGE_IMAGE_PARAMS




     @classmethod
     def 		lowerCAmelCase_     (				cls       :			Optional[int]				):


         """simple docstring"""



         super().setUpClass()
         torch.use_deterministic_algorithms(lowerCamelCase_				)




     @classmethod
     def 		lowerCAmelCase_     (				cls       :			List[str]				):


         """simple docstring"""



         super().tearDownClass()
         torch.use_deterministic_algorithms(lowerCamelCase_				)




     def 		lowerCAmelCase_     (				self       :			Dict				):


         """simple docstring"""



         torch.manual_seed(0				)
         __A         =	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_ ,	)
         __A         =	DDIMScheduler(
             beta_start=0.00085 ,	beta_end=0.012 ,	beta_schedule="""scaled_linear""" ,	clip_sample=lowerCamelCase_ ,	set_alpha_to_one=lowerCamelCase_ ,	)
         torch.manual_seed(0				)
         __A         =	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         =	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 ,	)
         __A         =	CLIPTextModel(lowerCamelCase_				)
         __A         =	CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""				)

         __A         =	{
             """unet""": unet,
             """scheduler""": scheduler,
             """vae""": vae,
             """text_encoder""": text_encoder,
             """tokenizer""": tokenizer,
             """safety_checker""": None,
             """feature_extractor""": None,
         }

         return components




     def 		lowerCAmelCase_     (				self       :			Dict ,	UpperCamelCase_       :			List[str] ,	UpperCamelCase_       :			Dict=0				):


         """simple docstring"""



         if str(lowerCamelCase_				).startswith("""mps"""				):
             __A         =	torch.manual_seed(lowerCamelCase_				)
         else:
             __A         =	torch.Generator(device=lowerCamelCase_				).manual_seed(lowerCamelCase_				)
         __A         =	{
             """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 		lowerCAmelCase_     (				self       :			Optional[int]				):


         """simple docstring"""



         __A         =	"""cpu"""

         __A         =	self.get_dummy_components()
         __A         =	self.pipeline_class(**lowerCamelCase_				)
         pipe.to(lowerCamelCase_				)
         pipe.set_progress_bar_config(disable=lowerCamelCase_				)

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

         self.assertEqual(image.shape ,	(1, 64, 64, 3)				)
         __A         =	np.array(
             [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496]				)
         __A         =	np.abs(image_slice.flatten() - expected_slice				).max()
         self.assertLessEqual(lowerCamelCase_ ,	1e-3				)




     def 		lowerCAmelCase_     (				self       :			List[str]				):


         """simple docstring"""



         super().test_cpu_offload_forward_pass(expected_max_diff=5e-4				)




     def 		lowerCAmelCase_     (				self       :			Any				):


         """simple docstring"""



         self._test_inference_batch_consistent(batch_sizes=[1, 2]				)




     def 		lowerCAmelCase_     (				self       :			Tuple				):


         """simple docstring"""



         self._test_inference_batch_single_identical(batch_size=2 ,	expected_max_diff=7e-4				)




     def 		lowerCAmelCase_     (				self       :			List[str]				):


         """simple docstring"""



         super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3				)




     def 		lowerCAmelCase_     (				self       :			str				):


         """simple docstring"""



         super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4				)




     def 		lowerCAmelCase_     (				self       :			Any				):


         """simple docstring"""



         super().test_save_load_local(expected_max_difference=5e-4				)





     def 		lowerCAmelCase_     (				self       :			int				):


         """simple docstring"""



         super().test_save_load_optional_components(expected_max_difference=4e-4				)


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







     '''simple docstring'''




     @classmethod
     def 		lowerCAmelCase_     (				cls       :			List[Any]				):


         """simple docstring"""



         super().setUpClass()
         torch.use_deterministic_algorithms(lowerCamelCase_				)




     @classmethod
     def 		lowerCAmelCase_     (				cls       :			int				):


         """simple docstring"""



         super().tearDownClass()
         torch.use_deterministic_algorithms(lowerCamelCase_				)




     def 		lowerCAmelCase_     (				self       :			Tuple				):


         """simple docstring"""



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





     def 		lowerCAmelCase_     (				self       :			int				):


         """simple docstring"""



         __A         =	torch.manual_seed(51				)

         __A         =	StableDiffusionAttendAndExcitePipeline.from_pretrained(
             """CompVis/stable-diffusion-v1-4""" ,	safety_checker=lowerCamelCase_ ,	torch_dtype=torch.floataa				)
         pipe.to("""cuda"""				)

         __A         =	"""a painting of an elephant with glasses"""
         __A         =	[5, 7]

         __A         =	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]

         __A         =	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












import os

import pytest

from datasets import (
    get_dataset_config_info,
    get_dataset_config_names,
    get_dataset_infos,
    get_dataset_split_names,
    inspect_dataset,
    inspect_metric,
)


__a      :       List[str]				  =   pytest.mark.integration



@pytest.mark.parametrize("""path"""			,				["""paws""", """csv"""]    )
def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			List[Any]			,				__lowercase   :			Optional[int]    )						->      Tuple:





    """simple docstring"""

    inspect_dataset(__lowercase			,				__lowercase    )
    __A         =	path + """.py"""
    assert script_name in os.listdir(__lowercase    )
    assert "__pycache__" not in os.listdir(__lowercase    )



@pytest.mark.filterwarnings("""ignore:inspect_metric is deprecated:FutureWarning"""    )
@pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning"""    )
@pytest.mark.parametrize("""path"""			,				["""accuracy"""]    )
def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			Optional[int]			,				__lowercase   :			Tuple    )						->      Any:





    """simple docstring"""

    inspect_metric(__lowercase			,				__lowercase    )
    __A         =	path + """.py"""
    assert script_name in os.listdir(__lowercase    )
    assert "__pycache__" not in os.listdir(__lowercase    )



@pytest.mark.parametrize(
    """path, config_name, expected_splits"""			,				[
        ("""squad""", """plain_text""", ["""train""", """validation"""]),
        ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]),
        ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]),
    ]			,				)
def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			Dict			,				__lowercase   :			Optional[int]			,				__lowercase   :			List[Any]    )						->      Optional[Any]:





    """simple docstring"""

    __A         =	get_dataset_config_info(__lowercase			,				config_name=__lowercase    )
    assert info.config_name == config_name
    assert list(info.splits.keys()    ) == expected_splits



@pytest.mark.parametrize(
    """path, config_name, expected_exception"""			,				[
        ("""paws""", None, ValueError),
    ]			,				)
def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			List[Any]			,				__lowercase   :			int			,				__lowercase   :			List[str]    )						->      int:





    """simple docstring"""

    with pytest.raises(__lowercase    ):
        get_dataset_config_info(__lowercase			,				config_name=__lowercase    )



@pytest.mark.parametrize(
    """path, expected"""			,				[
        ("""squad""", """plain_text"""),
        ("""acronym_identification""", """default"""),
        ("""lhoestq/squad""", """plain_text"""),
        ("""lhoestq/test""", """default"""),
        ("""lhoestq/demo1""", """lhoestq--demo1"""),
        ("""dalle-mini/wit""", """dalle-mini--wit"""),
    ]			,				)
def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			Tuple			,				__lowercase   :			Optional[Any]    )						->      Any:





    """simple docstring"""

    __A         =	get_dataset_config_names(__lowercase    )
    assert expected in config_names



@pytest.mark.parametrize(
    """path, expected_configs, expected_splits_in_first_config"""			,				[
        ("""squad""", ["""plain_text"""], ["""train""", """validation"""]),
        ("""dalle-mini/wit""", ["""dalle-mini--wit"""], ["""train"""]),
        ("""paws""", ["""labeled_final""", """labeled_swap""", """unlabeled_final"""], ["""train""", """test""", """validation"""]),
    ]			,				)
def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			int			,				__lowercase   :			Tuple			,				__lowercase   :			List[Any]    )						->      List[str]:





    """simple docstring"""

    __A         =	get_dataset_infos(__lowercase    )
    assert list(infos.keys()    ) == expected_configs
    __A         =	expected_configs[0]
    assert expected_config in infos
    __A         =	infos[expected_config]
    assert info.config_name == expected_config
    assert list(info.splits.keys()    ) == expected_splits_in_first_config



@pytest.mark.parametrize(
    """path, expected_config, expected_splits"""			,				[
        ("""squad""", """plain_text""", ["""train""", """validation"""]),
        ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]),
        ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]),
    ]			,				)
def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			Optional[int]			,				__lowercase   :			str			,				__lowercase   :			Union[str, Any]    )						->      Dict:





    """simple docstring"""

    __A         =	get_dataset_infos(__lowercase    )
    assert expected_config in infos
    __A         =	infos[expected_config]
    assert info.config_name == expected_config
    assert list(info.splits.keys()    ) == expected_splits






@pytest.mark.parametrize(
    """path, config_name, expected_exception"""			,				[
        ("""paws""", None, ValueError),
    ]			,				)
def 			_SCREAMING_SNAKE_CASE						( __lowercase   :			List[str]			,				__lowercase   :			Optional[int]			,				__lowercase   :			Tuple    )						->      Union[str, Any]:





    """simple docstring"""

    with pytest.raises(__lowercase    ):
        get_dataset_split_names(__lowercase			,				config_name=__lowercase    )




