


"""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	(					lowerCamelCase_	,    unittest.TestCase    ):




		'''simple docstring'''







		SCREAMING_SNAKE_CASE_						:     Any								=     """ssube/stable-diffusion-x4-upscaler-onnx"""







		def 							__A						(	self						,       lowerCAmelCase__=0				)     ->							Dict:
								SCREAMING_SNAKE_CASE													=					floats_tensor((1, 3, 128, 128)						,       rng=random.Random(lowerCAmelCase__				)				)
								SCREAMING_SNAKE_CASE													=					torch.manual_seed(lowerCAmelCase__				)
								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 							__A						(	self				)     ->							List[str]:
								SCREAMING_SNAKE_CASE													=					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,       provider='CPUExecutionProvider'				)
								pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					self.get_dummy_inputs()
								SCREAMING_SNAKE_CASE													=					pipe(**lowerCAmelCase__				).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.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]				)
								assert np.abs(image_slice - expected_slice				).max() < 1e-1







		def 							__A						(	self				)     ->							int:
								SCREAMING_SNAKE_CASE													=					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint						,       provider='CPUExecutionProvider'				)
								SCREAMING_SNAKE_CASE													=					PNDMScheduler.from_config(pipe.scheduler.config						,       skip_prk_steps=lowerCAmelCase__				)
								pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

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

								assert image.shape == (1, 512, 512, 3)
								SCREAMING_SNAKE_CASE													=					np.array(
								    [0.6_89_88_92, 0.59_24_05_56, 0.52_49_95_27, 0.58_86_62_15, 0.52_25_82_35, 0.52_57_27_15, 0.62_41_44_73, 0.6_17_43_87, 0.6_21_49_64]				)
								assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-1







		def 							__A						(	self				)     ->							Optional[int]:
								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=lowerCAmelCase__				)

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

								assert image.shape == (1, 512, 512, 3)
								SCREAMING_SNAKE_CASE													=					np.array(
								    [0.7_65_92_78, 0.76_43_76_64, 0.75_57_91_07, 0.7_69_11_16, 0.77_66_69_86, 0.7_72_76_72, 0.7_75_86_64, 0.7_81_22_26, 0.76_94_25_15]				)

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







		def 							__A						(	self				)     ->							int:
								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=lowerCAmelCase__				)

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

								assert image.shape == (1, 512, 512, 3)
								SCREAMING_SNAKE_CASE													=					np.array(
								    [0.6_97_47_82, 0.68_90_20_93, 0.70_13_58_85, 0.7_58_36_18, 0.7_80_45_45, 0.7_85_49_12, 0.78_66_74_26, 0.78_74_38_63, 0.78_07_02_23]				)
								assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-1







		def 							__A						(	self				)     ->							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=lowerCAmelCase__				)

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

								assert image.shape == (1, 512, 512, 3)
								SCREAMING_SNAKE_CASE													=					np.array(
								    [0.77_42_44_96, 0.77_36_01, 0.7_64_52_88, 0.7_76_95_98, 0.7_77_27_39, 0.7_73_86_88, 0.78_18_72_33, 0.77_87_95_84, 0.76_70_43]				)

								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 							__A						(	self				)     ->							int:
								return (
								    "CUDAExecutionProvider",
								    {
								        "gpu_mem_limit": "15000000000",  # 15GB
								        "arena_extend_strategy": "kSameAsRequested",
								    },
								)







		@property
		def 							__A						(	self				)     ->							List[Any]:
								SCREAMING_SNAKE_CASE													=					ort.SessionOptions()
								SCREAMING_SNAKE_CASE													=					False
								return options







		def 							__A						(	self				)     ->							List[str]:
								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=lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					'A fantasy landscape, trending on artstation'

								SCREAMING_SNAKE_CASE													=					torch.manual_seed(0				)
								SCREAMING_SNAKE_CASE													=					pipe(
								    prompt=lowerCAmelCase__						,       image=lowerCAmelCase__						,       guidance_scale=7.5						,       num_inference_steps=10						,       generator=lowerCAmelCase__						,       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.48_83, 0.49_47, 0.49_80, 0.49_75, 0.49_82, 0.49_80, 0.50_00, 0.50_06, 0.49_72]				)
								# 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				)     ->							Dict:
								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=lowerCAmelCase__						,       provider=self.gpu_provider						,       sess_options=self.gpu_options						,       )
								pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

								SCREAMING_SNAKE_CASE													=					'A fantasy landscape, trending on artstation'

								SCREAMING_SNAKE_CASE													=					torch.manual_seed(0				)
								SCREAMING_SNAKE_CASE													=					pipe(
								    prompt=lowerCAmelCase__						,       image=lowerCAmelCase__						,       guidance_scale=7.5						,       num_inference_steps=20						,       generator=lowerCAmelCase__						,       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.50_17_37_53, 0.50_22_33_56, 0.50_20_39, 0.50_23_30_36, 0.5_02_37_25, 0.5_02_26_01, 0.5_01_87_58, 0.50_23_40_85, 0.50_24_15_66]				)
								# 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"""




import json
import os
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
	import torch

if is_vision_available():
	from PIL import Image

	from transformers import ImageGPTImageProcessor
class 					lowerCAmelCase	(					unittest.TestCase    ):




		'''simple docstring'''







		def __init__(	self						,       lowerCAmelCase__						,       lowerCAmelCase__=7						,       lowerCAmelCase__=3						,       lowerCAmelCase__=18						,       lowerCAmelCase__=30						,       lowerCAmelCase__=400						,       lowerCAmelCase__=True						,       lowerCAmelCase__=None						,       lowerCAmelCase__=True						,       )     ->							int:
								SCREAMING_SNAKE_CASE													=					size if size is not None else {'height': 18, 'width': 18}
								SCREAMING_SNAKE_CASE													=					parent
								SCREAMING_SNAKE_CASE													=					batch_size
								SCREAMING_SNAKE_CASE													=					num_channels
								SCREAMING_SNAKE_CASE													=					image_size
								SCREAMING_SNAKE_CASE													=					min_resolution
								SCREAMING_SNAKE_CASE													=					max_resolution
								SCREAMING_SNAKE_CASE													=					do_resize
								SCREAMING_SNAKE_CASE													=					size
								SCREAMING_SNAKE_CASE													=					do_normalize







		def 							__A						(	self				)     ->							Optional[Any]:
								return {
								    # here we create 2 clusters for the sake of simplicity
								    "clusters": np.asarray(
								        [
								            [0.88_66_44_36_34_03_32_03, 0.66_18_82_93_69_54_49_83, 0.38_91_74_64_01_78_68_04],
								            [-0.60_42_55_91_46_88_11_04, -0.0_22_95_00_88_60_52_84_69, 0.54_23_79_73_69_00_32_96],
								        ]				),
								    "do_resize": self.do_resize,
								    "size": self.size,
								    "do_normalize": self.do_normalize,
								}





@require_torch
@require_vision
class 					lowerCAmelCase	(					lowerCamelCase_	,    unittest.TestCase    ):




		'''simple docstring'''







		SCREAMING_SNAKE_CASE_						:     Union[str, Any]								=     ImageGPTImageProcessor if is_vision_available() else None







		def 							__A						(	self				)     ->							Optional[int]:
								SCREAMING_SNAKE_CASE													=					ImageGPTImageProcessingTester(self				)







		@property
		def 							__A						(	self				)     ->							Any:
								return self.image_processor_tester.prepare_image_processor_dict()







		def 							__A						(	self				)     ->							List[Any]:
								SCREAMING_SNAKE_CASE													=					self.image_processing_class(**self.image_processor_dict				)
								self.assertTrue(hasattr(lowerCAmelCase__						,       'clusters'				)				)
								self.assertTrue(hasattr(lowerCAmelCase__						,       'do_resize'				)				)
								self.assertTrue(hasattr(lowerCAmelCase__						,       'size'				)				)
								self.assertTrue(hasattr(lowerCAmelCase__						,       'do_normalize'				)				)







		def 							__A						(	self				)     ->							Tuple:
								SCREAMING_SNAKE_CASE													=					self.image_processing_class.from_dict(self.image_processor_dict				)
								self.assertEqual(image_processor.size						,       {'height': 18, 'width': 18}				)

								SCREAMING_SNAKE_CASE													=					self.image_processing_class.from_dict(self.image_processor_dict						,       size=42				)
								self.assertEqual(image_processor.size						,       {'height': 42, 'width': 42}				)







		def 							__A						(	self				)     ->							List[Any]:
								SCREAMING_SNAKE_CASE													=					self.image_processing_class(**self.image_processor_dict				)
								SCREAMING_SNAKE_CASE													=					json.loads(image_processor.to_json_string()				)
								for key, value in self.image_processor_dict.items():
														if key == "clusters":
																				self.assertTrue(np.array_equal(lowerCAmelCase__						,       obj[key]				)				)
														else:
																				self.assertEqual(obj[key]						,       lowerCAmelCase__				)







		def 							__A						(	self				)     ->							List[str]:
								SCREAMING_SNAKE_CASE													=					self.image_processing_class(**self.image_processor_dict				)

								with tempfile.TemporaryDirectory() as tmpdirname:
														SCREAMING_SNAKE_CASE													=					os.path.join(lowerCAmelCase__						,       'image_processor.json'				)
														image_processor_first.to_json_file(lowerCAmelCase__				)
														SCREAMING_SNAKE_CASE													=					self.image_processing_class.from_json_file(lowerCAmelCase__				).to_dict()

								SCREAMING_SNAKE_CASE													=					image_processor_first.to_dict()
								for key, value in image_processor_first.items():
														if key == "clusters":
																				self.assertTrue(np.array_equal(lowerCAmelCase__						,       image_processor_second[key]				)				)
														else:
																				self.assertEqual(image_processor_first[key]						,       lowerCAmelCase__				)







		def 							__A						(	self				)     ->							Optional[Any]:
								SCREAMING_SNAKE_CASE													=					self.image_processing_class(**self.image_processor_dict				)

								with tempfile.TemporaryDirectory() as tmpdirname:
														image_processor_first.save_pretrained(lowerCAmelCase__				)
														SCREAMING_SNAKE_CASE													=					self.image_processing_class.from_pretrained(lowerCAmelCase__				).to_dict()

								SCREAMING_SNAKE_CASE													=					image_processor_first.to_dict()
								for key, value in image_processor_first.items():
														if key == "clusters":
																				self.assertTrue(np.array_equal(lowerCAmelCase__						,       image_processor_second[key]				)				)
														else:
																				self.assertEqual(image_processor_first[key]						,       lowerCAmelCase__				)







		@unittest.skip('ImageGPT requires clusters at initialization'				)
		def 							__A						(	self				)     ->							Optional[Any]:
								pass





def     lowercase			()   ->						Union[str, Any]:
						SCREAMING_SNAKE_CASE													=					load_dataset('hf-internal-testing/fixtures_image_utils' ,			split='test'  )

						SCREAMING_SNAKE_CASE													=					Image.open(dataset[4]['file']  )
						SCREAMING_SNAKE_CASE													=					Image.open(dataset[5]['file']  )

						SCREAMING_SNAKE_CASE													=					[imagea, imagea]

						return images


@require_vision
@require_torch
class 					lowerCAmelCase	(					unittest.TestCase    ):




		'''simple docstring'''







		@slow
		def 							__A						(	self				)     ->							List[Any]:
								SCREAMING_SNAKE_CASE													=					ImageGPTImageProcessor.from_pretrained('openai/imagegpt-small'				)

								SCREAMING_SNAKE_CASE													=					prepare_images()

								# test non-batched
								SCREAMING_SNAKE_CASE													=					image_processing(images[0]						,       return_tensors='pt'				)

								self.assertIsInstance(encoding.input_ids						,       torch.LongTensor				)
								self.assertEqual(encoding.input_ids.shape						,       (1, 1_024)				)

								SCREAMING_SNAKE_CASE													=					[306, 191, 191]
								self.assertEqual(encoding.input_ids[0, :3].tolist()						,       lowerCAmelCase__				)

								# test batched
								SCREAMING_SNAKE_CASE													=					image_processing(lowerCAmelCase__						,       return_tensors='pt'				)

								self.assertIsInstance(encoding.input_ids						,       torch.LongTensor				)
								self.assertEqual(encoding.input_ids.shape						,       (2, 1_024)				)

								SCREAMING_SNAKE_CASE													=					[303, 13, 13]
								self.assertEqual(encoding.input_ids[1, -3:].tolist()						,       lowerCAmelCase__				)


