
"""simple docstring"""







import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()







class 							__magic_name__     (		unittest.TestCase   ):





					def 							lowerCAmelCase      (				self   :							int    ):
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()





					@property
					def 							lowerCAmelCase      (				self   :							str    ):
												__snake_case     			=       1
												__snake_case     			=       3
												__snake_case     			=       (32, 32)

												__snake_case     			=       floats_tensor((batch_size, num_channels) + sizes							,						rng=random.Random(0    )    ).to(lowerCAmelCase_    )
												return image





					@property
					def 							lowerCAmelCase      (				self   :							Optional[int]    ):
												torch.manual_seed(0    )
												__snake_case     			=       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							,						)
												return model





					@property
					def 							lowerCAmelCase      (				self   :							List[str]    ):
												torch.manual_seed(0    )
												__snake_case     			=       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							,						)
												return model





					@property
					def 							lowerCAmelCase      (				self   :							str    ):
												torch.manual_seed(0    )
												__snake_case     			=       RobertaSeriesConfig(
												    hidden_size=32							,						project_dim=32							,						intermediate_size=37							,						layer_norm_eps=1e-05							,						num_attention_heads=4							,						num_hidden_layers=5							,						pad_token_id=1							,						vocab_size=5006							,						)
												return RobertaSeriesModelWithTransformation(lowerCAmelCase_    )





					@property
					def 							lowerCAmelCase      (				self   :							str    ):







												def extract(*snake_case_   :							Tuple							,						**snake_case_   :							Union[str, Any]    ):







																			class 							__magic_name__     :





																								def __init__(				self   :							Tuple    ):
																															__snake_case     			=       torch.ones([0]    )





																								def 							lowerCAmelCase      (				self   :							str							,						snake_case_   :							Dict    ):
																															self.pixel_values.to(lowerCAmelCase_    )
																															return self




																			return Out()

												return extract





					def 							lowerCAmelCase      (				self   :							Tuple    ):
												__snake_case     			=       "cpu"  # ensure determinism for the device-dependent torch.Generator
												__snake_case     			=       self.dummy_cond_unet
												__snake_case     			=       PNDMScheduler(skip_prk_steps=lowerCAmelCase_    )
												__snake_case     			=       self.dummy_vae
												__snake_case     			=       self.dummy_text_encoder
												__snake_case     			=       XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"    )
												__snake_case     			=       77

												__snake_case     			=       self.dummy_image.to(lowerCAmelCase_    )
												__snake_case     			=       init_image / 2 + 0.5

												# make sure here that pndm scheduler skips prk
												__snake_case     			=       AltDiffusionImgaImgPipeline(
												    unet=lowerCAmelCase_							,						scheduler=lowerCAmelCase_							,						vae=lowerCAmelCase_							,						text_encoder=lowerCAmelCase_							,						tokenizer=lowerCAmelCase_							,						safety_checker=lowerCAmelCase_							,						feature_extractor=self.dummy_extractor							,						)
												__snake_case     			=       VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor							,						do_normalize=lowerCAmelCase_    )
												__snake_case     			=       alt_pipe.to(lowerCAmelCase_    )
												alt_pipe.set_progress_bar_config(disable=lowerCAmelCase_    )

												__snake_case     			=       "A painting of a squirrel eating a burger"
												__snake_case     			=       torch.Generator(device=lowerCAmelCase_    ).manual_seed(0    )
												__snake_case     			=       alt_pipe(
												    [prompt]							,						generator=lowerCAmelCase_							,						guidance_scale=6.0							,						num_inference_steps=2							,						output_type="np"							,						image=lowerCAmelCase_							,						)

												__snake_case     			=       output.images

												__snake_case     			=       torch.Generator(device=lowerCAmelCase_    ).manual_seed(0    )
												__snake_case     			=       alt_pipe(
												    [prompt]							,						generator=lowerCAmelCase_							,						guidance_scale=6.0							,						num_inference_steps=2							,						output_type="np"							,						image=lowerCAmelCase_							,						return_dict=lowerCAmelCase_							,						)[0]

												__snake_case     			=       image[0, -3:, -3:, -1]
												__snake_case     			=       image_from_tuple[0, -3:, -3:, -1]

												assert image.shape == (1, 32, 32, 3)
												__snake_case     			=       np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]    )

												assert np.abs(image_slice.flatten() - expected_slice    ).max() < 5e-3
												assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() < 5e-3





					@unittest.skipIf(torch_device != "cuda"							,						"This test requires a GPU"    )
					def 							lowerCAmelCase      (				self   :							List[str]    ):
												__snake_case     			=       self.dummy_cond_unet
												__snake_case     			=       PNDMScheduler(skip_prk_steps=lowerCAmelCase_    )
												__snake_case     			=       self.dummy_vae
												__snake_case     			=       self.dummy_text_encoder
												__snake_case     			=       XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"    )
												__snake_case     			=       77

												__snake_case     			=       self.dummy_image.to(lowerCAmelCase_    )

												# put models in fp16
												__snake_case     			=       unet.half()
												__snake_case     			=       vae.half()
												__snake_case     			=       bert.half()

												# make sure here that pndm scheduler skips prk
												__snake_case     			=       AltDiffusionImgaImgPipeline(
												    unet=lowerCAmelCase_							,						scheduler=lowerCAmelCase_							,						vae=lowerCAmelCase_							,						text_encoder=lowerCAmelCase_							,						tokenizer=lowerCAmelCase_							,						safety_checker=lowerCAmelCase_							,						feature_extractor=self.dummy_extractor							,						)
												__snake_case     			=       VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor							,						do_normalize=lowerCAmelCase_    )
												__snake_case     			=       alt_pipe.to(lowerCAmelCase_    )
												alt_pipe.set_progress_bar_config(disable=lowerCAmelCase_    )

												__snake_case     			=       "A painting of a squirrel eating a burger"
												__snake_case     			=       torch.manual_seed(0    )
												__snake_case     			=       alt_pipe(
												    [prompt]							,						generator=lowerCAmelCase_							,						num_inference_steps=2							,						output_type="np"							,						image=lowerCAmelCase_							,						).images

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





					@unittest.skipIf(torch_device != "cuda"							,						"This test requires a GPU"    )
					def 							lowerCAmelCase      (				self   :							Tuple    ):
												__snake_case     			=       load_image(
												    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
												    "/img2img/sketch-mountains-input.jpg"    )
												# resize to resolution that is divisible by 8 but not 16 or 32
												__snake_case     			=       init_image.resize((760, 504)    )

												__snake_case     			=       "BAAI/AltDiffusion"
												__snake_case     			=       AltDiffusionImgaImgPipeline.from_pretrained(
												    lowerCAmelCase_							,						safety_checker=lowerCAmelCase_							,						)
												pipe.to(lowerCAmelCase_    )
												pipe.set_progress_bar_config(disable=lowerCAmelCase_    )
												pipe.enable_attention_slicing()

												__snake_case     			=       "A fantasy landscape, trending on artstation"

												__snake_case     			=       torch.manual_seed(0    )
												__snake_case     			=       pipe(
												    prompt=lowerCAmelCase_							,						image=lowerCAmelCase_							,						strength=0.75							,						guidance_scale=7.5							,						generator=lowerCAmelCase_							,						output_type="np"							,						)
												__snake_case     			=       output.images[0]

												__snake_case     			=       image[255:258, 383:386, -1]

												assert image.shape == (504, 760, 3)
												__snake_case     			=       np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]    )

												assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2







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





					def 							lowerCAmelCase      (				self   :							str    ):
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()





					def 							lowerCAmelCase      (				self   :							Any    ):
												__snake_case     			=       load_image(
												    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
												    "/img2img/sketch-mountains-input.jpg"    )
												__snake_case     			=       init_image.resize((768, 512)    )
												__snake_case     			=       load_numpy(
												    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"    )

												__snake_case     			=       "BAAI/AltDiffusion"
												__snake_case     			=       AltDiffusionImgaImgPipeline.from_pretrained(
												    lowerCAmelCase_							,						safety_checker=lowerCAmelCase_							,						)
												pipe.to(lowerCAmelCase_    )
												pipe.set_progress_bar_config(disable=lowerCAmelCase_    )
												pipe.enable_attention_slicing()

												__snake_case     			=       "A fantasy landscape, trending on artstation"

												__snake_case     			=       torch.manual_seed(0    )
												__snake_case     			=       pipe(
												    prompt=lowerCAmelCase_							,						image=lowerCAmelCase_							,						strength=0.75							,						guidance_scale=7.5							,						generator=lowerCAmelCase_							,						output_type="np"							,						)
												__snake_case     			=       output.images[0]

												assert image.shape == (512, 768, 3)
												# img2img is flaky across GPUs even in fp32, so using MAE here
												assert np.abs(expected_image - image    ).max() < 1e-2


"""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 							__magic_name__     (		unittest.TestCase   ):





					@property
					def 							lowerCAmelCase      (				self   :							Union[str, Any]    ):
												return (
												    "CUDAExecutionProvider",
												    {
												        "gpu_mem_limit": "15000000000",  # 15GB
												        "arena_extend_strategy": "kSameAsRequested",
												    },
												)





					@property
					def 							lowerCAmelCase      (				self   :							str    ):
												__snake_case     			=       ort.SessionOptions()
												__snake_case     			=       False
												return options





					def 							lowerCAmelCase      (				self   :							Tuple    ):
												__snake_case     			=       load_image(
												    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
												    "/in_paint/overture-creations-5sI6fQgYIuo.png"    )
												__snake_case     			=       load_image(
												    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
												    "/in_paint/overture-creations-5sI6fQgYIuo_mask.png"    )
												__snake_case     			=       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
												__snake_case     			=       OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained(
												    "CompVis/stable-diffusion-v1-4"							,						revision="onnx"							,						safety_checker=snake_case_							,						feature_extractor=snake_case_							,						provider=self.gpu_provider							,						sess_options=self.gpu_options							,						)
												pipe.set_progress_bar_config(disable=snake_case_    )

												__snake_case     			=       "A red cat sitting on a park bench"

												__snake_case     			=       np.random.RandomState(0    )
												__snake_case     			=       pipe(
												    prompt=snake_case_							,						image=snake_case_							,						mask_image=snake_case_							,						strength=0.75							,						guidance_scale=7.5							,						num_inference_steps=15							,						generator=snake_case_							,						output_type="np"							,						)

												__snake_case     			=       output.images[0]

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