





'''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 					UpperCAmelCase	(     snake_case_				,						unittest.TestCase  ):
      # TODO: is there an appropriate internal test set?
      _lowercase:     str			=  '''ssube/stable-diffusion-x4-upscaler-onnx'''




      def 							lowercase__       (     self     :					int     ,     __snake_case     :					Dict=0    )							-> Optional[int]:
            _lowerCAmelCase					=				floats_tensor((1, 3, 1_28, 1_28)     ,     rng=random.Random(__snake_case    )    )
            _lowerCAmelCase					=				torch.manual_seed(__snake_case    )
            _lowerCAmelCase					=				{
                """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 							lowercase__       (     self     :					Optional[Any]    )							-> Union[str, Any]:
            _lowerCAmelCase					=				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,     provider="""CPUExecutionProvider"""    )
            pipe.set_progress_bar_config(disable=__snake_case    )

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

            # started as 128, should now be 512
            assert image.shape == (1, 5_12, 5_12, 3)
            _lowerCAmelCase					=				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 							lowercase__       (     self     :					Any    )							-> Union[str, Any]:
            _lowerCAmelCase					=				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,     provider="""CPUExecutionProvider"""    )
            _lowerCAmelCase					=				PNDMScheduler.from_config(pipe.scheduler.config     ,     skip_prk_steps=__snake_case    )
            pipe.set_progress_bar_config(disable=__snake_case    )

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

            assert image.shape == (1, 5_12, 5_12, 3)
            _lowerCAmelCase					=				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 							lowercase__       (     self     :					Union[str, Any]    )							-> Optional[Any]:
            _lowerCAmelCase					=				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,     provider="""CPUExecutionProvider"""    )
            _lowerCAmelCase					=				DPMSolverMultistepScheduler.from_config(pipe.scheduler.config    )
            pipe.set_progress_bar_config(disable=__snake_case    )

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

            assert image.shape == (1, 5_12, 5_12, 3)
            _lowerCAmelCase					=				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 							lowercase__       (     self     :					int    )							-> List[Any]:
            _lowerCAmelCase					=				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,     provider="""CPUExecutionProvider"""    )
            _lowerCAmelCase					=				EulerDiscreteScheduler.from_config(pipe.scheduler.config    )
            pipe.set_progress_bar_config(disable=__snake_case    )

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

            assert image.shape == (1, 5_12, 5_12, 3)
            _lowerCAmelCase					=				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 							lowercase__       (     self     :					Any    )							-> Union[str, Any]:
            _lowerCAmelCase					=				OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,     provider="""CPUExecutionProvider"""    )
            _lowerCAmelCase					=				EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config    )
            pipe.set_progress_bar_config(disable=__snake_case    )

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

            assert image.shape == (1, 5_12, 5_12, 3)
            _lowerCAmelCase					=				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 					UpperCAmelCase	(     unittest.TestCase  ):




      @property
      def 							lowercase__       (     self     :					Optional[int]    )							-> List[Any]:
            return (
                "CUDAExecutionProvider",
                {
                    "gpu_mem_limit": "15000000000",  # 15GB
                    "arena_extend_strategy": "kSameAsRequested",
                },
            )




      @property
      def 							lowercase__       (     self     :					Tuple    )							-> Optional[int]:
            _lowerCAmelCase					=				ort.SessionOptions()
            _lowerCAmelCase					=				False
            return options




      def 							lowercase__       (     self     :					str    )							-> str:
            _lowerCAmelCase					=				load_image(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                """/img2img/sketch-mountains-input.jpg"""    )
            _lowerCAmelCase					=				init_image.resize((1_28, 1_28)    )
            # using the PNDM scheduler by default
            _lowerCAmelCase					=				OnnxStableDiffusionUpscalePipeline.from_pretrained(
                """ssube/stable-diffusion-x4-upscaler-onnx"""     ,     provider=self.gpu_provider     ,     sess_options=self.gpu_options     ,     )
            pipe.set_progress_bar_config(disable=__snake_case    )

            _lowerCAmelCase					=				"""A fantasy landscape, trending on artstation"""

            _lowerCAmelCase					=				torch.manual_seed(0    )
            _lowerCAmelCase					=				pipe(
                prompt=__snake_case     ,     image=__snake_case     ,     guidance_scale=7.5     ,     num_inference_steps=10     ,     generator=__snake_case     ,     output_type="""np"""     ,     )
            _lowerCAmelCase					=				output.images
            _lowerCAmelCase					=				images[0, 2_55:2_58, 3_83:3_86, -1]

            assert images.shape == (1, 5_12, 5_12, 3)
            _lowerCAmelCase					=				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 							lowercase__       (     self     :					List[Any]    )							-> List[Any]:
            _lowerCAmelCase					=				load_image(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                """/img2img/sketch-mountains-input.jpg"""    )
            _lowerCAmelCase					=				init_image.resize((1_28, 1_28)    )
            _lowerCAmelCase					=				LMSDiscreteScheduler.from_pretrained(
                """ssube/stable-diffusion-x4-upscaler-onnx"""     ,     subfolder="""scheduler"""    )
            _lowerCAmelCase					=				OnnxStableDiffusionUpscalePipeline.from_pretrained(
                """ssube/stable-diffusion-x4-upscaler-onnx"""     ,     scheduler=__snake_case     ,     provider=self.gpu_provider     ,     sess_options=self.gpu_options     ,     )
            pipe.set_progress_bar_config(disable=__snake_case    )

            _lowerCAmelCase					=				"""A fantasy landscape, trending on artstation"""

            _lowerCAmelCase					=				torch.manual_seed(0    )
            _lowerCAmelCase					=				pipe(
                prompt=__snake_case     ,     image=__snake_case     ,     guidance_scale=7.5     ,     num_inference_steps=20     ,     generator=__snake_case     ,     output_type="""np"""     ,     )
            _lowerCAmelCase					=				output.images
            _lowerCAmelCase					=				images[0, 2_55:2_58, 3_83:3_86, -1]

            assert images.shape == (1, 5_12, 5_12, 3)
            _lowerCAmelCase					=				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 numpy as np
from cva import COLOR_BGR2GRAY, cvtColor, imread
from numpy import array, uinta
from PIL import Image

from digital_image_processing import change_contrast as cc
from digital_image_processing import convert_to_negative as cn
from digital_image_processing import sepia as sp
from digital_image_processing.dithering import burkes as bs
from digital_image_processing.edge_detection import canny
from digital_image_processing.filters import convolve as conv
from digital_image_processing.filters import gaussian_filter as gg
from digital_image_processing.filters import local_binary_pattern as lbp
from digital_image_processing.filters import median_filter as med
from digital_image_processing.filters import sobel_filter as sob
from digital_image_processing.resize import resize as rs

A__							:  List[str]    =imread(r'''digital_image_processing/image_data/lena_small.jpg''')
A__							:  Union[str, Any]    =cvtColor(img, COLOR_BGR2GRAY)
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				cn.convert_to_negative(lowerCAmelCase    )
      # assert negative_img array for at least one True
      assert negative_img.any()
def   UpperCamelCase__ (						):





      """simple docstring"""


      with Image.open("""digital_image_processing/image_data/lena_small.jpg"""    ) as img:
            # Work around assertion for response
            assert str(cc.change_contrast(lowerCAmelCase				,      1_10    )    ).startswith(
                """<PIL.Image.Image image mode=RGB size=100x100 at"""    )
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				canny.gen_gaussian_kernel(9				,      sigma=1.4    )
      # Assert ambiguous array
      assert resp.all()
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				imread("""digital_image_processing/image_data/lena_small.jpg"""				,      0    )
      # assert ambiguous array for all == True
      assert canny_img.all()
      _lowerCAmelCase					=				canny.canny(lowerCAmelCase    )
      # assert canny array for at least one True
      assert canny_array.any()
def   UpperCamelCase__ (						):





      """simple docstring"""


      assert gg.gaussian_filter(lowerCAmelCase				,      5				,      sigma=0.9    ).all()
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]    )
      _lowerCAmelCase					=				conv.img_convolve(lowerCAmelCase				,      lowerCAmelCase    ).astype(lowerCAmelCase    )
      assert res.any()
def   UpperCamelCase__ (						):





      """simple docstring"""


      assert med.median_filter(lowerCAmelCase				,      3    ).any()
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase	,				_lowerCAmelCase					=				sob.sobel_filter(lowerCAmelCase    )
      assert grad.any() and theta.any()
def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				sp.make_sepia(lowerCAmelCase				,      20    )
      assert sepia.all()
def   UpperCamelCase__ (						lowerCAmelCase = "digital_image_processing/image_data/lena_small.jpg"    ):





      """simple docstring"""


      _lowerCAmelCase					=				bs.Burkes(imread(lowerCAmelCase				,      1    )				,      1_20    )
      burkes.process()
      assert burkes.output_img.any()
def   UpperCamelCase__ (						lowerCAmelCase = "digital_image_processing/image_data/lena_small.jpg"				,      ):





      """simple docstring"""


      _lowerCAmelCase					=				rs.NearestNeighbour(imread(lowerCAmelCase				,      1    )				,      4_00				,      2_00    )
      nn.process()
      assert nn.output.any()





def   UpperCamelCase__ (						):





      """simple docstring"""


      _lowerCAmelCase					=				"""digital_image_processing/image_data/lena.jpg"""

      # Reading the image and converting it to grayscale.
      _lowerCAmelCase					=				imread(lowerCAmelCase				,      0    )

      # Test for get_neighbors_pixel function() return not None
      _lowerCAmelCase					=				0
      _lowerCAmelCase					=				0
      _lowerCAmelCase					=				image[x_coordinate][y_coordinate]

      _lowerCAmelCase					=				lbp.get_neighbors_pixel(
          lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase    )

      assert neighbors_pixels is not None

      # Test for local_binary_pattern function()
      # Create a numpy array as the same height and width of read image
      _lowerCAmelCase					=				np.zeros((image.shape[0], image.shape[1])    )

      # Iterating through the image and calculating the local binary pattern value
      # for each pixel.
      for i in range(0				,      image.shape[0]    ):
            for j in range(0				,      image.shape[1]    ):
                  _lowerCAmelCase					=				lbp.local_binary_value(lowerCAmelCase				,      lowerCAmelCase				,      lowerCAmelCase    )

      assert lbp_image.any()






