




"""simple docstring"""






import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, 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 PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class lowerCAmelCase__      (	lowercase,      lowercase,      unittest.TestCase		):






			'''simple docstring'''



			lowerCamelCase__ =     StableDiffusionSAGPipeline
			lowerCamelCase__ =     TEXT_TO_IMAGE_PARAMS
			lowerCamelCase__ =     TEXT_TO_IMAGE_BATCH_PARAMS
			lowerCamelCase__ =     TEXT_TO_IMAGE_IMAGE_PARAMS
			lowerCamelCase__ =     TEXT_TO_IMAGE_IMAGE_PARAMS
			lowerCamelCase__ =     False
			def    A_       (    self    ):
							torch.manual_seed(0    )
							_lowerCamelCase	:     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')    , cross_attention_dim=32    , )
							_lowerCamelCase	:     List[str]       =       DDIMScheduler(
							    beta_start=0.0_00_85    , beta_end=0.0_12    , beta_schedule='scaled_linear'    , clip_sample=lowercase    , set_alpha_to_one=lowercase    , )
							torch.manual_seed(0    )
							_lowerCamelCase	:     List[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    , )
							torch.manual_seed(0    )
							_lowerCamelCase	:     str       =       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    , )
							_lowerCamelCase	:     Optional[int]       =       CLIPTextModel(lowercase    )
							_lowerCamelCase	:     Any       =       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    )

							_lowerCamelCase	:     Optional[Any]       =       {
							    'unet': unet,
							    'scheduler': scheduler,
							    'vae': vae,
							    'text_encoder': text_encoder,
							    'tokenizer': tokenizer,
							    'safety_checker': None,
							    'feature_extractor': None,
							}
							return components
			def    A_       (    self    , lowercase    , lowercase=0    ):
							if str(lowercase    ).startswith('mps'    ):
											_lowerCamelCase	:     Any       =       torch.manual_seed(lowercase    )
							else:
											_lowerCamelCase	:     str       =       torch.Generator(device=lowercase    ).manual_seed(lowercase    )
							_lowerCamelCase	:     int       =       {
							    'prompt': '.',
							    'generator': generator,
							    'num_inference_steps': 2,
							    'guidance_scale': 1.0,
							    'sag_scale': 1.0,
							    'output_type': 'numpy',
							}
							return inputs






			def    A_       (    self    ):
							super().test_inference_batch_single_identical(expected_max_diff=3E-3    )






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






			'''simple docstring'''



			def    A_       (    self    ):
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()
			def    A_       (    self    ):
							_lowerCamelCase	:     Tuple       =       StableDiffusionSAGPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'    )
							_lowerCamelCase	:     str       =       sag_pipe.to(lowercase    )
							sag_pipe.set_progress_bar_config(disable=lowercase    )

							_lowerCamelCase	:     Optional[int]       =       '.'
							_lowerCamelCase	:     List[Any]       =       torch.manual_seed(0    )
							_lowerCamelCase	:     Optional[Any]       =       sag_pipe(
							    [prompt]    , generator=lowercase    , guidance_scale=7.5    , sag_scale=1.0    , num_inference_steps=20    , output_type='np'    )

							_lowerCamelCase	:     List[Any]       =       output.images

							_lowerCamelCase	:     int       =       image[0, -3:, -3:, -1]

							assert image.shape == (1, 512, 512, 3)
							_lowerCamelCase	:     Optional[Any]       =       np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]    )

							assert np.abs(image_slice.flatten() - expected_slice    ).max() < 5E-2
			def    A_       (    self    ):
							_lowerCamelCase	:     List[Any]       =       StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'    )
							_lowerCamelCase	:     str       =       sag_pipe.to(lowercase    )
							sag_pipe.set_progress_bar_config(disable=lowercase    )

							_lowerCamelCase	:     Optional[Any]       =       '.'
							_lowerCamelCase	:     List[str]       =       torch.manual_seed(0    )
							_lowerCamelCase	:     Optional[Any]       =       sag_pipe(
							    [prompt]    , generator=lowercase    , guidance_scale=7.5    , sag_scale=1.0    , num_inference_steps=20    , output_type='np'    )

							_lowerCamelCase	:     Union[str, Any]       =       output.images

							_lowerCamelCase	:     Union[str, Any]       =       image[0, -3:, -3:, -1]

							assert image.shape == (1, 512, 512, 3)
							_lowerCamelCase	:     Dict       =       np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]    )

							assert np.abs(image_slice.flatten() - expected_slice    ).max() < 5E-2






			def    A_       (    self    ):
							_lowerCamelCase	:     int       =       StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'    )
							_lowerCamelCase	:     Optional[Any]       =       sag_pipe.to(lowercase    )
							sag_pipe.set_progress_bar_config(disable=lowercase    )

							_lowerCamelCase	:     List[Any]       =       '.'
							_lowerCamelCase	:     int       =       torch.manual_seed(0    )
							_lowerCamelCase	:     Dict       =       sag_pipe(
							    [prompt]    , width=768    , height=512    , generator=lowercase    , guidance_scale=7.5    , sag_scale=1.0    , num_inference_steps=20    , output_type='np'    , )

							_lowerCamelCase	:     List[Any]       =       output.images

							assert image.shape == (1, 512, 768, 3)







"""simple docstring"""


import unittest

import numpy as np

from diffusers import OnnxStableDiffusionInpaintPipelineLegacy
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    load_numpy,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)


if is_onnx_available():
		import onnxruntime as ort




@nightly
@require_onnxruntime
@require_torch_gpu
class 						__UpperCamelCase     (     unittest.TestCase						):
					@property
					def        UpperCAmelCase__ (							self							:	Union[str, Any]   )	->       Dict:
											return (
											    "CUDAExecutionProvider",
											    {
											        "gpu_mem_limit": "15000000000",  # 15GB
											        "arena_extend_strategy": "kSameAsRequested",
											    },
											)
					@property
					def        UpperCAmelCase__ (							self							:	int   )	->       Optional[Any]:
											lowerCAmelCase   :Any						=			ort.SessionOptions()
											lowerCAmelCase   :Dict						=			False
											return options
					def        UpperCAmelCase__ (							self							:	Tuple   )	->       str:
											lowerCAmelCase   :Union[str, Any]						=			load_image(
											    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
											    '/in_paint/overture-creations-5sI6fQgYIuo.png'   )
											lowerCAmelCase   :str						=			load_image(
											    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
											    '/in_paint/overture-creations-5sI6fQgYIuo_mask.png'   )
											lowerCAmelCase   :List[Any]						=			load_numpy(
											    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
											    '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy'   )

											# using the PNDM scheduler by default
											lowerCAmelCase   :Tuple						=			OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained(
											    'CompVis/stable-diffusion-v1-4'     , revision='onnx'     , safety_checker=UpperCAmelCase     , feature_extractor=UpperCAmelCase     , provider=self.gpu_provider     , sess_options=self.gpu_options     , )
											pipe.set_progress_bar_config(disable=UpperCAmelCase   )

											lowerCAmelCase   :Optional[Any]						=			'A red cat sitting on a park bench'

											lowerCAmelCase   :Optional[Any]						=			np.random.RandomState(0   )
											lowerCAmelCase   :Union[str, Any]						=			pipe(
											    prompt=UpperCAmelCase     , image=UpperCAmelCase     , mask_image=UpperCAmelCase     , strength=0.7_5     , guidance_scale=7.5     , num_inference_steps=15     , generator=UpperCAmelCase     , output_type='np'     , )

											lowerCAmelCase   :Optional[int]						=			output.images[0]

											assert image.shape == (512, 512, 3)
											assert np.abs(expected_image - image   ).max() < 1e-2