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



	def 			__A							(       self			,	UpperCAmelCase__=0		):
							A__							=       floats_tensor((1, 3, 128, 128)			,	rng=random.Random(__a		)		)
							A__							=       torch.manual_seed(__a		)
							A__							=       {
							    "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 			__A							(       self		):
							A__							=       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint			,	provider="CPUExecutionProvider"		)
							pipe.set_progress_bar_config(disable=__a		)

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

							# started as 128, should now be 512
							assert image.shape == (1, 512, 512, 3)
							A__							=       np.array(
							    [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223]		)
							assert np.abs(image_slice - expected_slice		).max() < 1e-1



	def 			__A							(       self		):
							A__							=       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint			,	provider="CPUExecutionProvider"		)
							A__							=       PNDMScheduler.from_config(pipe.scheduler.config			,	skip_prk_steps=__a		)
							pipe.set_progress_bar_config(disable=__a		)

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

							assert image.shape == (1, 512, 512, 3)
							A__							=       np.array(
							    [0.6_898_892, 0.59_240_556, 0.52_499_527, 0.58_866_215, 0.52_258_235, 0.52_572_715, 0.62_414_473, 0.6_174_387, 0.6_214_964]		)
							assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-1



	def 			__A							(       self		):
							A__							=       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint			,	provider="CPUExecutionProvider"		)
							A__							=       DPMSolverMultistepScheduler.from_config(pipe.scheduler.config		)
							pipe.set_progress_bar_config(disable=__a		)

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

							assert image.shape == (1, 512, 512, 3)
							A__							=       np.array(
							    [0.7_659_278, 0.76_437_664, 0.75_579_107, 0.7_691_116, 0.77_666_986, 0.7_727_672, 0.7_758_664, 0.7_812_226, 0.76_942_515]		)

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



	def 			__A							(       self		):
							A__							=       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint			,	provider="CPUExecutionProvider"		)
							A__							=       EulerDiscreteScheduler.from_config(pipe.scheduler.config		)
							pipe.set_progress_bar_config(disable=__a		)

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

							assert image.shape == (1, 512, 512, 3)
							A__							=       np.array(
							    [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223]		)
							assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-1



	def 			__A							(       self		):
							A__							=       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint			,	provider="CPUExecutionProvider"		)
							A__							=       EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config		)
							pipe.set_progress_bar_config(disable=__a		)

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

							assert image.shape == (1, 512, 512, 3)
							A__							=       np.array(
							    [0.77_424_496, 0.773_601, 0.7_645_288, 0.7_769_598, 0.7_772_739, 0.7_738_688, 0.78_187_233, 0.77_879_584, 0.767_043]		)

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






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



	@property
	def 			__A							(       self		):
							return (
							    "CUDAExecutionProvider",
							    {
							        "gpu_mem_limit": "15000000000",  # 15GB
							        "arena_extend_strategy": "kSameAsRequested",
							    },
							)



	@property
	def 			__A							(       self		):
							A__							=       ort.SessionOptions()
							A__							=       False
							return options



	def 			__A							(       self		):
							A__							=       load_image(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
							    "/img2img/sketch-mountains-input.jpg"		)
							A__							=       init_image.resize((128, 128)		)
							# using the PNDM scheduler by default
							A__							=       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		)

							A__							=       "A fantasy landscape, trending on artstation"

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

							assert images.shape == (1, 512, 512, 3)
							A__							=       np.array([0.4_883, 0.4_947, 0.4_980, 0.4_975, 0.4_982, 0.4_980, 0.5_000, 0.5_006, 0.4_972]		)
							# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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



	def 			__A							(       self		):
							A__							=       load_image(
							    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
							    "/img2img/sketch-mountains-input.jpg"		)
							A__							=       init_image.resize((128, 128)		)
							A__							=       LMSDiscreteScheduler.from_pretrained(
							    "ssube/stable-diffusion-x4-upscaler-onnx"			,	subfolder="scheduler"		)
							A__							=       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		)

							A__							=       "A fantasy landscape, trending on artstation"

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

							assert images.shape == (1, 512, 512, 3)
							A__							=       np.array(
							    [0.50_173_753, 0.50_223_356, 0.502_039, 0.50_233_036, 0.5_023_725, 0.5_022_601, 0.5_018_758, 0.50_234_085, 0.50_241_566]		)
							# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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










from manim import *






class      UpperCamelCase    (						_UpperCAmelCase     ):



	def 			__A							(       self		):
							A__							=       Rectangle(height=0.5			,	width=0.5		)
							A__							=       Rectangle(height=0.46			,	width=0.46		).set_stroke(width=0		)

							A__							=       [mem.copy() for i in range(6		)]
							A__							=       [mem.copy() for i in range(6		)]
							A__							=       VGroup(*UpperCAmelCase__		).arrange(UpperCAmelCase__			,	buff=0		)
							A__							=       VGroup(*UpperCAmelCase__		).arrange(UpperCAmelCase__			,	buff=0		)
							A__							=       VGroup(UpperCAmelCase__			,	UpperCAmelCase__		).arrange(UpperCAmelCase__			,	buff=0		)
							A__							=       Text("CPU"			,	font_size=24		)
							A__							=       Group(UpperCAmelCase__			,	UpperCAmelCase__		).arrange(UpperCAmelCase__			,	buff=0.5			,	aligned_edge=UpperCAmelCase__		)
							cpu.move_to([-2.5, -0.5, 0]		)
							self.add(UpperCAmelCase__		)

							A__							=       [mem.copy() for i in range(4		)]
							A__							=       VGroup(*UpperCAmelCase__		).arrange(UpperCAmelCase__			,	buff=0		)
							A__							=       Text("GPU"			,	font_size=24		)
							A__							=       Group(UpperCAmelCase__			,	UpperCAmelCase__		).arrange(UpperCAmelCase__			,	buff=0.5			,	aligned_edge=UpperCAmelCase__		)
							gpu.move_to([-1, -1, 0]		)
							self.add(UpperCAmelCase__		)

							A__							=       [mem.copy() for i in range(6		)]
							A__							=       VGroup(*UpperCAmelCase__		).arrange(UpperCAmelCase__			,	buff=0		)

							A__							=       Text("Model"			,	font_size=24		)
							A__							=       Group(UpperCAmelCase__			,	UpperCAmelCase__		).arrange(UpperCAmelCase__			,	buff=0.5			,	aligned_edge=UpperCAmelCase__		)
							model.move_to([3, -1.0, 0]		)
							self.add(UpperCAmelCase__		)

							A__							=       []
							for i, rect in enumerate(UpperCAmelCase__		):
													rect.set_stroke(UpperCAmelCase__		)
													# target = fill.copy().set_fill(YELLOW, opacity=0.7)
													# target.move_to(rect)
													# self.add(target)

													A__							=       Rectangle(height=0.46 / 4			,	width=0.46 / 3		).set_stroke(width=0.0		).set_fill(UpperCAmelCase__			,	opacity=0.7		)

													if i == 0:
																			cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT		)			,	buff=0.02			,	direction=UpperCAmelCase__		)
																			cpu_target.set_x(cpu_target.get_x() + 0.1		)
													elif i == 3:
																			cpu_target.next_to(cpu_targs[0]			,	direction=UpperCAmelCase__			,	buff=0.0		)
													else:
																			cpu_target.next_to(cpu_targs[i - 1]			,	direction=UpperCAmelCase__			,	buff=0.0		)
													self.add(UpperCAmelCase__		)
													cpu_targs.append(UpperCAmelCase__		)

							A__							=       [mem.copy() for i in range(6		)]
							A__							=       VGroup(*UpperCAmelCase__		).arrange(UpperCAmelCase__			,	buff=0		)

							A__							=       Text("Loaded Checkpoint"			,	font_size=24		)
							A__							=       Group(UpperCAmelCase__			,	UpperCAmelCase__		).arrange(UpperCAmelCase__			,	aligned_edge=UpperCAmelCase__			,	buff=0.4		)
							checkpoint.move_to([3, 0.5, 0]		)

							A__							=       Square(side_length=2.2		)
							key.move_to([-5, 2, 0]		)

							A__							=       MarkupText(
							    F"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model"""			,	font_size=18			,	)

							key_text.move_to([-5, 2.4, 0]		)

							self.add(UpperCAmelCase__			,	UpperCAmelCase__		)

							A__							=       MarkupText(
							    F"""<span fgcolor='{BLUE}'>●</span> Checkpoint"""			,	font_size=18			,	)

							blue_text.next_to(UpperCAmelCase__			,	DOWN * 2.4			,	aligned_edge=key_text.get_left()		)

							A__							=       MarkupText(
							    F"""Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>."""			,	font_size=24			,	)
							step_a.move_to([2, 2, 0]		)
							self.play(Write(UpperCAmelCase__		)			,	Write(UpperCAmelCase__		)		)

							self.play(Write(UpperCAmelCase__			,	run_time=1		)			,	Create(UpperCAmelCase__			,	run_time=1		)		)

							A__							=       []
							A__							=       []
							for i, rect in enumerate(UpperCAmelCase__		):
													A__							=       fill.copy().set_fill(UpperCAmelCase__			,	opacity=0.7		)
													target.move_to(UpperCAmelCase__		)
													first_animations.append(GrowFromCenter(UpperCAmelCase__			,	run_time=1		)		)

													A__							=       target.copy()
													cpu_target.generate_target()
													if i < 5:
																			cpu_target.target.move_to(cpu_left_col_base[i + 1]		)
													else:
																			cpu_target.target.move_to(cpu_right_col_base[i - 5]		)
													second_animations.append(MoveToTarget(UpperCAmelCase__			,	run_time=1.5		)		)

							self.play(*UpperCAmelCase__		)
							self.play(*UpperCAmelCase__		)
							self.wait()





