
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__  (       __lowercase    ,unittest.TestCase    ):
   _SCREAMING_SNAKE_CASE      :							Optional[int]	       =      "hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"
   def       lowerCAmelCase			(self :					Tuple					,				snake_case_ :					Optional[Any]=0   ):
    __a :  str						=  floats_tensor((1, 3, 1_2_8, 1_2_8)					,				rng=random.Random(snake_case_   )   )
    __a :  Dict						=  np.random.RandomState(snake_case_   )
    __a :  Tuple						=  {
        '''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 :					List[Any]   ):
    __a :  str						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,				provider='''CPUExecutionProvider'''   )
    pipe.set_progress_bar_config(disable=snake_case_   )

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

    assert image.shape == (1, 1_2_8, 1_2_8, 3)
    __a :  int						=  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 :					int   ):
    __a :  int						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,				provider='''CPUExecutionProvider'''   )
    __a :  Tuple						=  PNDMScheduler.from_config(pipe.scheduler.config					,				skip_prk_steps=snake_case_   )
    pipe.set_progress_bar_config(disable=snake_case_   )

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

    assert image.shape == (1, 1_2_8, 1_2_8, 3)
    __a :  int						=  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 :					int   ):
    __a :  Dict						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,				provider='''CPUExecutionProvider'''   )
    __a :  Tuple						=  LMSDiscreteScheduler.from_config(pipe.scheduler.config   )
    pipe.set_progress_bar_config(disable=snake_case_   )

    # warmup pass to apply optimizations
    __a :  Any						=  pipe(**self.get_dummy_inputs()   )

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

    assert image.shape == (1, 1_2_8, 1_2_8, 3)
    __a :  List[Any]						=  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 :					List[Any]   ):
    __a :  Dict						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,				provider='''CPUExecutionProvider'''   )
    __a :  Optional[int]						=  EulerDiscreteScheduler.from_config(pipe.scheduler.config   )
    pipe.set_progress_bar_config(disable=snake_case_   )

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

    assert image.shape == (1, 1_2_8, 1_2_8, 3)
    __a :  Union[str, 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       lowerCAmelCase			(self :					Dict   ):
    __a :  Any						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,				provider='''CPUExecutionProvider'''   )
    __a :  str						=  EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config   )
    pipe.set_progress_bar_config(disable=snake_case_   )

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

    assert image.shape == (1, 1_2_8, 1_2_8, 3)
    __a :  Union[str, 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       lowerCAmelCase			(self :					List[Any]   ):
    __a :  List[str]						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint					,				provider='''CPUExecutionProvider'''   )
    __a :  int						=  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config   )
    pipe.set_progress_bar_config(disable=snake_case_   )

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

    assert image.shape == (1, 1_2_8, 1_2_8, 3)
    __a :  List[Any]						=  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    ):
   @property
   def       lowerCAmelCase			(self :					List[str]   ):
    return (
        "CUDAExecutionProvider",
        {
            "gpu_mem_limit": "15000000000",  # 15GB
            "arena_extend_strategy": "kSameAsRequested",
        },
    )
   @property
   def       lowerCAmelCase			(self :					List[str]   ):
    __a :  Dict						=  ort.SessionOptions()
    __a :  str						=  False
    return options
   def       lowerCAmelCase			(self :					str   ):
    __a :  int						=  load_image(
        '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
        '''/img2img/sketch-mountains-input.jpg'''   )
    __a :  List[str]						=  init_image.resize((7_6_8, 5_1_2)   )
    # using the PNDM scheduler by default
    __a :  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_   )

    __a :  Optional[Any]						=  '''A fantasy landscape, trending on artstation'''

    __a :  Union[str, Any]						=  np.random.RandomState(0   )
    __a :  Union[str, Any]						=  pipe(
        prompt=snake_case_					,				image=snake_case_					,				strength=0.75					,				guidance_scale=7.5					,				num_inference_steps=1_0					,				generator=snake_case_					,				output_type='''np'''					,				)
    __a :  str						=  output.images
    __a :  List[Any]						=  images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

    assert images.shape == (1, 5_1_2, 7_6_8, 3)
    __a :  List[str]						=  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]   ):
    __a :  List[Any]						=  load_image(
        '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
        '''/img2img/sketch-mountains-input.jpg'''   )
    __a :  List[Any]						=  init_image.resize((7_6_8, 5_1_2)   )
    __a :  Any						=  LMSDiscreteScheduler.from_pretrained(
        '''runwayml/stable-diffusion-v1-5'''					,				subfolder='''scheduler'''					,				revision='''onnx'''   )
    __a :  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_   )

    __a :  Tuple						=  '''A fantasy landscape, trending on artstation'''

    __a :  Optional[Any]						=  np.random.RandomState(0   )
    __a :  Optional[Any]						=  pipe(
        prompt=snake_case_					,				image=snake_case_					,				strength=0.75					,				guidance_scale=7.5					,				num_inference_steps=2_0					,				generator=snake_case_					,				output_type='''np'''					,				)
    __a :  Union[str, Any]						=  output.images
    __a :  Any						=  images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

    assert images.shape == (1, 5_1_2, 7_6_8, 3)
    __a :  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


from __future__ import annotations

from fractions import Fraction
from math import gcd, sqrt




def    __UpperCamelCase     (				lowerCAmelCase__							:				int  ):
 __a :  int						=  int(number**0.5  )
 return number == sq * sq




def    __UpperCamelCase     (				lowerCAmelCase__							:				int  ,   lowerCAmelCase__							:				int  ,   lowerCAmelCase__							:				int  ,   lowerCAmelCase__							:				int  ,   lowerCAmelCase__							:				int  ,   lowerCAmelCase__							:				int  ):
 __a :  int						=  x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den
 __a :  int						=  x_den * y_den * z_den
 __a :  int						=  gcd(lowerCAmelCase__  ,   lowerCAmelCase__  )
 top //= hcf
 bottom //= hcf
 return top, bottom




def    __UpperCamelCase     (				lowerCAmelCase__							:				int = 3_5  ):
 __a :  set						=  set()
 __a :  int
 __a :  Fraction						=  Fraction(0  )
 __a :  tuple[int, int]

 for x_num in range(1  ,   order + 1  ):
  for x_den in range(x_num + 1  ,   order + 1  ):
   for y_num in range(1  ,   order + 1  ):
    for y_den in range(y_num + 1  ,   order + 1  ):
     # n=1
     __a :  Any						=  x_num * y_den + x_den * y_num
     __a :  Dict						=  x_den * y_den
     __a :  int						=  gcd(lowerCAmelCase__  ,   lowerCAmelCase__  )
     z_num //= hcf
     z_den //= hcf
     if 0 < z_num < z_den <= order:
      __a :  str						=  add_three(
          lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  )
      unique_s.add(lowerCAmelCase__  )

     # n=2
     __a :  Union[str, Any]						=  (
         x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num
     )
     __a :  Optional[Any]						=  x_den * x_den * y_den * y_den
     if is_sq(lowerCAmelCase__  ) and is_sq(lowerCAmelCase__  ):
      __a :  Any						=  int(sqrt(lowerCAmelCase__  )  )
      __a :  Optional[Any]						=  int(sqrt(lowerCAmelCase__  )  )
      __a :  int						=  gcd(lowerCAmelCase__  ,   lowerCAmelCase__  )
      z_num //= hcf
      z_den //= hcf
      if 0 < z_num < z_den <= order:
       __a :  str						=  add_three(
           lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  )
       unique_s.add(lowerCAmelCase__  )

                    # n=-1
     __a :  List[str]						=  x_num * y_num
     __a :  List[str]						=  x_den * y_num + x_num * y_den
     __a :  str						=  gcd(lowerCAmelCase__  ,   lowerCAmelCase__  )
     z_num //= hcf
     z_den //= hcf
     if 0 < z_num < z_den <= order:
      __a :  Optional[int]						=  add_three(
          lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  )
      unique_s.add(lowerCAmelCase__  )

     # n=2
     __a :  List[str]						=  x_num * x_num * y_num * y_num
     __a :  Optional[int]						=  (
         x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den
     )
     if is_sq(lowerCAmelCase__  ) and is_sq(lowerCAmelCase__  ):
      __a :  Union[str, Any]						=  int(sqrt(lowerCAmelCase__  )  )
      __a :  List[str]						=  int(sqrt(lowerCAmelCase__  )  )
      __a :  Optional[int]						=  gcd(lowerCAmelCase__  ,   lowerCAmelCase__  )
      z_num //= hcf
      z_den //= hcf
      if 0 < z_num < z_den <= order:
       __a :  int						=  add_three(
           lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  ,   lowerCAmelCase__  )
       unique_s.add(lowerCAmelCase__  )

 for num, den in unique_s:
  total += Fraction(lowerCAmelCase__  ,   lowerCAmelCase__  )

 return total.denominator + total.numerator


if __name__ == "__main__":
      print(F"""{solution() = }""")
