
"""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    _UpperCAmelCase(   lowerCamelCase				,					unittest.TestCase     ):
		# TODO: is there an appropriate internal test set?
		lowercase__      =				'ssube/stable-diffusion-x4-upscaler-onnx'



		def 						UpperCAmelCase							( self    ,		__a=0)	->	Any:






							'''simple docstring'''
							_UpperCamelCase										=  floats_tensor((1, 3, 1_28, 1_28)    ,		rng=random.Random(__a))
							_UpperCamelCase										=  torch.manual_seed(__a)
							_UpperCamelCase										=  {
							    '''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)	->	Tuple:






							'''simple docstring'''
							_UpperCamelCase										=  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint    ,		provider='''CPUExecutionProvider''')
							pipe.set_progress_bar_config(disable=__a)

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

							# started as 128, should now be 512
							assert image.shape == (1, 5_12, 5_12, 3)
							_UpperCamelCase										=  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)	->	Any:






							'''simple docstring'''
							_UpperCamelCase										=  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint    ,		provider='''CPUExecutionProvider''')
							_UpperCamelCase										=  PNDMScheduler.from_config(pipe.scheduler.config    ,		skip_prk_steps=__a)
							pipe.set_progress_bar_config(disable=__a)

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

							assert image.shape == (1, 5_12, 5_12, 3)
							_UpperCamelCase										=  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)	->	Optional[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint    ,		provider='''CPUExecutionProvider''')
							_UpperCamelCase										=  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
							pipe.set_progress_bar_config(disable=__a)

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

							assert image.shape == (1, 5_12, 5_12, 3)
							_UpperCamelCase										=  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)	->	Any:






							'''simple docstring'''
							_UpperCamelCase										=  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint    ,		provider='''CPUExecutionProvider''')
							_UpperCamelCase										=  EulerDiscreteScheduler.from_config(pipe.scheduler.config)
							pipe.set_progress_bar_config(disable=__a)

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

							assert image.shape == (1, 5_12, 5_12, 3)
							_UpperCamelCase										=  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[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint    ,		provider='''CPUExecutionProvider''')
							_UpperCamelCase										=  EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
							pipe.set_progress_bar_config(disable=__a)

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

							assert image.shape == (1, 5_12, 5_12, 3)
							_UpperCamelCase										=  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    _UpperCAmelCase(   unittest.TestCase     ):



		@property
		def 						UpperCAmelCase							( self)	->	List[Any]:






							'''simple docstring'''
							return (
							    "CUDAExecutionProvider",
							    {
							        "gpu_mem_limit": "15000000000",  # 15GB
							        "arena_extend_strategy": "kSameAsRequested",
							    },
							)



		@property
		def 						UpperCAmelCase							( self)	->	int:






							'''simple docstring'''
							_UpperCamelCase										=  ort.SessionOptions()
							_UpperCamelCase										=  False
							return options



		def 						UpperCAmelCase							( self)	->	Dict:






							'''simple docstring'''
							_UpperCamelCase										=  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/img2img/sketch-mountains-input.jpg''')
							_UpperCamelCase										=  init_image.resize((1_28, 1_28))
							# using the PNDM scheduler by default
							_UpperCamelCase										=  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)

							_UpperCamelCase										=  '''A fantasy landscape, trending on artstation'''

							_UpperCamelCase										=  torch.manual_seed(0)
							_UpperCamelCase										=  pipe(
							    prompt=__a    ,		image=__a    ,		guidance_scale=7.5    ,		num_inference_steps=10    ,		generator=__a    ,		output_type='''np'''    ,		)
							_UpperCamelCase										=  output.images
							_UpperCamelCase										=  images[0, 2_55:2_58, 3_83:3_86, -1]

							assert images.shape == (1, 5_12, 5_12, 3)
							_UpperCamelCase										=  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)	->	Union[str, Any]:






							'''simple docstring'''
							_UpperCamelCase										=  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/img2img/sketch-mountains-input.jpg''')
							_UpperCamelCase										=  init_image.resize((1_28, 1_28))
							_UpperCamelCase										=  LMSDiscreteScheduler.from_pretrained(
							    '''ssube/stable-diffusion-x4-upscaler-onnx'''    ,		subfolder='''scheduler''')
							_UpperCamelCase										=  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)

							_UpperCamelCase										=  '''A fantasy landscape, trending on artstation'''

							_UpperCamelCase										=  torch.manual_seed(0)
							_UpperCamelCase										=  pipe(
							    prompt=__a    ,		image=__a    ,		guidance_scale=7.5    ,		num_inference_steps=20    ,		generator=__a    ,		output_type='''np'''    ,		)
							_UpperCamelCase										=  output.images
							_UpperCamelCase										=  images[0, 2_55:2_58, 3_83:3_86, -1]

							assert images.shape == (1, 5_12, 5_12, 3)
							_UpperCamelCase										=  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"""





class    _UpperCAmelCase:



		def __init__( self    ,		__a    ,		__a    ,		__a)	->	List[Any]:






							'''simple docstring'''
							_UpperCamelCase										=  name
							_UpperCamelCase										=  value
							_UpperCamelCase										=  weight



		def __repr__( self)	->	List[str]:






							'''simple docstring'''
							return F'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})'''



		def 						UpperCAmelCase							( self)	->	Tuple:






							'''simple docstring'''
							return self.value



		def 						UpperCAmelCase							( self)	->	Union[str, Any]:






							'''simple docstring'''
							return self.name



		def 						UpperCAmelCase							( self)	->	int:






							'''simple docstring'''
							return self.weight




		def 						UpperCAmelCase							( self)	->	Any:






							'''simple docstring'''
							return self.value / self.weight





def 				lowerCamelCase__		(      __snake_case,					__snake_case,					__snake_case     )							->		Optional[Any]:


					"""simple docstring"""





					_UpperCamelCase										=  []
					for i in range(len(__snake_case     )     ):
										menu.append(Things(name[i],					value[i],					weight[i]     )     )
					return menu



def 				lowerCamelCase__		(      __snake_case,					__snake_case,					__snake_case     )							->		List[str]:


					"""simple docstring"""





					_UpperCamelCase										=  sorted(__snake_case,					key=__snake_case,					reverse=__snake_case     )
					_UpperCamelCase										=  []
					_UpperCamelCase			,  _UpperCamelCase										=  0.0, 0.0
					for i in range(len(__snake_case     )     ):
										if (total_cost + items_copy[i].get_weight()) <= max_cost:
															result.append(items_copy[i]     )
															total_cost += items_copy[i].get_weight()
															total_value += items_copy[i].get_value()
					return (result, total_value)



def 				lowerCamelCase__		(      )							->		List[str]:


					"""simple docstring"""







if __name__ == "__main__":
				import doctest

				doctest.testmod()






