"""simple docstring"""



from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
       import torch


__lowercase		:		Union[str, Any]														=							logging.get_logger(__name__)



class      _A	(						_UpperCAmelCase					):




    """simple docstring"""




    UpperCamelCase_	:					Optional[int]							=					['''pixel_values''']
    def __init__(		self							:     List[Any]	,      A_							:     bool = True	,      A_							:     Optional[Dict[str, int]] = None	,      A_							:     PILImageResampling = PILImageResampling.BILINEAR	,      A_							:     bool = True	,      A_							:     Dict[str, int] = None	,      A_							:     bool = True	,      A_							:     Union[int, float] = 1 / 255	,      A_							:     bool = True	,      A_							:     Optional[Union[float, List[float]]] = None	,      A_							:     Optional[Union[float, List[float]]] = None	,      **A_							:     Tuple	,      )    ->       None:
         super().__init__(**A_    )
         __snake_case				=							size if size is not None else {'''shortest_edge''': 256}
         __snake_case				=							get_size_dict(A_	,      default_to_square=A_    )
         __snake_case				=							crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
         __snake_case				=							get_size_dict(A_	,      param_name='''crop_size'''    )
         __snake_case				=							do_resize
         __snake_case				=							size
         __snake_case				=							resample
         __snake_case				=							do_center_crop
         __snake_case				=							crop_size
         __snake_case				=							do_rescale
         __snake_case				=							rescale_factor
         __snake_case				=							do_normalize
         __snake_case				=							image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
         __snake_case				=							image_std if image_std is not None else IMAGENET_STANDARD_STD
    def  lowercase					(		self							:     Optional[int]	,      A_							:     np.ndarray	,      A_							:     Dict[str, int]	,      A_							:     PILImageResampling = PILImageResampling.BICUBIC	,      A_							:     Optional[Union[str, ChannelDimension]] = None	,      **A_							:     List[str]	,      )    ->       np.ndarray:
         __snake_case				=							get_size_dict(A_	,      default_to_square=A_    )
         if "shortest_edge" not in size:
              raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"    )
         __snake_case				=							get_resize_output_image_size(A_	,      size=size['''shortest_edge''']	,      default_to_square=A_    )
         return resize(A_	,      size=A_	,      resample=A_	,      data_format=A_	,      **A_    )
    def  lowercase					(		self							:     Tuple	,      A_							:     np.ndarray	,      A_							:     Dict[str, int]	,      A_							:     Optional[Union[str, ChannelDimension]] = None	,      **A_							:     Optional[int]	,      )    ->       np.ndarray:
         __snake_case				=							get_size_dict(A_    )
         if "height" not in size or "width" not in size:
              raise ValueError(f"The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}"    )
         return center_crop(A_	,      size=(size['''height'''], size['''width'''])	,      data_format=A_	,      **A_    )
    def  lowercase					(		self							:     Dict	,      A_							:     np.ndarray	,      A_							:     float	,      A_							:     Optional[Union[str, ChannelDimension]] = None	,      **A_							:     Dict    )    ->       np.ndarray:
         return rescale(A_	,      scale=A_	,      data_format=A_	,      **A_    )
    def  lowercase					(		self							:     Optional[int]	,      A_							:     np.ndarray	,      A_							:     Union[float, List[float]]	,      A_							:     Union[float, List[float]]	,      A_							:     Optional[Union[str, ChannelDimension]] = None	,      **A_							:     Optional[int]	,      )    ->       np.ndarray:
         return normalize(A_	,      mean=A_	,      std=A_	,      data_format=A_	,      **A_    )
    def  lowercase					(		self							:     Any	,      A_							:     ImageInput	,      A_							:     Optional[bool] = None	,      A_							:     Dict[str, int] = None	,      A_							:     PILImageResampling = None	,      A_							:     bool = None	,      A_							:     Dict[str, int] = None	,      A_							:     Optional[bool] = None	,      A_							:     Optional[float] = None	,      A_							:     Optional[bool] = None	,      A_							:     Optional[Union[float, List[float]]] = None	,      A_							:     Optional[Union[float, List[float]]] = None	,      A_							:     Optional[Union[str, TensorType]] = None	,      A_							:     Union[str, ChannelDimension] = ChannelDimension.FIRST	,      **A_							:     Dict	,      )    ->       Union[str, Any]:
         __snake_case				=							do_resize if do_resize is not None else self.do_resize
         __snake_case				=							size if size is not None else self.size
         __snake_case				=							get_size_dict(A_	,      default_to_square=A_    )
         __snake_case				=							resample if resample is not None else self.resample
         __snake_case				=							do_center_crop if do_center_crop is not None else self.do_center_crop
         __snake_case				=							crop_size if crop_size is not None else self.crop_size
         __snake_case				=							get_size_dict(A_	,      param_name='''crop_size'''    )
         __snake_case				=							do_rescale if do_rescale is not None else self.do_rescale
         __snake_case				=							rescale_factor if rescale_factor is not None else self.rescale_factor
         __snake_case				=							do_normalize if do_normalize is not None else self.do_normalize
         __snake_case				=							image_mean if image_mean is not None else self.image_mean
         __snake_case				=							image_std if image_std is not None else self.image_std

         __snake_case				=							make_list_of_images(A_    )

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

         if do_resize and size is None:
              raise ValueError('''Size must be specified if do_resize is True.'''    )

         if do_center_crop and crop_size is None:
              raise ValueError('''Crop size must be specified if do_center_crop is True.'''    )

         if do_rescale and rescale_factor is None:
              raise ValueError('''Rescale factor must be specified if do_rescale is True.'''    )

         if do_normalize and (image_mean is None or image_std is None):
              raise ValueError('''Image mean and std must be specified if do_normalize is True.'''    )

         # All transformations expect numpy arrays.
         __snake_case				=							[to_numpy_array(A_    ) for image in images]

         if do_resize:
              __snake_case				=							[self.resize(image=A_	,      size=A_	,      resample=A_    ) for image in images]

         if do_center_crop:
              __snake_case				=							[self.center_crop(image=A_	,      size=A_    ) for image in images]

         if do_rescale:
              __snake_case				=							[self.rescale(image=A_	,      scale=A_    ) for image in images]

         if do_normalize:
              __snake_case				=							[self.normalize(image=A_	,      mean=A_	,      std=A_    ) for image in images]

         __snake_case				=							[to_channel_dimension_format(A_	,      A_    ) for image in images]

         __snake_case				=							{'''pixel_values''': images}
         return BatchFeature(data=A_	,      tensor_type=A_    )







    def  lowercase					(		self							:     int	,      A_							:     Dict	,      A_							:     List[Tuple] = None    )    ->       Any:
         __snake_case				=							outputs.logits

         # Resize logits and compute semantic segmentation maps
         if target_sizes is not None:
              if len(A_    ) != len(A_    ):
                   raise ValueError(
                       '''Make sure that you pass in as many target sizes as the batch dimension of the logits'''    )

              if is_torch_tensor(A_    ):
                   __snake_case				=							target_sizes.numpy()

              __snake_case				=							[]

              for idx in range(len(A_    )    ):
                   __snake_case				=							torch.nn.functional.interpolate(
                       logits[idx].unsqueeze(dim=0    )	,      size=target_sizes[idx]	,      mode='''bilinear'''	,      align_corners=A_    )
                   __snake_case				=							resized_logits[0].argmax(dim=0    )
                   semantic_segmentation.append(A_    )
         else:
              __snake_case				=							logits.argmax(dim=1    )
              __snake_case				=							[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]    )]

         return semantic_segmentation







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




    """simple docstring"""




    UpperCamelCase_	:					Dict							=					'''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'''
    def  lowercase					(		self							:     Optional[int]	,      A_							:     List[str]=0    )    ->       int:
         __snake_case				=							floats_tensor((1, 3, 128, 128)	,      rng=random.Random(A_    )    )
         __snake_case				=							np.random.RandomState(A_    )
         __snake_case				=							{
             '''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  lowercase					(		self							:     Optional[Any]    )    ->       List[Any]:
         __snake_case				=							OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,      provider='''CPUExecutionProvider'''    )
         pipe.set_progress_bar_config(disable=A_    )

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

         assert image.shape == (1, 128, 128, 3)
         __snake_case				=							np.array([0.6_96_43, 0.5_84_84, 0.5_03_14, 0.5_87_60, 0.5_53_68, 0.5_96_43, 0.5_15_29, 0.4_12_17, 0.4_90_87]    )
         assert np.abs(image_slice - expected_slice    ).max() < 1E-1
    def  lowercase					(		self							:     Tuple    )    ->       Optional[int]:
         __snake_case				=							OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,      provider='''CPUExecutionProvider'''    )
         __snake_case				=							PNDMScheduler.from_config(pipe.scheduler.config	,      skip_prk_steps=A_    )
         pipe.set_progress_bar_config(disable=A_    )

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

         assert image.shape == (1, 128, 128, 3)
         __snake_case				=							np.array([0.6_17_37, 0.5_46_42, 0.5_31_83, 0.5_44_65, 0.5_27_42, 0.6_05_25, 0.4_99_69, 0.4_06_55, 0.4_81_54]    )

         assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1E-1
    def  lowercase					(		self							:     Optional[int]    )    ->       str:
         __snake_case				=							OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,      provider='''CPUExecutionProvider'''    )
         __snake_case				=							LMSDiscreteScheduler.from_config(pipe.scheduler.config    )
         pipe.set_progress_bar_config(disable=A_    )

         # warmup pass to apply optimizations
         __snake_case				=							pipe(**self.get_dummy_inputs()    )

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

         assert image.shape == (1, 128, 128, 3)
         __snake_case				=							np.array([0.5_27_61, 0.5_99_77, 0.4_90_33, 0.4_96_19, 0.5_42_82, 0.5_03_11, 0.4_76_00, 0.4_09_18, 0.4_52_03]    )

         assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1E-1
    def  lowercase					(		self							:     str    )    ->       List[str]:
         __snake_case				=							OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,      provider='''CPUExecutionProvider'''    )
         __snake_case				=							EulerDiscreteScheduler.from_config(pipe.scheduler.config    )
         pipe.set_progress_bar_config(disable=A_    )

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

         assert image.shape == (1, 128, 128, 3)
         __snake_case				=							np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04]    )

         assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1E-1
    def  lowercase					(		self							:     Optional[int]    )    ->       Union[str, Any]:
         __snake_case				=							OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,      provider='''CPUExecutionProvider'''    )
         __snake_case				=							EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config    )
         pipe.set_progress_bar_config(disable=A_    )

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

         assert image.shape == (1, 128, 128, 3)
         __snake_case				=							np.array([0.5_29_11, 0.6_00_04, 0.4_92_29, 0.4_98_05, 0.5_45_02, 0.5_06_80, 0.4_77_77, 0.4_10_28, 0.4_53_04]    )

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







    def  lowercase					(		self							:     List[str]    )    ->       Any:
         __snake_case				=							OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint	,      provider='''CPUExecutionProvider'''    )
         __snake_case				=							DPMSolverMultistepScheduler.from_config(pipe.scheduler.config    )
         pipe.set_progress_bar_config(disable=A_    )

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

         assert image.shape == (1, 128, 128, 3)
         __snake_case				=							np.array([0.6_53_31, 0.5_82_77, 0.4_82_04, 0.5_60_59, 0.5_36_65, 0.5_62_35, 0.5_09_69, 0.4_00_09, 0.4_65_52]    )

         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  lowercase					(		self							:     str    )    ->       int:
         return (
             "CUDAExecutionProvider",
             {
                 "gpu_mem_limit": "15000000000",  # 15GB
                 "arena_extend_strategy": "kSameAsRequested",
             },
         )
    @property
    def  lowercase					(		self							:     Dict    )    ->       Union[str, Any]:
         __snake_case				=							ort.SessionOptions()
         __snake_case				=							False
         return options
    def  lowercase					(		self							:     Optional[Any]    )    ->       Union[str, Any]:
         __snake_case				=							load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/img2img/sketch-mountains-input.jpg'''    )
         __snake_case				=							init_image.resize((768, 512)    )
         # using the PNDM scheduler by default
         __snake_case				=							OnnxStableDiffusionImgaImgPipeline.from_pretrained(
             '''CompVis/stable-diffusion-v1-4'''	,      revision='''onnx'''	,      safety_checker=A_	,      feature_extractor=A_	,      provider=self.gpu_provider	,      sess_options=self.gpu_options	,      )
         pipe.set_progress_bar_config(disable=A_    )

         __snake_case				=							'''A fantasy landscape, trending on artstation'''

         __snake_case				=							np.random.RandomState(0    )
         __snake_case				=							pipe(
             prompt=A_	,      image=A_	,      strength=0.75	,      guidance_scale=7.5	,      num_inference_steps=10	,      generator=A_	,      output_type='''np'''	,      )
         __snake_case				=							output.images
         __snake_case				=							images[0, 255:258, 383:386, -1]

         assert images.shape == (1, 512, 768, 3)
         __snake_case				=							np.array([0.49_09, 0.50_59, 0.53_72, 0.46_23, 0.48_76, 0.50_49, 0.48_20, 0.49_56, 0.50_19]    )
         # 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							:     str    )    ->       Optional[int]:
         __snake_case				=							load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/img2img/sketch-mountains-input.jpg'''    )
         __snake_case				=							init_image.resize((768, 512)    )
         __snake_case				=							LMSDiscreteScheduler.from_pretrained(
             '''runwayml/stable-diffusion-v1-5'''	,      subfolder='''scheduler'''	,      revision='''onnx'''    )
         __snake_case				=							OnnxStableDiffusionImgaImgPipeline.from_pretrained(
             '''runwayml/stable-diffusion-v1-5'''	,      revision='''onnx'''	,      scheduler=A_	,      safety_checker=A_	,      feature_extractor=A_	,      provider=self.gpu_provider	,      sess_options=self.gpu_options	,      )
         pipe.set_progress_bar_config(disable=A_    )

         __snake_case				=							'''A fantasy landscape, trending on artstation'''

         __snake_case				=							np.random.RandomState(0    )
         __snake_case				=							pipe(
             prompt=A_	,      image=A_	,      strength=0.75	,      guidance_scale=7.5	,      num_inference_steps=20	,      generator=A_	,      output_type='''np'''	,      )
         __snake_case				=							output.images
         __snake_case				=							images[0, 255:258, 383:386, -1]

         assert images.shape == (1, 512, 768, 3)
         __snake_case				=							np.array([0.80_43, 0.9_26, 0.95_81, 0.81_19, 0.89_54, 0.9_13, 0.72_09, 0.74_63, 0.74_31]    )
         # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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