



import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
						import onnxruntime as ort



class 				__snake_case						(     UpperCamelCase_						,unittest.TestCase						):
							# TODO: is there an appropriate internal test set?
							_a			      = '''ssube/stable-diffusion-x4-upscaler-onnx'''




							def    UpperCAmelCase__			(       self     :       Tuple				,				A_     :       Optional[Any]=0):
									lowerCAmelCase_			:     Optional[Any]									= floats_tensor((1, 3, 1_2_8, 1_2_8)				,				rng=random.Random(A_))
									lowerCAmelCase_			:     Dict									= torch.manual_seed(A_)
									lowerCAmelCase_			:     Dict									= {
									    '''prompt''': '''A painting of a squirrel eating a burger''',
									    '''image''': image,
									    '''generator''': generator,
									    '''num_inference_steps''': 3,
									    '''guidance_scale''': 7.5,
									    '''output_type''': '''numpy''',
									}
									return inputs




							def    UpperCAmelCase__			(       self     :       List[str]):
									lowerCAmelCase_			:     int									= OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider='''CPUExecutionProvider''')
									pipe.set_progress_bar_config(disable=A_)

									lowerCAmelCase_			:     List[str]									= self.get_dummy_inputs()
									lowerCAmelCase_			:     Any									= pipe(**A_).images
									lowerCAmelCase_			:     Optional[int]									= image[0, -3:, -3:, -1].flatten()

									# started as 128, should now be 512
									assert image.shape == (1, 5_1_2, 5_1_2, 3)
									lowerCAmelCase_			:     List[str]									= np.array(
									    [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223])
									assert np.abs(image_slice - expected_slice).max() < 1e-1




							def    UpperCAmelCase__			(       self     :       Union[str, Any]):
									lowerCAmelCase_			:     Union[str, Any]									= OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider='''CPUExecutionProvider''')
									lowerCAmelCase_			:     List[str]									= PNDMScheduler.from_config(pipe.scheduler.config				,				skip_prk_steps=A_)
									pipe.set_progress_bar_config(disable=A_)

									lowerCAmelCase_			:     Any									= self.get_dummy_inputs()
									lowerCAmelCase_			:     int									= pipe(**A_).images
									lowerCAmelCase_			:     List[Any]									= image[0, -3:, -3:, -1]

									assert image.shape == (1, 5_1_2, 5_1_2, 3)
									lowerCAmelCase_			:     str									= np.array(
									    [0.689_8892, 0.5924_0556, 0.5249_9527, 0.5886_6215, 0.5225_8235, 0.5257_2715, 0.6241_4473, 0.617_4387, 0.621_4964])
									assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1




							def    UpperCAmelCase__			(       self     :       Dict):
									lowerCAmelCase_			:     List[Any]									= OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider='''CPUExecutionProvider''')
									lowerCAmelCase_			:     int									= DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
									pipe.set_progress_bar_config(disable=A_)

									lowerCAmelCase_			:     Optional[Any]									= self.get_dummy_inputs()
									lowerCAmelCase_			:     Optional[int]									= pipe(**A_).images
									lowerCAmelCase_			:     Union[str, Any]									= image[0, -3:, -3:, -1]

									assert image.shape == (1, 5_1_2, 5_1_2, 3)
									lowerCAmelCase_			:     Optional[int]									= np.array(
									    [0.765_9278, 0.7643_7664, 0.7557_9107, 0.769_1116, 0.7766_6986, 0.772_7672, 0.775_8664, 0.781_2226, 0.7694_2515])

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




							def    UpperCAmelCase__			(       self     :       Optional[Any]):
									lowerCAmelCase_			:     Union[str, Any]									= OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider='''CPUExecutionProvider''')
									lowerCAmelCase_			:     Tuple									= EulerDiscreteScheduler.from_config(pipe.scheduler.config)
									pipe.set_progress_bar_config(disable=A_)

									lowerCAmelCase_			:     str									= self.get_dummy_inputs()
									lowerCAmelCase_			:     int									= pipe(**A_).images
									lowerCAmelCase_			:     Union[str, Any]									= image[0, -3:, -3:, -1]

									assert image.shape == (1, 5_1_2, 5_1_2, 3)
									lowerCAmelCase_			:     Tuple									= np.array(
									    [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223])
									assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1







							def    UpperCAmelCase__			(       self     :       Optional[int]):
									lowerCAmelCase_			:     int									= OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider='''CPUExecutionProvider''')
									lowerCAmelCase_			:     List[Any]									= EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
									pipe.set_progress_bar_config(disable=A_)

									lowerCAmelCase_			:     Tuple									= self.get_dummy_inputs()
									lowerCAmelCase_			:     Dict									= pipe(**A_).images
									lowerCAmelCase_			:     List[str]									= image[0, -3:, -3:, -1]

									assert image.shape == (1, 5_1_2, 5_1_2, 3)
									lowerCAmelCase_			:     List[str]									= np.array(
									    [0.7742_4496, 0.77_3601, 0.764_5288, 0.776_9598, 0.777_2739, 0.773_8688, 0.7818_7233, 0.7787_9584, 0.76_7043])

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





@nightly
@require_onnxruntime
@require_torch_gpu
class 				__snake_case						(     unittest.TestCase						):




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




							@property
							def    UpperCAmelCase__			(       self     :       Any):
									lowerCAmelCase_			:     Dict									= ort.SessionOptions()
									lowerCAmelCase_			:     Optional[int]									= False
									return options




							def    UpperCAmelCase__			(       self     :       str):
									lowerCAmelCase_			:     Any									= load_image(
									    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
									    '''/img2img/sketch-mountains-input.jpg''')
									lowerCAmelCase_			:     Tuple									= init_image.resize((1_2_8, 1_2_8))
									# using the PNDM scheduler by default
									lowerCAmelCase_			:     Union[str, Any]									= OnnxStableDiffusionUpscalePipeline.from_pretrained(
									    '''ssube/stable-diffusion-x4-upscaler-onnx'''				,				provider=self.gpu_provider				,				sess_options=self.gpu_options				,				)
									pipe.set_progress_bar_config(disable=A_)

									lowerCAmelCase_			:     Optional[Any]									= '''A fantasy landscape, trending on artstation'''

									lowerCAmelCase_			:     str									= torch.manual_seed(0)
									lowerCAmelCase_			:     Optional[Any]									= pipe(
									    prompt=A_				,				image=A_				,				guidance_scale=7.5				,				num_inference_steps=1_0				,				generator=A_				,				output_type='''np'''				,				)
									lowerCAmelCase_			:     Union[str, Any]									= output.images
									lowerCAmelCase_			:     List[Any]									= images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

									assert images.shape == (1, 5_1_2, 5_1_2, 3)
									lowerCAmelCase_			:     Optional[Any]									= np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972])
									# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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







							def    UpperCAmelCase__			(       self     :       Dict):
									lowerCAmelCase_			:     Tuple									= load_image(
									    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
									    '''/img2img/sketch-mountains-input.jpg''')
									lowerCAmelCase_			:     List[str]									= init_image.resize((1_2_8, 1_2_8))
									lowerCAmelCase_			:     Dict									= LMSDiscreteScheduler.from_pretrained(
									    '''ssube/stable-diffusion-x4-upscaler-onnx'''				,				subfolder='''scheduler''')
									lowerCAmelCase_			:     List[str]									= OnnxStableDiffusionUpscalePipeline.from_pretrained(
									    '''ssube/stable-diffusion-x4-upscaler-onnx'''				,				scheduler=A_				,				provider=self.gpu_provider				,				sess_options=self.gpu_options				,				)
									pipe.set_progress_bar_config(disable=A_)

									lowerCAmelCase_			:     Optional[Any]									= '''A fantasy landscape, trending on artstation'''

									lowerCAmelCase_			:     Any									= torch.manual_seed(0)
									lowerCAmelCase_			:     List[str]									= pipe(
									    prompt=A_				,				image=A_				,				guidance_scale=7.5				,				num_inference_steps=2_0				,				generator=A_				,				output_type='''np'''				,				)
									lowerCAmelCase_			:     List[Any]									= output.images
									lowerCAmelCase_			:     Tuple									= images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

									assert images.shape == (1, 5_1_2, 5_1_2, 3)
									lowerCAmelCase_			:     Optional[int]									= np.array(
									    [0.5017_3753, 0.5022_3356, 0.50_2039, 0.5023_3036, 0.502_3725, 0.502_2601, 0.501_8758, 0.5023_4085, 0.5024_1566])
									# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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










import gc
import unittest

from diffusers import FlaxStableDiffusionInpaintPipeline
from diffusers.utils import is_flax_available, load_image, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
						import jax
						import jax.numpy as jnp
						from flax.jax_utils import replicate
						from flax.training.common_utils import shard



@slow
@require_flax
class 				__snake_case						(     unittest.TestCase						):




							def    UpperCAmelCase__			(       self     :       Tuple):
									# clean up the VRAM after each test
									super().tearDown()
									gc.collect()







							def    UpperCAmelCase__			(       self     :       List[str]):
									lowerCAmelCase_			:     Any									= load_image(
									    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
									    '''/sd2-inpaint/init_image.png''')
									lowerCAmelCase_			:     str									= load_image(
									    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png''')

									lowerCAmelCase_			:     List[Any]									= '''xvjiarui/stable-diffusion-2-inpainting'''
									lowerCAmelCase_					,  lowerCAmelCase_			:     Optional[Any]									= FlaxStableDiffusionInpaintPipeline.from_pretrained(A_				,				safety_checker=A_)

									lowerCAmelCase_			:     List[str]									= '''Face of a yellow cat, high resolution, sitting on a park bench'''

									lowerCAmelCase_			:     List[Any]									= jax.random.PRNGKey(0)
									lowerCAmelCase_			:     str									= 5_0

									lowerCAmelCase_			:     List[Any]									= jax.device_count()
									lowerCAmelCase_			:     Union[str, Any]									= num_samples * [prompt]
									lowerCAmelCase_			:     str									= num_samples * [init_image]
									lowerCAmelCase_			:     Union[str, Any]									= num_samples * [mask_image]
									lowerCAmelCase_					,  lowerCAmelCase_					,  lowerCAmelCase_			:     Optional[Any]									= pipeline.prepare_inputs(A_				,				A_				,				A_)

									# shard inputs and rng
									lowerCAmelCase_			:     str									= replicate(A_)
									lowerCAmelCase_			:     str									= jax.random.split(A_				,				jax.device_count())
									lowerCAmelCase_			:     List[Any]									= shard(A_)
									lowerCAmelCase_			:     str									= shard(A_)
									lowerCAmelCase_			:     Tuple									= shard(A_)

									lowerCAmelCase_			:     int									= pipeline(
									    A_				,				A_				,				A_				,				A_				,				A_				,				A_				,				jit=A_)

									lowerCAmelCase_			:     Optional[int]									= output.images.reshape(A_				,				5_1_2				,				5_1_2				,				3)

									lowerCAmelCase_			:     List[str]									= images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

									lowerCAmelCase_			:     int									= jnp.asarray(jax.device_get(image_slice.flatten()))
									lowerCAmelCase_			:     str									= jnp.array(
									    [0.361_1307, 0.3764_9736, 0.375_7408, 0.3821_3953, 0.3929_5167, 0.384_1631, 0.4155_4978, 0.413_7475, 0.421_7084])
									print(F"""output_slice: {output_slice}""")
									assert jnp.abs(output_slice - expected_slice).max() < 1e-2





