
import io
import math
from typing import Dict, Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    get_image_size,
    infer_channel_dimension_format,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_vision_available, logging
from ...utils.import_utils import requires_backends


if is_vision_available():
							import textwrap

							from PIL import Image, ImageDraw, ImageFont

if is_torch_available():
							import torch

							from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
							lowerCamelCase_  :	List[str] 				=					False


lowerCamelCase_  :	int 				=					logging.get_logger(__name__)
lowerCamelCase_  :	Optional[int] 				=					"""ybelkada/fonts"""







def     A__   (  )					->		Dict:
				if is_torch_available() and not is_torch_greater_or_equal_than_1_11:
								raise ImportError(
								    F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use '''
								    """Pix2StructImageProcessor. Please upgrade torch."""  )







def     A__   (  lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase  )					->		Optional[int]:
				requires_backends(lowerCamelCase       ,      ["""torch"""]  )
				_check_torch_version()

				UpperCamelCase_:							Tuple		=  image_tensor.unsqueeze(0  )
				UpperCamelCase_:							Any		=  torch.nn.functional.unfold(lowerCamelCase       ,      (patch_height, patch_width)       ,      stride=(patch_height, patch_width)  )
				UpperCamelCase_:							int		=  patches.reshape(image_tensor.size(0  )       ,      image_tensor.size(1  )       ,      lowerCamelCase       ,      lowerCamelCase       ,      -1  )
				UpperCamelCase_:							Any		=  patches.permute(0       ,      4       ,      2       ,      3       ,      1  ).reshape(
				    image_tensor.size(2  ) // patch_height       ,      image_tensor.size(3  ) // patch_width       ,      image_tensor.size(1  ) * patch_height * patch_width       ,      )
				return patches.unsqueeze(0  )







def     A__   (  lowerCamelCase       ,      lowerCamelCase = 36       ,      lowerCamelCase = "black"       ,      lowerCamelCase = "white"       ,      lowerCamelCase = 5       ,      lowerCamelCase = 5       ,      lowerCamelCase = 5       ,      lowerCamelCase = 5       ,      lowerCamelCase = None       ,      lowerCamelCase = None       ,      )					->		Image.Image:
				requires_backends(lowerCamelCase       ,      """vision"""  )
				# Add new lines so that each line is no more than 80 characters.

				UpperCamelCase_:							List[str]		=  textwrap.TextWrapper(width=80  )
				UpperCamelCase_:							Optional[int]		=  wrapper.wrap(text=lowerCamelCase  )
				UpperCamelCase_:							List[str]		=  """\n""".join(lowerCamelCase  )

				if font_bytes is not None and font_path is None:
								UpperCamelCase_:							List[Any]		=  io.BytesIO(lowerCamelCase  )
				elif font_path is not None:
								UpperCamelCase_:							List[Any]		=  font_path
				else:
								UpperCamelCase_:							Tuple		=  hf_hub_download(lowerCamelCase       ,      """Arial.TTF"""  )
				UpperCamelCase_:							Optional[Any]		=  ImageFont.truetype(lowerCamelCase       ,      encoding="""UTF-8"""       ,      size=lowerCamelCase  )

				# Use a temporary canvas to determine the width and height in pixels when
				# rendering the text.
				UpperCamelCase_:							str		=  ImageDraw.Draw(Image.new("""RGB"""       ,      (1, 1)       ,      lowerCamelCase  )  )
				UpperCamelCase_,				UpperCamelCase_,				UpperCamelCase_,				UpperCamelCase_:							Optional[int]		=  temp_draw.textbbox((0, 0)       ,      lowerCamelCase       ,      lowerCamelCase  )

				# Create the actual image with a bit of padding around the text.
				UpperCamelCase_:							Optional[int]		=  text_width + left_padding + right_padding
				UpperCamelCase_:							List[str]		=  text_height + top_padding + bottom_padding
				UpperCamelCase_:							Union[str, Any]		=  Image.new("""RGB"""       ,      (image_width, image_height)       ,      lowerCamelCase  )
				UpperCamelCase_:							Optional[Any]		=  ImageDraw.Draw(lowerCamelCase  )
				draw.text(xy=(left_padding, top_padding)       ,      text=lowerCamelCase       ,      fill=lowerCamelCase       ,      font=lowerCamelCase  )
				return image







def     A__   (  lowerCamelCase       ,      lowerCamelCase       ,      **lowerCamelCase  )					->		List[str]:
				requires_backends(lowerCamelCase       ,      """vision"""  )

				# Convert to PIL image if necessary
				UpperCamelCase_:							List[str]		=  to_pil_image(lowerCamelCase  )

				UpperCamelCase_:							Union[str, Any]		=  render_text(lowerCamelCase       ,      **lowerCamelCase  )
				UpperCamelCase_:							Tuple		=  max(header_image.width       ,      image.width  )

				UpperCamelCase_:							Tuple		=  int(image.height * (new_width / image.width)  )
				UpperCamelCase_:							Dict		=  int(header_image.height * (new_width / header_image.width)  )

				UpperCamelCase_:							str		=  Image.new("""RGB"""       ,      (new_width, new_height + new_header_height)       ,      """white"""  )
				new_image.paste(header_image.resize((new_width, new_header_height)  )       ,      (0, 0)  )
				new_image.paste(image.resize((new_width, new_height)  )       ,      (0, new_header_height)  )

				# Convert back to the original framework if necessary
				UpperCamelCase_:							Optional[Any]		=  to_numpy_array(lowerCamelCase  )

				if infer_channel_dimension_format(lowerCamelCase  ) == ChannelDimension.LAST:
								UpperCamelCase_:							Tuple		=  to_channel_dimension_format(lowerCamelCase       ,      ChannelDimension.LAST  )

				return new_image





class     _UpperCamelCase			(   _A					):






			'''simple docstring'''

			__UpperCamelCase :  Optional[int]    =	["""flattened_patches"""]

			def __init__(    self	:    int  ,		snake_case_	:    bool = True  ,		snake_case_	:    bool = True  ,		snake_case_	:    Dict[str, int] = None  ,		snake_case_	:    int = 2048  ,		snake_case_	:    bool = False  ,		**snake_case_	:    Any  ,		):
							super().__init__(**snake_case_ )
							UpperCamelCase_:							int		=  patch_size if patch_size is not None else {"""height""": 16, """width""": 16}
							UpperCamelCase_:							Tuple		=  do_normalize
							UpperCamelCase_:							List[Any]		=  do_convert_rgb
							UpperCamelCase_:							Tuple		=  max_patches
							UpperCamelCase_:							Tuple		=  is_vqa

			def  lowerCAmelCase__		(    self	:    int  ,		snake_case_	:    np.ndarray  ,		snake_case_	:    int  ,		snake_case_	:    dict  ,		**snake_case_	:    Tuple ):
							requires_backends(self.extract_flattened_patches  ,		"""torch""" )
							_check_torch_version()

							# convert to torch
							UpperCamelCase_:							int		=  to_channel_dimension_format(snake_case_  ,		ChannelDimension.FIRST )
							UpperCamelCase_:							List[str]		=  torch.from_numpy(snake_case_ )

							UpperCamelCase_,				UpperCamelCase_:							List[Any]		=  patch_size["""height"""], patch_size["""width"""]
							UpperCamelCase_,				UpperCamelCase_:							Tuple		=  get_image_size(snake_case_ )

							# maximize scale s.t.
							UpperCamelCase_:							List[Any]		=  math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) )
							UpperCamelCase_:							Any		=  max(min(math.floor(scale * image_height / patch_height )  ,		snake_case_ )  ,		1 )
							UpperCamelCase_:							List[str]		=  max(min(math.floor(scale * image_width / patch_width )  ,		snake_case_ )  ,		1 )
							UpperCamelCase_:							int		=  max(num_feasible_rows * patch_height  ,		1 )
							UpperCamelCase_:							Optional[Any]		=  max(num_feasible_cols * patch_width  ,		1 )

							UpperCamelCase_:							str		=  torch.nn.functional.interpolate(
							    image.unsqueeze(0 )  ,		size=(resized_height, resized_width)  ,		mode="""bilinear"""  ,		align_corners=snake_case_  ,		antialias=snake_case_  ,		).squeeze(0 )

							# [1, rows, columns, patch_height * patch_width * image_channels]
							UpperCamelCase_:							List[str]		=  torch_extract_patches(snake_case_  ,		snake_case_  ,		snake_case_ )

							UpperCamelCase_:							List[Any]		=  patches.shape
							UpperCamelCase_:							List[str]		=  patches_shape[1]
							UpperCamelCase_:							Optional[Any]		=  patches_shape[2]
							UpperCamelCase_:							List[str]		=  patches_shape[3]

							# [rows * columns, patch_height * patch_width * image_channels]
							UpperCamelCase_:							Union[str, Any]		=  patches.reshape([rows * columns, depth] )

							# [rows * columns, 1]
							UpperCamelCase_:							Optional[Any]		=  torch.arange(snake_case_ ).reshape([rows, 1] ).repeat(1  ,		snake_case_ ).reshape([rows * columns, 1] )
							UpperCamelCase_:							Optional[int]		=  torch.arange(snake_case_ ).reshape([1, columns] ).repeat(snake_case_  ,		1 ).reshape([rows * columns, 1] )

							# Offset by 1 so the ids do not contain zeros, which represent padding.
							row_ids += 1
							col_ids += 1

							# Prepare additional patch features.
							# [rows * columns, 1]
							UpperCamelCase_:							Union[str, Any]		=  row_ids.to(torch.floataa )
							UpperCamelCase_:							str		=  col_ids.to(torch.floataa )

							# [rows * columns, 2 + patch_height * patch_width * image_channels]
							UpperCamelCase_:							Optional[Any]		=  torch.cat([row_ids, col_ids, patches]  ,		-1 )

							# [max_patches, 2 + patch_height * patch_width * image_channels]
							UpperCamelCase_:							Tuple		=  torch.nn.functional.pad(snake_case_  ,		[0, 0, 0, max_patches - (rows * columns)] ).float()

							UpperCamelCase_:							List[Any]		=  to_numpy_array(snake_case_ )

							return result

			def  lowerCAmelCase__		(    self	:    List[Any]  ,		snake_case_	:    np.ndarray  ,		snake_case_	:    Optional[Union[str, ChannelDimension]] = None  ,		**snake_case_	:    Tuple ):
							if image.dtype == np.uinta:
											UpperCamelCase_:							List[str]		=  image.astype(np.floataa )

							# take mean across the whole `image`
							UpperCamelCase_:							str		=  np.mean(snake_case_ )
							UpperCamelCase_:							str		=  np.std(snake_case_ )
							UpperCamelCase_:							str		=  max(snake_case_  ,		1.0 / math.sqrt(np.prod(image.shape ) ) )

							return normalize(snake_case_  ,		mean=snake_case_  ,		std=snake_case_  ,		**snake_case_ )




			def  lowerCAmelCase__		(    self	:    str  ,		snake_case_	:    ImageInput  ,		snake_case_	:    Optional[str] = None  ,		snake_case_	:    bool = None  ,		snake_case_	:    Optional[bool] = None  ,		snake_case_	:    Optional[int] = None  ,		snake_case_	:    Optional[Dict[str, int]] = None  ,		snake_case_	:    Optional[Union[str, TensorType]] = None  ,		snake_case_	:    ChannelDimension = ChannelDimension.FIRST  ,		**snake_case_	:    Union[str, Any]  ,		):
							UpperCamelCase_:							Tuple		=  do_normalize if do_normalize is not None else self.do_normalize
							UpperCamelCase_:							Tuple		=  do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
							UpperCamelCase_:							Optional[Any]		=  patch_size if patch_size is not None else self.patch_size
							UpperCamelCase_:							Optional[int]		=  max_patches if max_patches is not None else self.max_patches
							UpperCamelCase_:							Tuple		=  self.is_vqa

							if kwargs.get("""data_format"""  ,		snake_case_ ) is not None:
											raise ValueError("""data_format is not an accepted input as the outputs are """ )

							UpperCamelCase_:							Dict		=  make_list_of_images(snake_case_ )

							if not valid_images(snake_case_ ):
											raise ValueError(
											    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
											    """torch.Tensor, tf.Tensor or jax.ndarray.""" )

							# PIL RGBA images are converted to RGB
							if do_convert_rgb:
											UpperCamelCase_:							str		=  [convert_to_rgb(snake_case_ ) for image in images]

							# All transformations expect numpy arrays.
							UpperCamelCase_:							Union[str, Any]		=  [to_numpy_array(snake_case_ ) for image in images]

							if is_vqa:
											if header_text is None:
															raise ValueError("""A header text must be provided for VQA models.""" )
											UpperCamelCase_:							List[Any]		=  kwargs.pop("""font_bytes"""  ,		snake_case_ )
											UpperCamelCase_:							List[Any]		=  kwargs.pop("""font_path"""  ,		snake_case_ )

											if isinstance(snake_case_  ,		snake_case_ ):
															UpperCamelCase_:							str		=  [header_text] * len(snake_case_ )

											UpperCamelCase_:							str		=  [
											    render_header(snake_case_  ,		header_text[i]  ,		font_bytes=snake_case_  ,		font_path=snake_case_ )
											    for i, image in enumerate(snake_case_ )
											]

							if do_normalize:
											UpperCamelCase_:							Union[str, Any]		=  [self.normalize(image=snake_case_ ) for image in images]

							# convert to torch tensor and permute
							UpperCamelCase_:							str		=  [
							    self.extract_flattened_patches(image=snake_case_  ,		max_patches=snake_case_  ,		patch_size=snake_case_ )
							    for image in images
							]

							# create attention mask in numpy
							UpperCamelCase_:							List[Any]		=  [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images]

							UpperCamelCase_:							Optional[Any]		=  BatchFeature(
							    data={"""flattened_patches""": images, """attention_mask""": attention_masks}  ,		tensor_type=snake_case_ )

							return encoded_outputs








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     _UpperCamelCase			(   _A       ,    unittest.TestCase					):






			'''simple docstring'''

			__UpperCamelCase :  Optional[Any]    =	"""hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"""

			def  lowerCAmelCase__		(    self	:    List[str]  ,		snake_case_	:    Optional[int]=0 ):
							UpperCamelCase_:							str		=  floats_tensor((1, 3, 128, 128)  ,		rng=random.Random(snake_case_ ) )
							UpperCamelCase_:							Optional[int]		=  np.random.RandomState(snake_case_ )
							UpperCamelCase_:							Dict		=  {
							    """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  lowerCAmelCase__		(    self	:    Any ):
							UpperCamelCase_:							Any		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							pipe.set_progress_bar_config(disable=snake_case_ )

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

							assert image.shape == (1, 128, 128, 3)
							UpperCamelCase_:							str		=  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  lowerCAmelCase__		(    self	:    List[str] ):
							UpperCamelCase_:							int		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							UpperCamelCase_:							Tuple		=  PNDMScheduler.from_config(pipe.scheduler.config  ,		skip_prk_steps=snake_case_ )
							pipe.set_progress_bar_config(disable=snake_case_ )

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

							assert image.shape == (1, 128, 128, 3)
							UpperCamelCase_:							Any		=  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  lowerCAmelCase__		(    self	:    str ):
							UpperCamelCase_:							str		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							UpperCamelCase_:							List[Any]		=  LMSDiscreteScheduler.from_config(pipe.scheduler.config )
							pipe.set_progress_bar_config(disable=snake_case_ )

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

							UpperCamelCase_:							Tuple		=  self.get_dummy_inputs()
							UpperCamelCase_:							Optional[int]		=  pipe(**snake_case_ ).images
							UpperCamelCase_:							str		=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 128, 128, 3)
							UpperCamelCase_:							Optional[int]		=  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  lowerCAmelCase__		(    self	:    Union[str, Any] ):
							UpperCamelCase_:							List[str]		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							UpperCamelCase_:							Optional[int]		=  EulerDiscreteScheduler.from_config(pipe.scheduler.config )
							pipe.set_progress_bar_config(disable=snake_case_ )

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

							assert image.shape == (1, 128, 128, 3)
							UpperCamelCase_:							List[str]		=  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  lowerCAmelCase__		(    self	:    Optional[int] ):
							UpperCamelCase_:							List[Any]		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							UpperCamelCase_:							List[Any]		=  EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
							pipe.set_progress_bar_config(disable=snake_case_ )

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

							assert image.shape == (1, 128, 128, 3)
							UpperCamelCase_:							Tuple		=  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  lowerCAmelCase__		(    self	:    Union[str, Any] ):
							UpperCamelCase_:							Optional[Any]		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint  ,		provider="""CPUExecutionProvider""" )
							UpperCamelCase_:							str		=  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
							pipe.set_progress_bar_config(disable=snake_case_ )

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

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






			'''simple docstring'''

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

			@property
			def  lowerCAmelCase__		(    self	:    List[Any] ):
							UpperCamelCase_:							Dict		=  ort.SessionOptions()
							UpperCamelCase_:							Optional[int]		=  False
							return options

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

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

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

							assert images.shape == (1, 512, 768, 3)
							UpperCamelCase_:							Tuple		=  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  lowerCAmelCase__		(    self	:    Optional[Any] ):
							UpperCamelCase_:							Union[str, Any]		=  load_image(
							    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
							    """/img2img/sketch-mountains-input.jpg""" )
							UpperCamelCase_:							List[Any]		=  init_image.resize((768, 512) )
							UpperCamelCase_:							Union[str, Any]		=  LMSDiscreteScheduler.from_pretrained(
							    """runwayml/stable-diffusion-v1-5"""  ,		subfolder="""scheduler"""  ,		revision="""onnx""" )
							UpperCamelCase_:							Dict		=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(
							    """runwayml/stable-diffusion-v1-5"""  ,		revision="""onnx"""  ,		scheduler=snake_case_  ,		safety_checker=snake_case_  ,		feature_extractor=snake_case_  ,		provider=self.gpu_provider  ,		sess_options=self.gpu_options  ,		)
							pipe.set_progress_bar_config(disable=snake_case_ )

							UpperCamelCase_:							Any		=  """A fantasy landscape, trending on artstation"""

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

							assert images.shape == (1, 512, 768, 3)
							UpperCamelCase_:							Optional[int]		=  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






