



"""simple docstring"""






import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    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 			A__   (  __SCREAMING_SNAKE_CASE  ,		unittest.TestCase							):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE          =	'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'

	def 							_SCREAMING_SNAKE_CASE   (     self:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		Optional[int]=0)				->       Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  Dict												=       floats_tensor((1, 3, 128, 128)       ,			rng=random.Random(_SCREAMING_SNAKE_CASE))
				__lowerCAmelCase      :  Optional[int]												=       np.random.RandomState(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  str												=       {
				    "prompt": "A painting of a squirrel eating a burger",
				    "image": image,
				    "generator": generator,
				    "num_inference_steps": 3,
				    "strength": 0.75,
				    "guidance_scale": 7.5,
				    "output_type": "numpy",
				}
				return inputs

	def 							_SCREAMING_SNAKE_CASE   (     self:		Dict)				->       Optional[int]:

				"""simple docstring"""

				__lowerCAmelCase      :  Optional[Any]												=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint       ,			provider="CPUExecutionProvider")
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  List[Any]												=       self.get_dummy_inputs()
				__lowerCAmelCase      :  List[str]												=       pipe(**_SCREAMING_SNAKE_CASE).images
				__lowerCAmelCase      :  List[str]												=       image[0, -3:, -3:, -1].flatten()

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase      :  Optional[Any]												=       np.array([0.6_9643, 0.5_8484, 0.5_0314, 0.5_8760, 0.5_5368, 0.5_9643, 0.5_1529, 0.4_1217, 0.4_9087])
				assert np.abs(image_slice - expected_slice).max() < 1e-1

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

				"""simple docstring"""

				__lowerCAmelCase      :  List[str]												=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint       ,			provider="CPUExecutionProvider")
				__lowerCAmelCase      :  Optional[Any]												=       PNDMScheduler.from_config(pipe.scheduler.config       ,			skip_prk_steps=_SCREAMING_SNAKE_CASE)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  str												=       self.get_dummy_inputs()
				__lowerCAmelCase      :  Any												=       pipe(**_SCREAMING_SNAKE_CASE).images
				__lowerCAmelCase      :  Optional[Any]												=       image[0, -3:, -3:, -1]

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase      :  str												=       np.array([0.6_1737, 0.5_4642, 0.5_3183, 0.5_4465, 0.5_2742, 0.6_0525, 0.4_9969, 0.4_0655, 0.4_8154])

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

	def 							_SCREAMING_SNAKE_CASE   (     self:		Any)				->       int:

				"""simple docstring"""

				__lowerCAmelCase      :  Dict												=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint       ,			provider="CPUExecutionProvider")
				__lowerCAmelCase      :  Union[str, Any]												=       LMSDiscreteScheduler.from_config(pipe.scheduler.config)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				# warmup pass to apply optimizations
				__lowerCAmelCase      :  Union[str, Any]												=       pipe(**self.get_dummy_inputs())

				__lowerCAmelCase      :  List[Any]												=       self.get_dummy_inputs()
				__lowerCAmelCase      :  List[str]												=       pipe(**_SCREAMING_SNAKE_CASE).images
				__lowerCAmelCase      :  Tuple												=       image[0, -3:, -3:, -1]

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase      :  str												=       np.array([0.5_2761, 0.5_9977, 0.4_9033, 0.4_9619, 0.5_4282, 0.5_0311, 0.4_7600, 0.4_0918, 0.4_5203])

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

	def 							_SCREAMING_SNAKE_CASE   (     self:		Dict)				->       Any:

				"""simple docstring"""

				__lowerCAmelCase      :  int												=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint       ,			provider="CPUExecutionProvider")
				__lowerCAmelCase      :  List[str]												=       EulerDiscreteScheduler.from_config(pipe.scheduler.config)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

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

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase      :  int												=       np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304])

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

	def 							_SCREAMING_SNAKE_CASE   (     self:		str)				->       str:

				"""simple docstring"""

				__lowerCAmelCase      :  Dict												=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint       ,			provider="CPUExecutionProvider")
				__lowerCAmelCase      :  List[str]												=       EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  List[Any]												=       self.get_dummy_inputs()
				__lowerCAmelCase      :  int												=       pipe(**_SCREAMING_SNAKE_CASE).images
				__lowerCAmelCase      :  Dict												=       image[0, -3:, -3:, -1]

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase      :  Any												=       np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304])

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







	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[Any])				->       Tuple:

				"""simple docstring"""

				__lowerCAmelCase      :  Optional[int]												=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint       ,			provider="CPUExecutionProvider")
				__lowerCAmelCase      :  Optional[int]												=       DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  Union[str, Any]												=       self.get_dummy_inputs()
				__lowerCAmelCase      :  Optional[Any]												=       pipe(**_SCREAMING_SNAKE_CASE).images
				__lowerCAmelCase      :  Tuple												=       image[0, -3:, -3:, -1]

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase      :  Tuple												=       np.array([0.6_5331, 0.5_8277, 0.4_8204, 0.5_6059, 0.5_3665, 0.5_6235, 0.5_0969, 0.4_0009, 0.4_6552])

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






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




	'''simple docstring'''





	@property
	def 							_SCREAMING_SNAKE_CASE   (     self:		Tuple)				->       Optional[Any]:

				"""simple docstring"""

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

	@property
	def 							_SCREAMING_SNAKE_CASE   (     self:		Union[str, Any])				->       List[str]:

				"""simple docstring"""

				__lowerCAmelCase      :  List[Any]												=       ort.SessionOptions()
				__lowerCAmelCase      :  int												=       False
				return options

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

				"""simple docstring"""

				__lowerCAmelCase      :  str												=       load_image(
				    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
				    "/img2img/sketch-mountains-input.jpg")
				__lowerCAmelCase      :  Union[str, Any]												=       init_image.resize((768, 512))
				# using the PNDM scheduler by default
				__lowerCAmelCase      :  Optional[int]												=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(
				    "CompVis/stable-diffusion-v1-4"       ,			revision="onnx"       ,			safety_checker=_SCREAMING_SNAKE_CASE       ,			feature_extractor=_SCREAMING_SNAKE_CASE       ,			provider=self.gpu_provider       ,			sess_options=self.gpu_options       ,			)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  Dict												=       "A fantasy landscape, trending on artstation"

				__lowerCAmelCase      :  Dict												=       np.random.RandomState(0)
				__lowerCAmelCase      :  Any												=       pipe(
				    prompt=_SCREAMING_SNAKE_CASE       ,			image=_SCREAMING_SNAKE_CASE       ,			strength=0.75       ,			guidance_scale=7.5       ,			num_inference_steps=10       ,			generator=_SCREAMING_SNAKE_CASE       ,			output_type="np"       ,			)
				__lowerCAmelCase      :  Optional[int]												=       output.images
				__lowerCAmelCase      :  Optional[int]												=       images[0, 255:258, 383:386, -1]

				assert images.shape == (1, 512, 768, 3)
				__lowerCAmelCase      :  int												=       np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019])
				# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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







	def 							_SCREAMING_SNAKE_CASE   (     self:		Any)				->       List[Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  Optional[int]												=       load_image(
				    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
				    "/img2img/sketch-mountains-input.jpg")
				__lowerCAmelCase      :  Dict												=       init_image.resize((768, 512))
				__lowerCAmelCase      :  List[str]												=       LMSDiscreteScheduler.from_pretrained(
				    "runwayml/stable-diffusion-v1-5"       ,			subfolder="scheduler"       ,			revision="onnx")
				__lowerCAmelCase      :  str												=       OnnxStableDiffusionImgaImgPipeline.from_pretrained(
				    "runwayml/stable-diffusion-v1-5"       ,			revision="onnx"       ,			scheduler=_SCREAMING_SNAKE_CASE       ,			safety_checker=_SCREAMING_SNAKE_CASE       ,			feature_extractor=_SCREAMING_SNAKE_CASE       ,			provider=self.gpu_provider       ,			sess_options=self.gpu_options       ,			)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  Optional[int]												=       "A fantasy landscape, trending on artstation"

				__lowerCAmelCase      :  int												=       np.random.RandomState(0)
				__lowerCAmelCase      :  Dict												=       pipe(
				    prompt=_SCREAMING_SNAKE_CASE       ,			image=_SCREAMING_SNAKE_CASE       ,			strength=0.75       ,			guidance_scale=7.5       ,			num_inference_steps=20       ,			generator=_SCREAMING_SNAKE_CASE       ,			output_type="np"       ,			)
				__lowerCAmelCase      :  Union[str, Any]												=       output.images
				__lowerCAmelCase      :  Tuple												=       images[0, 255:258, 383:386, -1]

				assert images.shape == (1, 512, 768, 3)
				__lowerCAmelCase      :  Optional[Any]												=       np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431])
				# 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 re
from pathlib import Path
from unittest import TestCase

import pytest



@pytest.mark.integration
class 			A__   (  __SCREAMING_SNAKE_CASE							):




	'''simple docstring'''





	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[int]       ,			_SCREAMING_SNAKE_CASE:		str)				->       Dict:

				"""simple docstring"""

				with open(_SCREAMING_SNAKE_CASE       ,			encoding="utf-8") as input_file:
							__lowerCAmelCase      :  List[str]												=       re.compile(r"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)")
							__lowerCAmelCase      :  List[Any]												=       input_file.read()
							__lowerCAmelCase      :  Any												=       regexp.search(_SCREAMING_SNAKE_CASE)

				return match

	def 							_SCREAMING_SNAKE_CASE   (     self:		List[Any]       ,			_SCREAMING_SNAKE_CASE:		str)				->       Optional[Any]:

				"""simple docstring"""

				with open(_SCREAMING_SNAKE_CASE       ,			encoding="utf-8") as input_file:
							__lowerCAmelCase      :  Any												=       re.compile(r"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()"       ,			re.DOTALL)
							__lowerCAmelCase      :  Optional[int]												=       input_file.read()
							# use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search`
							__lowerCAmelCase      :  int												=       regexp.finditer(_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase      :  Union[str, Any]												=       [match for match in matches if match is not None and match.group(1) is not None]
				return matches[0] if matches else None

	def 							_SCREAMING_SNAKE_CASE   (     self:		str)				->       List[Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  Optional[Any]												=       Path("./datasets")
				__lowerCAmelCase      :  Optional[int]												=       list(dataset_paths.absolute().glob("**/*.py"))

				for dataset in dataset_files:
							if self._no_encoding_on_file_open(str(_SCREAMING_SNAKE_CASE)):
										raise AssertionError(F"""open(...) must use utf-8 encoding in {dataset}""")







	def 							_SCREAMING_SNAKE_CASE   (     self:		Optional[Any])				->       Optional[int]:

				"""simple docstring"""

				__lowerCAmelCase      :  Dict												=       Path("./datasets")
				__lowerCAmelCase      :  Union[str, Any]												=       list(dataset_paths.absolute().glob("**/*.py"))

				for dataset in dataset_files:
							if self._no_print_statements(str(_SCREAMING_SNAKE_CASE)):
										raise AssertionError(F"""print statement found in {dataset}. Use datasets.logger/logging instead.""")