"""simple docstring"""






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 lowerCamelCase		(_snake_case    ,    unittest.TestCase      ):






					'''simple docstring'''


					a   	=		"""ssube/stable-diffusion-x4-upscaler-onnx"""



					def 			lowerCAmelCase_					(						self			:				int   , _snake_case			:				Any=0		)							->       List[str]:
									SCREAMING_SNAKE_CASE__		  =				floats_tensor((1, 3, 128, 128)   , rng=random.Random(snake_case_		)		)
									SCREAMING_SNAKE_CASE__		  =				torch.manual_seed(snake_case_		)
									SCREAMING_SNAKE_CASE__		  =				{
									    "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 			lowerCAmelCase_					(						self			:				List[Any]		)							->       Tuple:
									SCREAMING_SNAKE_CASE__		  =				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint   , provider="CPUExecutionProvider"		)
									pipe.set_progress_bar_config(disable=snake_case_		)

									SCREAMING_SNAKE_CASE__		  =				self.get_dummy_inputs()
									SCREAMING_SNAKE_CASE__		  =				pipe(**snake_case_		).images
									SCREAMING_SNAKE_CASE__		  =				image[0, -3:, -3:, -1].flatten()

									# started as 128, should now be 512
									assert image.shape == (1, 512, 512, 3)
									SCREAMING_SNAKE_CASE__		  =				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 			lowerCAmelCase_					(						self			:				Optional[Any]		)							->       List[Any]:
									SCREAMING_SNAKE_CASE__		  =				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint   , provider="CPUExecutionProvider"		)
									SCREAMING_SNAKE_CASE__		  =				PNDMScheduler.from_config(pipe.scheduler.config   , skip_prk_steps=snake_case_		)
									pipe.set_progress_bar_config(disable=snake_case_		)

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

									assert image.shape == (1, 512, 512, 3)
									SCREAMING_SNAKE_CASE__		  =				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 			lowerCAmelCase_					(						self			:				Optional[Any]		)							->       List[str]:
									SCREAMING_SNAKE_CASE__		  =				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint   , provider="CPUExecutionProvider"		)
									SCREAMING_SNAKE_CASE__		  =				DPMSolverMultistepScheduler.from_config(pipe.scheduler.config		)
									pipe.set_progress_bar_config(disable=snake_case_		)

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

									assert image.shape == (1, 512, 512, 3)
									SCREAMING_SNAKE_CASE__		  =				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 			lowerCAmelCase_					(						self			:				Optional[Any]		)							->       Any:
									SCREAMING_SNAKE_CASE__		  =				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint   , provider="CPUExecutionProvider"		)
									SCREAMING_SNAKE_CASE__		  =				EulerDiscreteScheduler.from_config(pipe.scheduler.config		)
									pipe.set_progress_bar_config(disable=snake_case_		)

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

									assert image.shape == (1, 512, 512, 3)
									SCREAMING_SNAKE_CASE__		  =				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 			lowerCAmelCase_					(						self			:				List[str]		)							->       List[str]:
									SCREAMING_SNAKE_CASE__		  =				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint   , provider="CPUExecutionProvider"		)
									SCREAMING_SNAKE_CASE__		  =				EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config		)
									pipe.set_progress_bar_config(disable=snake_case_		)

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

									assert image.shape == (1, 512, 512, 3)
									SCREAMING_SNAKE_CASE__		  =				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 lowerCamelCase		(unittest.TestCase      ):






					'''simple docstring'''


					@property
					def 			lowerCAmelCase_					(						self			:				int		)							->       Tuple:
									return (
									    "CUDAExecutionProvider",
									    {
									        "gpu_mem_limit": "15000000000",  # 15GB
									        "arena_extend_strategy": "kSameAsRequested",
									    },
									)



					@property
					def 			lowerCAmelCase_					(						self			:				int		)							->       Any:
									SCREAMING_SNAKE_CASE__		  =				ort.SessionOptions()
									SCREAMING_SNAKE_CASE__		  =				False
									return options



					def 			lowerCAmelCase_					(						self			:				str		)							->       int:
									SCREAMING_SNAKE_CASE__		  =				load_image(
									    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
									    "/img2img/sketch-mountains-input.jpg"		)
									SCREAMING_SNAKE_CASE__		  =				init_image.resize((128, 128)		)
									# using the PNDM scheduler by default
									SCREAMING_SNAKE_CASE__		  =				OnnxStableDiffusionUpscalePipeline.from_pretrained(
									    "ssube/stable-diffusion-x4-upscaler-onnx"   , provider=self.gpu_provider   , sess_options=self.gpu_options   , )
									pipe.set_progress_bar_config(disable=snake_case_		)

									SCREAMING_SNAKE_CASE__		  =				"A fantasy landscape, trending on artstation"

									SCREAMING_SNAKE_CASE__		  =				torch.manual_seed(0		)
									SCREAMING_SNAKE_CASE__		  =				pipe(
									    prompt=snake_case_   , image=snake_case_   , guidance_scale=7.5   , num_inference_steps=10   , generator=snake_case_   , output_type="np"   , )
									SCREAMING_SNAKE_CASE__		  =				output.images
									SCREAMING_SNAKE_CASE__		  =				images[0, 255:258, 383:386, -1]

									assert images.shape == (1, 512, 512, 3)
									SCREAMING_SNAKE_CASE__		  =				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 			lowerCAmelCase_					(						self			:				Tuple		)							->       Any:
									SCREAMING_SNAKE_CASE__		  =				load_image(
									    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
									    "/img2img/sketch-mountains-input.jpg"		)
									SCREAMING_SNAKE_CASE__		  =				init_image.resize((128, 128)		)
									SCREAMING_SNAKE_CASE__		  =				LMSDiscreteScheduler.from_pretrained(
									    "ssube/stable-diffusion-x4-upscaler-onnx"   , subfolder="scheduler"		)
									SCREAMING_SNAKE_CASE__		  =				OnnxStableDiffusionUpscalePipeline.from_pretrained(
									    "ssube/stable-diffusion-x4-upscaler-onnx"   , scheduler=snake_case_   , provider=self.gpu_provider   , sess_options=self.gpu_options   , )
									pipe.set_progress_bar_config(disable=snake_case_		)

									SCREAMING_SNAKE_CASE__		  =				"A fantasy landscape, trending on artstation"

									SCREAMING_SNAKE_CASE__		  =				torch.manual_seed(0		)
									SCREAMING_SNAKE_CASE__		  =				pipe(
									    prompt=snake_case_   , image=snake_case_   , guidance_scale=7.5   , num_inference_steps=20   , generator=snake_case_   , output_type="np"   , )
									SCREAMING_SNAKE_CASE__		  =				output.images
									SCREAMING_SNAKE_CASE__		  =				images[0, 255:258, 383:386, -1]

									assert images.shape == (1, 512, 512, 3)
									SCREAMING_SNAKE_CASE__		  =				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





"""simple docstring"""






from typing import List, Optional, Tuple, Union

import torch

from ...schedulers import DDIMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput

class lowerCamelCase		(_SCREAMING_SNAKE_CASE      ):






					'''simple docstring'''


					def __init__(						self			:				int   , _snake_case			:				Optional[int]   , _snake_case			:				Dict		)							->       Dict:
									super().__init__()

									# make sure scheduler can always be converted to DDIM
									SCREAMING_SNAKE_CASE__		  =				DDIMScheduler.from_config(scheduler.config		)

									self.register_modules(unet=_snake_case   , scheduler=_snake_case		)



					@torch.no_grad()
					def __call__(						self			:				int   , _snake_case			:				int = 1   , _snake_case			:				Optional[Union[torch.Generator, List[torch.Generator]]] = None   , _snake_case			:				float = 0.0   , _snake_case			:				int = 50   , _snake_case			:				Optional[bool] = None   , _snake_case			:				Optional[str] = "pil"   , _snake_case			:				bool = True   , )							->       Union[ImagePipelineOutput, Tuple]:

									# Sample gaussian noise to begin loop
									if isinstance(self.unet.config.sample_size   , _snake_case		):
													SCREAMING_SNAKE_CASE__		  =				(
													    batch_size,
													    self.unet.config.in_channels,
													    self.unet.config.sample_size,
													    self.unet.config.sample_size,
													)
									else:
													SCREAMING_SNAKE_CASE__		  =				(batch_size, self.unet.config.in_channels, *self.unet.config.sample_size)

									if isinstance(_snake_case   , _snake_case		) and len(_snake_case		) != batch_size:
													raise ValueError(
													    F"""You have passed a list of generators of length {len(_snake_case		)}, but requested an effective batch"""
													    F""" size of {batch_size}. Make sure the batch size matches the length of the generators."""		)

									SCREAMING_SNAKE_CASE__		  =				randn_tensor(_snake_case   , generator=_snake_case   , device=self.device   , dtype=self.unet.dtype		)

									# set step values
									self.scheduler.set_timesteps(_snake_case		)

									for t in self.progress_bar(self.scheduler.timesteps		):
													# 1. predict noise model_output
													SCREAMING_SNAKE_CASE__		  =				self.unet(_snake_case   , _snake_case		).sample

													# 2. predict previous mean of image x_t-1 and add variance depending on eta
													# eta corresponds to η in paper and should be between [0, 1]
													# do x_t -> x_t-1
													SCREAMING_SNAKE_CASE__		  =				self.scheduler.step(
													    _snake_case   , _snake_case   , _snake_case   , eta=_snake_case   , use_clipped_model_output=_snake_case   , generator=_snake_case		).prev_sample

									SCREAMING_SNAKE_CASE__		  =				(image / 2 + 0.5).clamp(0   , 1		)
									SCREAMING_SNAKE_CASE__		  =				image.cpu().permute(0   , 2   , 3   , 1		).numpy()
									if output_type == "pil":
													SCREAMING_SNAKE_CASE__		  =				self.numpy_to_pil(_snake_case		)

									if not return_dict:
													return (image,)

									return ImagePipelineOutput(images=_snake_case		)




