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


__lowercase											=      False


@skip_mps
class 			lowerCamelCase_  (     __SCREAMING_SNAKE_CASE		,			__SCREAMING_SNAKE_CASE		,			__SCREAMING_SNAKE_CASE		,			unittest.TestCase				):






    '''simple docstring'''






    a__			:		str      			=   StableDiffusionAttendAndExcitePipeline
    a__			:		Any      			=   False
    a__			:		Tuple      			=   TEXT_TO_IMAGE_PARAMS
    a__			:		Optional[Any]      			=   TEXT_TO_IMAGE_BATCH_PARAMS.union({"""token_indices"""}				)
    a__			:		str      			=   TEXT_TO_IMAGE_IMAGE_PARAMS
    a__			:		List[Any]      			=   TEXT_TO_IMAGE_IMAGE_PARAMS







    @classmethod
    def     UpperCamelCase__     (			cls) ->			List[str]:
        super().setUpClass()
        torch.use_deterministic_algorithms(_a)







    @classmethod
    def     UpperCamelCase__     (			cls) ->			str:
        super().tearDownClass()
        torch.use_deterministic_algorithms(_a)







    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        torch.manual_seed(0)
        __UpperCamelCase  :Tuple    						=	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=_a				,				)
        __UpperCamelCase  :List[Any]    						=	DDIMScheduler(
            beta_start=0.0_00_85				,				beta_end=0.0_12				,				beta_schedule='''scaled_linear'''				,				clip_sample=_a				,				set_alpha_to_one=_a				,				)
        torch.manual_seed(0)
        __UpperCamelCase  :str    						=	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-0_5				,				num_attention_heads=4				,				num_hidden_layers=5				,				pad_token_id=1				,				vocab_size=1_000				,				hidden_act='''gelu'''				,				projection_dim=512				,				)
        __UpperCamelCase  :str    						=	CLIPTextModel(_a)
        __UpperCamelCase  :Optional[Any]    						=	CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

        __UpperCamelCase  :Union[str, Any]    						=	{
            '''unet''': unet,
            '''scheduler''': scheduler,
            '''vae''': vae,
            '''text_encoder''': text_encoder,
            '''tokenizer''': tokenizer,
            '''safety_checker''': None,
            '''feature_extractor''': None,
        }

        return components







    def     UpperCamelCase__     (			self				,				__lowercase				,				__lowercase=0) ->			Tuple:
        if str(_a).startswith('''mps'''):
            __UpperCamelCase  :List[str]    						=	torch.manual_seed(_a)
        else:
            __UpperCamelCase  :List[str]    						=	torch.Generator(device=_a).manual_seed(_a)
        __UpperCamelCase  :str    						=	{
            '''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) ->			List[Any]:
        __UpperCamelCase  :Any    						=	'''cpu'''

        __UpperCamelCase  :Union[str, Any]    						=	self.get_dummy_components()
        __UpperCamelCase  :Optional[int]    						=	self.pipeline_class(**_a)
        pipe.to(_a)
        pipe.set_progress_bar_config(disable=_a)

        __UpperCamelCase  :int    						=	self.get_dummy_inputs(_a)
        __UpperCamelCase  :Optional[Any]    						=	pipe(**_a).images
        __UpperCamelCase  :int    						=	image[0, -3:, -3:, -1]

        self.assertEqual(image.shape				,				(1, 64, 64, 3))
        __UpperCamelCase  :Optional[Any]    						=	np.array(
            [0.63_90_53_64, 0.62_89_73_07, 0.48_59_90_17, 0.5_13_36_24, 0.5_55_00_48, 0.45_76_95_16, 0.50_32_69_73, 0.5_02_31_39, 0.45_38_44_96])
        __UpperCamelCase  :List[Any]    						=	np.abs(image_slice.flatten() - expected_slice).max()
        self.assertLessEqual(_a				,				1E-3)







    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        super().test_cpu_offload_forward_pass(expected_max_diff=5E-4)







    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
        self._test_inference_batch_consistent(batch_sizes=[1, 2])







    def     UpperCamelCase__     (			self) ->			Optional[int]:
        self._test_inference_batch_single_identical(batch_size=2				,				expected_max_diff=7E-4)







    def     UpperCamelCase__     (			self) ->			Optional[Any]:
        super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3)







    def     UpperCamelCase__     (			self) ->			Union[str, Any]:
        super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4)







    def     UpperCamelCase__     (			self) ->			Optional[int]:
        super().test_save_load_local(expected_max_difference=5E-4)







    def     UpperCamelCase__     (			self) ->			str:
        super().test_save_load_optional_components(expected_max_difference=4E-4)


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






    '''simple docstring'''






    @classmethod
    def     UpperCamelCase__     (			cls) ->			str:
        super().setUpClass()
        torch.use_deterministic_algorithms(_a)







    @classmethod
    def     UpperCamelCase__     (			cls) ->			Optional[Any]:
        super().tearDownClass()
        torch.use_deterministic_algorithms(_a)







    def     UpperCamelCase__     (			self) ->			Tuple:
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()







    def     UpperCamelCase__     (			self) ->			Tuple:
        __UpperCamelCase  :Union[str, Any]    						=	torch.manual_seed(51)

        __UpperCamelCase  :Union[str, Any]    						=	StableDiffusionAttendAndExcitePipeline.from_pretrained(
            '''CompVis/stable-diffusion-v1-4'''				,				safety_checker=_a				,				torch_dtype=torch.floataa)
        pipe.to('''cuda''')

        __UpperCamelCase  :Dict    						=	'''a painting of an elephant with glasses'''
        __UpperCamelCase  :Union[str, Any]    						=	[5, 7]

        __UpperCamelCase  :Union[str, Any]    						=	pipe(
            prompt=_a				,				token_indices=_a				,				guidance_scale=7.5				,				generator=_a				,				num_inference_steps=5				,				max_iter_to_alter=5				,				output_type='''numpy'''				,				).images[0]

        __UpperCamelCase  :Tuple    						=	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 numpy as np
from cva import COLOR_BGR2GRAY, cvtColor, imread
from numpy import array, uinta
from PIL import Image

from digital_image_processing import change_contrast as cc
from digital_image_processing import convert_to_negative as cn
from digital_image_processing import sepia as sp
from digital_image_processing.dithering import burkes as bs
from digital_image_processing.edge_detection import canny
from digital_image_processing.filters import convolve as conv
from digital_image_processing.filters import gaussian_filter as gg
from digital_image_processing.filters import local_binary_pattern as lbp
from digital_image_processing.filters import median_filter as med
from digital_image_processing.filters import sobel_filter as sob
from digital_image_processing.resize import resize as rs

__lowercase											=      imread(r'''digital_image_processing/image_data/lena_small.jpg''')
__lowercase											=      cvtColor(img, COLOR_BGR2GRAY)



def lowerCamelCase						(     ):
    '''simple docstring'''







    __UpperCamelCase  :Optional[Any]    						=	cn.convert_to_negative(SCREAMING_SNAKE_CASE			)
    # assert negative_img array for at least one True
    assert negative_img.any()



def lowerCamelCase						(     ):
    '''simple docstring'''







    with Image.open('''digital_image_processing/image_data/lena_small.jpg'''			) as img:
        # Work around assertion for response
        assert str(cc.change_contrast(SCREAMING_SNAKE_CASE						,    110			)			).startswith(
            '''<PIL.Image.Image image mode=RGB size=100x100 at'''			)



def lowerCamelCase						(     ):
    '''simple docstring'''







    __UpperCamelCase  :List[Any]    						=	canny.gen_gaussian_kernel(9						,    sigma=1.4			)
    # Assert ambiguous array
    assert resp.all()



def lowerCamelCase						(     ):
    '''simple docstring'''







    __UpperCamelCase  :List[str]    						=	imread('''digital_image_processing/image_data/lena_small.jpg'''						,    0			)
    # assert ambiguous array for all == True
    assert canny_img.all()
    __UpperCamelCase  :str    						=	canny.canny(SCREAMING_SNAKE_CASE			)
    # assert canny array for at least one True
    assert canny_array.any()



def lowerCamelCase						(     ):
    '''simple docstring'''







    assert gg.gaussian_filter(SCREAMING_SNAKE_CASE						,    5						,    sigma=0.9			).all()



def lowerCamelCase						(     ):
    '''simple docstring'''







    __UpperCamelCase  :List[str]    						=	array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]			)
    __UpperCamelCase  :Optional[Any]    						=	conv.img_convolve(SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE			).astype(SCREAMING_SNAKE_CASE			)
    assert res.any()



def lowerCamelCase						(     ):
    '''simple docstring'''







    assert med.median_filter(SCREAMING_SNAKE_CASE						,    3			).any()



def lowerCamelCase						(     ):
    '''simple docstring'''







    __UpperCamelCase						, __UpperCamelCase  :Dict    						=	sob.sobel_filter(SCREAMING_SNAKE_CASE			)
    assert grad.any() and theta.any()



def lowerCamelCase						(     ):
    '''simple docstring'''







    __UpperCamelCase  :Dict    						=	sp.make_sepia(SCREAMING_SNAKE_CASE						,    20			)
    assert sepia.all()



def lowerCamelCase						(     SCREAMING_SNAKE_CASE = "digital_image_processing/image_data/lena_small.jpg"			):
    '''simple docstring'''







    __UpperCamelCase  :Dict    						=	bs.Burkes(imread(SCREAMING_SNAKE_CASE						,    1			)						,    120			)
    burkes.process()
    assert burkes.output_img.any()



def lowerCamelCase						(     SCREAMING_SNAKE_CASE = "digital_image_processing/image_data/lena_small.jpg"						,    ):
    '''simple docstring'''







    __UpperCamelCase  :List[str]    						=	rs.NearestNeighbour(imread(SCREAMING_SNAKE_CASE						,    1			)						,    400						,    200			)
    nn.process()
    assert nn.output.any()



def lowerCamelCase						(     ):
    '''simple docstring'''







    __UpperCamelCase  :Union[str, Any]    						=	'''digital_image_processing/image_data/lena.jpg'''

    # Reading the image and converting it to grayscale.
    __UpperCamelCase  :Optional[int]    						=	imread(SCREAMING_SNAKE_CASE						,    0			)

    # Test for get_neighbors_pixel function() return not None
    __UpperCamelCase  :Optional[int]    						=	0
    __UpperCamelCase  :List[Any]    						=	0
    __UpperCamelCase  :Dict    						=	image[x_coordinate][y_coordinate]

    __UpperCamelCase  :int    						=	lbp.get_neighbors_pixel(
        SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE			)

    assert neighbors_pixels is not None

    # Test for local_binary_pattern function()
    # Create a numpy array as the same height and width of read image
    __UpperCamelCase  :Tuple    						=	np.zeros((image.shape[0], image.shape[1])			)

    # Iterating through the image and calculating the local binary pattern value
    # for each pixel.
    for i in range(0						,    image.shape[0]			):
        for j in range(0						,    image.shape[1]			):
            __UpperCamelCase  :Optional[int]    						=	lbp.local_binary_value(SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE						,    SCREAMING_SNAKE_CASE			)

    assert lbp_image.any()





