

'''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			(  _a	,						unittest.TestCase						):



			'''simple docstring'''






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


			def lowercase__						(				self	:						List[str]		,      lowerCAmelCase_	:						Any=0			)      ->		str:





									'''simple docstring'''
									A__					:       List[Any]     =floats_tensor((1, 3, 1_28, 1_28)		,      rng=random.Random(lowerCAmelCase_			)			)
									A__					:       List[str]     =torch.manual_seed(lowerCAmelCase_			)
									A__					:       Any     ={
									    '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 lowercase__						(				self	:						Optional[Any]			)      ->		Union[str, Any]:





									'''simple docstring'''
									A__					:       Dict     =OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,      provider="""CPUExecutionProvider"""			)
									pipe.set_progress_bar_config(disable=lowerCAmelCase_			)

									A__					:       Optional[Any]     =self.get_dummy_inputs()
									A__					:       Tuple     =pipe(**lowerCAmelCase_			).images
									A__					:       Optional[Any]     =image[0, -3:, -3:, -1].flatten()

									# started as 128, should now be 512
									assert image.shape == (1, 5_12, 5_12, 3)
									A__					:       Union[str, Any]     =np.array(
									    [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]			)
									assert np.abs(image_slice - expected_slice			).max() < 1e-1


			def lowercase__						(				self	:						Any			)      ->		str:





									'''simple docstring'''
									A__					:       List[str]     =OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,      provider="""CPUExecutionProvider"""			)
									A__					:       Optional[Any]     =PNDMScheduler.from_config(pipe.scheduler.config		,      skip_prk_steps=lowerCAmelCase_			)
									pipe.set_progress_bar_config(disable=lowerCAmelCase_			)

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

									assert image.shape == (1, 5_12, 5_12, 3)
									A__					:       int     =np.array(
									    [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964]			)
									assert np.abs(image_slice.flatten() - expected_slice			).max() < 1e-1


			def lowercase__						(				self	:						Dict			)      ->		Tuple:





									'''simple docstring'''
									A__					:       Any     =OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,      provider="""CPUExecutionProvider"""			)
									A__					:       int     =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config			)
									pipe.set_progress_bar_config(disable=lowerCAmelCase_			)

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

									assert image.shape == (1, 5_12, 5_12, 3)
									A__					:       Union[str, Any]     =np.array(
									    [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515]			)

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


			def lowercase__						(				self	:						Optional[Any]			)      ->		List[Any]:





									'''simple docstring'''
									A__					:       Any     =OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,      provider="""CPUExecutionProvider"""			)
									A__					:       Any     =EulerDiscreteScheduler.from_config(pipe.scheduler.config			)
									pipe.set_progress_bar_config(disable=lowerCAmelCase_			)

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

									assert image.shape == (1, 5_12, 5_12, 3)
									A__					:       Any     =np.array(
									    [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]			)
									assert np.abs(image_slice.flatten() - expected_slice			).max() < 1e-1



			def lowercase__						(				self	:						Optional[int]			)      ->		str:





									'''simple docstring'''
									A__					:       List[Any]     =OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,      provider="""CPUExecutionProvider"""			)
									A__					:       Union[str, Any]     =EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config			)
									pipe.set_progress_bar_config(disable=lowerCAmelCase_			)

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

									assert image.shape == (1, 5_12, 5_12, 3)
									A__					:       Dict     =np.array(
									    [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043]			)

									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 lowercase__						(				self	:						Union[str, Any]			)      ->		str:





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


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





									'''simple docstring'''
									A__					:       List[str]     =ort.SessionOptions()
									A__					:       Union[str, Any]     =False
									return options


			def lowercase__						(				self	:						Optional[int]			)      ->		List[str]:





									'''simple docstring'''
									A__					:       Optional[int]     =load_image(
									    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
									    """/img2img/sketch-mountains-input.jpg"""			)
									A__					:       List[Any]     =init_image.resize((1_28, 1_28)			)
									# using the PNDM scheduler by default
									A__					:       int     =OnnxStableDiffusionUpscalePipeline.from_pretrained(
									    """ssube/stable-diffusion-x4-upscaler-onnx"""		,      provider=self.gpu_provider		,      sess_options=self.gpu_options		,      )
									pipe.set_progress_bar_config(disable=lowerCAmelCase_			)

									A__					:       Tuple     ='A fantasy landscape, trending on artstation'

									A__					:       Any     =torch.manual_seed(0			)
									A__					:       List[Any]     =pipe(
									    prompt=lowerCAmelCase_		,      image=lowerCAmelCase_		,      guidance_scale=7.5		,      num_inference_steps=10		,      generator=lowerCAmelCase_		,      output_type="""np"""		,      )
									A__					:       Tuple     =output.images
									A__					:       Optional[Any]     =images[0, 2_55:2_58, 3_83:3_86, -1]

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





									'''simple docstring'''
									A__					:       Union[str, Any]     =load_image(
									    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
									    """/img2img/sketch-mountains-input.jpg"""			)
									A__					:       List[Any]     =init_image.resize((1_28, 1_28)			)
									A__					:       Optional[Any]     =LMSDiscreteScheduler.from_pretrained(
									    """ssube/stable-diffusion-x4-upscaler-onnx"""		,      subfolder="""scheduler"""			)
									A__					:       int     =OnnxStableDiffusionUpscalePipeline.from_pretrained(
									    """ssube/stable-diffusion-x4-upscaler-onnx"""		,      scheduler=lowerCAmelCase_		,      provider=self.gpu_provider		,      sess_options=self.gpu_options		,      )
									pipe.set_progress_bar_config(disable=lowerCAmelCase_			)

									A__					:       Union[str, Any]     ='A fantasy landscape, trending on artstation'

									A__					:       int     =torch.manual_seed(0			)
									A__					:       Union[str, Any]     =pipe(
									    prompt=lowerCAmelCase_		,      image=lowerCAmelCase_		,      guidance_scale=7.5		,      num_inference_steps=20		,      generator=lowerCAmelCase_		,      output_type="""np"""		,      )
									A__					:       Tuple     =output.images
									A__					:       Tuple     =images[0, 2_55:2_58, 3_83:3_86, -1]

									assert images.shape == (1, 5_12, 5_12, 3)
									A__					:       Optional[int]     =np.array(
									    [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566]			)
									# 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 argparse import ArgumentParser

from .add_new_model import AddNewModelCommand
from .add_new_model_like import AddNewModelLikeCommand
from .convert import ConvertCommand
from .download import DownloadCommand
from .env import EnvironmentCommand
from .lfs import LfsCommands
from .pt_to_tf import PTtoTFCommand
from .run import RunCommand
from .serving import ServeCommand
from .user import UserCommands
def 						__lowerCamelCase	(       )	->							List[Any]:






						"""simple docstring"""





						A__					:       List[Any]     =ArgumentParser("""Transformers CLI tool""",		usage="""transformers-cli <command> [<args>]"""	)
						A__					:       List[Any]     =parser.add_subparsers(help="""transformers-cli command helpers"""	)

						# Register commands
						ConvertCommand.register_subcommand(__snake_case	)
						DownloadCommand.register_subcommand(__snake_case	)
						EnvironmentCommand.register_subcommand(__snake_case	)
						RunCommand.register_subcommand(__snake_case	)
						ServeCommand.register_subcommand(__snake_case	)
						UserCommands.register_subcommand(__snake_case	)
						AddNewModelCommand.register_subcommand(__snake_case	)
						AddNewModelLikeCommand.register_subcommand(__snake_case	)
						LfsCommands.register_subcommand(__snake_case	)
						PTtoTFCommand.register_subcommand(__snake_case	)

						# Let's go
						A__					:       List[str]     =parser.parse_args()

						if not hasattr(__snake_case,		"""func"""	):
												parser.print_help()
												exit(1	)

						# Run
						A__					:       Optional[Any]     =args.func(__snake_case	)
						service.run()


if __name__ == "__main__":
		main()

