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      _A (     lowercase_						,			unittest.TestCase				):
  SCREAMING_SNAKE_CASE_						:						Optional[Any]    ="ssube/stable-diffusion-x4-upscaler-onnx"






  def 		_a       (self ,					SCREAMING_SNAKE_CASE_=0						)		->   Optional[Any]:





       '''simple docstring'''





       UpperCamelCase__					    =   floats_tensor((1, 3, 128, 128) ,					rng=random.Random(_lowercase						)						)
       UpperCamelCase__					    =   torch.manual_seed(_lowercase						)
       UpperCamelCase__					    =   {
           '''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 		_a       (self						)		->   str:





       '''simple docstring'''





       UpperCamelCase__					    =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,					provider='''CPUExecutionProvider'''						)
       pipe.set_progress_bar_config(disable=_lowercase						)

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

       # started as 128, should now be 512
       assert image.shape == (1, 512, 512, 3)
       UpperCamelCase__					    =   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 		_a       (self						)		->   Optional[Any]:





       '''simple docstring'''





       UpperCamelCase__					    =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,					provider='''CPUExecutionProvider'''						)
       UpperCamelCase__					    =   PNDMScheduler.from_config(pipe.scheduler.config ,					skip_prk_steps=_lowercase						)
       pipe.set_progress_bar_config(disable=_lowercase						)

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

       assert image.shape == (1, 512, 512, 3)
       UpperCamelCase__					    =   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 		_a       (self						)		->   str:





       '''simple docstring'''





       UpperCamelCase__					    =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,					provider='''CPUExecutionProvider'''						)
       UpperCamelCase__					    =   DPMSolverMultistepScheduler.from_config(pipe.scheduler.config						)
       pipe.set_progress_bar_config(disable=_lowercase						)

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

       assert image.shape == (1, 512, 512, 3)
       UpperCamelCase__					    =   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 		_a       (self						)		->   Union[str, Any]:





       '''simple docstring'''





       UpperCamelCase__					    =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,					provider='''CPUExecutionProvider'''						)
       UpperCamelCase__					    =   EulerDiscreteScheduler.from_config(pipe.scheduler.config						)
       pipe.set_progress_bar_config(disable=_lowercase						)

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

       assert image.shape == (1, 512, 512, 3)
       UpperCamelCase__					    =   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 		_a       (self						)		->   List[Any]:





       '''simple docstring'''





       UpperCamelCase__					    =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,					provider='''CPUExecutionProvider'''						)
       UpperCamelCase__					    =   EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config						)
       pipe.set_progress_bar_config(disable=_lowercase						)

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

       assert image.shape == (1, 512, 512, 3)
       UpperCamelCase__					    =   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      _A (     unittest.TestCase				):






  @property
  def 		_a       (self						)		->   List[str]:





       '''simple docstring'''





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






  @property
  def 		_a       (self						)		->   Dict:





       '''simple docstring'''





       UpperCamelCase__					    =   ort.SessionOptions()
       UpperCamelCase__					    =   False
       return options






  def 		_a       (self						)		->   Dict:





       '''simple docstring'''





       UpperCamelCase__					    =   load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/img2img/sketch-mountains-input.jpg'''						)
       UpperCamelCase__					    =   init_image.resize((128, 128)						)
       # using the PNDM scheduler by default
       UpperCamelCase__					    =   OnnxStableDiffusionUpscalePipeline.from_pretrained(
           '''ssube/stable-diffusion-x4-upscaler-onnx''' ,					provider=self.gpu_provider ,					sess_options=self.gpu_options ,					)
       pipe.set_progress_bar_config(disable=_lowercase						)

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

       UpperCamelCase__					    =   torch.manual_seed(0						)
       UpperCamelCase__					    =   pipe(
           prompt=_lowercase ,					image=_lowercase ,					guidance_scale=7.5 ,					num_inference_steps=10 ,					generator=_lowercase ,					output_type='''np''' ,					)
       UpperCamelCase__					    =   output.images
       UpperCamelCase__					    =   images[0, 255:258, 383:386, -1]

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





       '''simple docstring'''





       UpperCamelCase__					    =   load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/img2img/sketch-mountains-input.jpg'''						)
       UpperCamelCase__					    =   init_image.resize((128, 128)						)
       UpperCamelCase__					    =   LMSDiscreteScheduler.from_pretrained(
           '''ssube/stable-diffusion-x4-upscaler-onnx''' ,					subfolder='''scheduler'''						)
       UpperCamelCase__					    =   OnnxStableDiffusionUpscalePipeline.from_pretrained(
           '''ssube/stable-diffusion-x4-upscaler-onnx''' ,					scheduler=_lowercase ,					provider=self.gpu_provider ,					sess_options=self.gpu_options ,					)
       pipe.set_progress_bar_config(disable=_lowercase						)

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

       UpperCamelCase__					    =   torch.manual_seed(0						)
       UpperCamelCase__					    =   pipe(
           prompt=_lowercase ,					image=_lowercase ,					guidance_scale=7.5 ,					num_inference_steps=20 ,					generator=_lowercase ,					output_type='''np''' ,					)
       UpperCamelCase__					    =   output.images
       UpperCamelCase__					    =   images[0, 255:258, 383:386, -1]

       assert images.shape == (1, 512, 512, 3)
       UpperCamelCase__					    =   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






'''simple docstring'''

def 							_UpperCamelCase				(   lowerCAmelCase__:					str   )      -> bool:
							return credit_card_number.startswith(('34', '35', '37', '4', '5', '6')   )




def 							_UpperCamelCase				(   lowerCAmelCase__:					str   )      -> bool:
							SCREAMING_SNAKE_CASE_				=				credit_card_number
							SCREAMING_SNAKE_CASE_				=				0
							SCREAMING_SNAKE_CASE_				=				len(lowerCAmelCase__   ) - 2
							for i in range(lowerCAmelCase__		,-1		,-2   ):
														#  double the value of every second digit
														SCREAMING_SNAKE_CASE_				=				int(cc_number[i]   )
														digit *= 2
														# If doubling of a number results in a two digit number
														# i.e greater than 9(e.g., 6 × 2 = 12),
														# then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6),
														# to get a single digit number.
														if digit > 9:
																					digit %= 10
																					digit += 1
														SCREAMING_SNAKE_CASE_				=				cc_number[:i] + str(lowerCAmelCase__   ) + cc_number[i + 1 :]
														total += digit

							# Sum up the remaining digits
							for i in range(len(lowerCAmelCase__   ) - 1		,-1		,-2   ):
														total += int(cc_number[i]   )

							return total % 10 == 0




def 							_UpperCamelCase				(   lowerCAmelCase__:					str   )      -> bool:
							SCREAMING_SNAKE_CASE_				=				F"""{credit_card_number} is an invalid credit card number because"""
							if not credit_card_number.isdigit():
														print(F"""{error_message} it has nonnumerical characters."""   )
														return False

							if not 13 <= len(lowerCAmelCase__   ) <= 16:
														print(F"""{error_message} of its length."""   )
														return False

							if not validate_initial_digits(lowerCAmelCase__   ):
														print(F"""{error_message} of its first two digits."""   )
														return False

							if not luhn_validation(lowerCAmelCase__   ):
														print(F"""{error_message} it fails the Luhn check."""   )
														return False

							print(F"""{credit_card_number} is a valid credit card number."""   )
							return True


if __name__ == "__main__":
							import doctest

							doctest.testmod()
							validate_credit_card_number("4111111111111111")
							validate_credit_card_number("32323")





