

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_    ( A  ,		unittest.TestCase ):



 """simple docstring"""







 _lowercase     :					List[Any]      =						'''ssube/stable-diffusion-x4-upscaler-onnx'''

 def    __magic_name__       (		self :	Union[str, Any]     ,						A_ :	str=0       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[Any]        =    floats_tensor((1, 3, 1_2_8, 1_2_8)     ,						rng=random.Random(__A       )       )
      _lowerCAmelCase   :					Optional[Any]        =    torch.manual_seed(__A       )
      _lowerCAmelCase   :					str        =    {
          "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    __magic_name__       (		self :	int       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[int]        =    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,						provider="CPUExecutionProvider"       )
      pipe.set_progress_bar_config(disable=__A       )

      _lowerCAmelCase   :					str        =    self.get_dummy_inputs()
      _lowerCAmelCase   :					Optional[Any]        =    pipe(**__A       ).images
      _lowerCAmelCase   :					Tuple        =    image[0, -3:, -3:, -1].flatten()

      # started as 128, should now be 512
      assert image.shape == (1, 5_1_2, 5_1_2, 3)
      _lowerCAmelCase   :					Optional[Any]        =    np.array(
          [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]       )
      assert np.abs(image_slice - expected_slice       ).max() < 1E-1

 def    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[str]        =    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,						provider="CPUExecutionProvider"       )
      _lowerCAmelCase   :					str        =    PNDMScheduler.from_config(pipe.scheduler.config     ,						skip_prk_steps=__A       )
      pipe.set_progress_bar_config(disable=__A       )

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

      assert image.shape == (1, 5_1_2, 5_1_2, 3)
      _lowerCAmelCase   :					Optional[int]        =    np.array(
          [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964]       )
      assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-1

 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Any        =    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,						provider="CPUExecutionProvider"       )
      _lowerCAmelCase   :					str        =    DPMSolverMultistepScheduler.from_config(pipe.scheduler.config       )
      pipe.set_progress_bar_config(disable=__A       )

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

      assert image.shape == (1, 5_1_2, 5_1_2, 3)
      _lowerCAmelCase   :					List[str]        =    np.array(
          [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515]       )

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

 def    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					str        =    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,						provider="CPUExecutionProvider"       )
      _lowerCAmelCase   :					Optional[Any]        =    EulerDiscreteScheduler.from_config(pipe.scheduler.config       )
      pipe.set_progress_bar_config(disable=__A       )

      _lowerCAmelCase   :					Optional[Any]        =    self.get_dummy_inputs()
      _lowerCAmelCase   :					List[Any]        =    pipe(**__A       ).images
      _lowerCAmelCase   :					Optional[Any]        =    image[0, -3:, -3:, -1]

      assert image.shape == (1, 5_1_2, 5_1_2, 3)
      _lowerCAmelCase   :					Union[str, Any]        =    np.array(
          [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]       )
      assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-1


 def    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Tuple        =    OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint     ,						provider="CPUExecutionProvider"       )
      _lowerCAmelCase   :					Optional[Any]        =    EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config       )
      pipe.set_progress_bar_config(disable=__A       )

      _lowerCAmelCase   :					str        =    self.get_dummy_inputs()
      _lowerCAmelCase   :					Dict        =    pipe(**__A       ).images
      _lowerCAmelCase   :					List[str]        =    image[0, -3:, -3:, -1]

      assert image.shape == (1, 5_1_2, 5_1_2, 3)
      _lowerCAmelCase   :					Dict        =    np.array(
          [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043]       )

      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    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




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

 @property
 def    __magic_name__       (		self :	str       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Dict        =    ort.SessionOptions()
      _lowerCAmelCase   :					Union[str, Any]        =    False
      return options

 def    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[Any]        =    load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/img2img/sketch-mountains-input.jpg"       )
      _lowerCAmelCase   :					Dict        =    init_image.resize((1_2_8, 1_2_8)       )
      # using the PNDM scheduler by default
      _lowerCAmelCase   :					int        =    OnnxStableDiffusionUpscalePipeline.from_pretrained(
          "ssube/stable-diffusion-x4-upscaler-onnx"     ,						provider=self.gpu_provider     ,						sess_options=self.gpu_options     ,						)
      pipe.set_progress_bar_config(disable=__A       )

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

      _lowerCAmelCase   :					List[str]        =    torch.manual_seed(0       )
      _lowerCAmelCase   :					Any        =    pipe(
          prompt=__A     ,						image=__A     ,						guidance_scale=7.5     ,						num_inference_steps=1_0     ,						generator=__A     ,						output_type="np"     ,						)
      _lowerCAmelCase   :					Optional[int]        =    output.images
      _lowerCAmelCase   :					int        =    images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

      assert images.shape == (1, 5_1_2, 5_1_2, 3)
      _lowerCAmelCase   :					Tuple        =    np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972]       )
      # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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


 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[Any]        =    load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/img2img/sketch-mountains-input.jpg"       )
      _lowerCAmelCase   :					List[Any]        =    init_image.resize((1_2_8, 1_2_8)       )
      _lowerCAmelCase   :					Union[str, Any]        =    LMSDiscreteScheduler.from_pretrained(
          "ssube/stable-diffusion-x4-upscaler-onnx"     ,						subfolder="scheduler"       )
      _lowerCAmelCase   :					str        =    OnnxStableDiffusionUpscalePipeline.from_pretrained(
          "ssube/stable-diffusion-x4-upscaler-onnx"     ,						scheduler=__A     ,						provider=self.gpu_provider     ,						sess_options=self.gpu_options     ,						)
      pipe.set_progress_bar_config(disable=__A       )

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

      _lowerCAmelCase   :					Optional[int]        =    torch.manual_seed(0       )
      _lowerCAmelCase   :					str        =    pipe(
          prompt=__A     ,						image=__A     ,						guidance_scale=7.5     ,						num_inference_steps=2_0     ,						generator=__A     ,						output_type="np"     ,						)
      _lowerCAmelCase   :					Tuple        =    output.images
      _lowerCAmelCase   :					Optional[int]        =    images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

      assert images.shape == (1, 5_1_2, 5_1_2, 3)
      _lowerCAmelCase   :					int        =    np.array(
          [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566]       )
      # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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









def 	_snake_case		(    SCREAMING_SNAKE_CASE				)       ->      "list[int]":

     """simple docstring"""







     if upper_limit < 0:
          raise ValueError("Limit for the Catalan sequence must be ≥ 0"				)

     _lowerCAmelCase   :					Optional[Any]        =    [0] * (upper_limit + 1)

     # Base case: C(0) = C(1) = 1
     _lowerCAmelCase   :					Optional[int]        =    1
     if upper_limit > 0:
          _lowerCAmelCase   :					Any        =    1

     # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i
     for i in range(2		,							upper_limit + 1				):
          for j in range(SCREAMING_SNAKE_CASE				):
               catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1]

     return catalan_list


if __name__ == "__main__":
  print('\n********* Catalan Numbers Using Dynamic Programming ************\n')
  print('\n*** Enter -1 at any time to quit ***')
  print('\nEnter the upper limit (≥ 0) for the Catalan number sequence: ', end='')
  try:
    while True:
      __UpperCAmelCase    				=     int(input().strip())
      if N < 0:
        print('\n********* Goodbye!! ************')
        break
      else:
        print(f'''The Catalan numbers from 0 through {N} are:''')
        print(catalan_numbers(N))
        print('Try another upper limit for the sequence: ', end='')
  except (NameError, ValueError):
    print('\n********* Invalid input, goodbye! ************\n')

  import doctest

  doctest.testmod()






