





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





 """simple docstring"""


 _lowerCamelCase				=					"""ssube/stable-diffusion-x4-upscaler-onnx"""

 def  UpperCamelCase__(   self ,						__lowerCamelCase=0  ):



     '''simple docstring'''




     __A   :						Any									=					floats_tensor((1, 3, 128, 128) ,						rng=random.Random(lowercase_  )  )
     __A   :						List[str]									=					torch.manual_seed(lowercase_  )
     __A   :						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  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[Any]									=					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,						provider='''CPUExecutionProvider'''  )
     pipe.set_progress_bar_config(disable=lowercase_  )

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

     # started as 128, should now be 512
     assert image.shape == (1, 512, 512, 3)
     __A   :						Optional[int]									=					np.array(
         [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3]  )
     assert np.abs(image_slice - expected_slice  ).max() < 1e-1

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Dict									=					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,						provider='''CPUExecutionProvider'''  )
     __A   :						List[Any]									=					PNDMScheduler.from_config(pipe.scheduler.config ,						skip_prk_steps=lowercase_  )
     pipe.set_progress_bar_config(disable=lowercase_  )

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

     assert image.shape == (1, 512, 512, 3)
     __A   :						Dict									=					np.array(
         [0.6_8_9_8_8_9_2, 0.5_9_2_4_0_5_5_6, 0.5_2_4_9_9_5_2_7, 0.5_8_8_6_6_2_1_5, 0.5_2_2_5_8_2_3_5, 0.5_2_5_7_2_7_1_5, 0.6_2_4_1_4_4_7_3, 0.6_1_7_4_3_8_7, 0.6_2_1_4_9_6_4]  )
     assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-1

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Optional[int]									=					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,						provider='''CPUExecutionProvider'''  )
     __A   :						Tuple									=					DPMSolverMultistepScheduler.from_config(pipe.scheduler.config  )
     pipe.set_progress_bar_config(disable=lowercase_  )

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

     assert image.shape == (1, 512, 512, 3)
     __A   :						str									=					np.array(
         [0.7_6_5_9_2_7_8, 0.7_6_4_3_7_6_6_4, 0.7_5_5_7_9_1_0_7, 0.7_6_9_1_1_1_6, 0.7_7_6_6_6_9_8_6, 0.7_7_2_7_6_7_2, 0.7_7_5_8_6_6_4, 0.7_8_1_2_2_2_6, 0.7_6_9_4_2_5_1_5]  )

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

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




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

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

     assert image.shape == (1, 512, 512, 3)
     __A   :						Any									=					np.array(
         [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3]  )
     assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-1







 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




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

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

     assert image.shape == (1, 512, 512, 3)
     __A   :						Optional[int]									=					np.array(
         [0.7_7_4_2_4_4_9_6, 0.7_7_3_6_0_1, 0.7_6_4_5_2_8_8, 0.7_7_6_9_5_9_8, 0.7_7_7_2_7_3_9, 0.7_7_3_8_6_8_8, 0.7_8_1_8_7_2_3_3, 0.7_7_8_7_9_5_8_4, 0.7_6_7_0_4_3]  )

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






@nightly
@require_onnxruntime
@require_torch_gpu
class 		__snake_case (		unittest.TestCase					):





 """simple docstring"""


 @property
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




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

 @property
 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Optional[Any]									=					ort.SessionOptions()
     __A   :						List[Any]									=					False
     return options

 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						Any									=					load_image(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
         '''/img2img/sketch-mountains-input.jpg'''  )
     __A   :						Optional[Any]									=					init_image.resize((128, 128)  )
     # using the PNDM scheduler by default
     __A   :						Optional[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=lowercase_  )

     __A   :						List[str]									=					"""A fantasy landscape, trending on artstation"""

     __A   :						List[str]									=					torch.manual_seed(0  )
     __A   :						str									=					pipe(
         prompt=lowercase_ ,						image=lowercase_ ,						guidance_scale=7.5 ,						num_inference_steps=10 ,						generator=lowercase_ ,						output_type='''np''' ,						)
     __A   :						Optional[Any]									=					output.images
     __A   :						List[Any]									=					images[0, 255:258, 383:386, -1]

     assert images.shape == (1, 512, 512, 3)
     __A   :						Optional[Any]									=					np.array([0.4_8_8_3, 0.4_9_4_7, 0.4_9_8_0, 0.4_9_7_5, 0.4_9_8_2, 0.4_9_8_0, 0.5_0_0_0, 0.5_0_0_6, 0.4_9_7_2]  )
     # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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







 def  UpperCamelCase__(   self  ):



     '''simple docstring'''




     __A   :						List[Any]									=					load_image(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
         '''/img2img/sketch-mountains-input.jpg'''  )
     __A   :						Tuple									=					init_image.resize((128, 128)  )
     __A   :						Any									=					LMSDiscreteScheduler.from_pretrained(
         '''ssube/stable-diffusion-x4-upscaler-onnx''' ,						subfolder='''scheduler'''  )
     __A   :						List[Any]									=					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_  )

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

     __A   :						Optional[Any]									=					torch.manual_seed(0  )
     __A   :						Any									=					pipe(
         prompt=lowercase_ ,						image=lowercase_ ,						guidance_scale=7.5 ,						num_inference_steps=20 ,						generator=lowercase_ ,						output_type='''np''' ,						)
     __A   :						Dict									=					output.images
     __A   :						Union[str, Any]									=					images[0, 255:258, 383:386, -1]

     assert images.shape == (1, 512, 512, 3)
     __A   :						Union[str, Any]									=					np.array(
         [0.5_0_1_7_3_7_5_3, 0.5_0_2_2_3_3_5_6, 0.5_0_2_0_3_9, 0.5_0_2_3_3_0_3_6, 0.5_0_2_3_7_2_5, 0.5_0_2_2_6_0_1, 0.5_0_1_8_7_5_8, 0.5_0_2_3_4_0_8_5, 0.5_0_2_4_1_5_6_6]  )
     # 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 string

# frequency taken from https://en.wikipedia.org/wiki/Letter_frequency
a_			=      {
    """E""": 12.70,
    """T""": 9.06,
    """A""": 8.17,
    """O""": 7.51,
    """I""": 6.97,
    """N""": 6.75,
    """S""": 6.33,
    """H""": 6.09,
    """R""": 5.99,
    """D""": 4.25,
    """L""": 4.03,
    """C""": 2.78,
    """U""": 2.76,
    """M""": 2.41,
    """W""": 2.36,
    """F""": 2.23,
    """G""": 2.02,
    """Y""": 1.97,
    """P""": 1.93,
    """B""": 1.29,
    """V""": 0.98,
    """K""": 0.77,
    """J""": 0.15,
    """X""": 0.15,
    """Q""": 0.10,
    """Z""": 0.07,
}
a_			=      """ETAOINSHRDLCUMWFGYPBVKJXQZ"""
a_			=      """ABCDEFGHIJKLMNOPQRSTUVWXYZ"""







def 		__lowercase					(       snake_case_  :  str						)       ->dict[str, int]:



    '''simple docstring'''







    __A   :						Any									=					{letter: 0 for letter in string.ascii_uppercase}
    for letter in message.upper():
        if letter in LETTERS:
            letter_count[letter] += 1

    return letter_count







def 		__lowercase					(       snake_case_  :  tuple						)       ->str:



    '''simple docstring'''







    return x[0]







def 		__lowercase					(       snake_case_  :  str						)       ->str:



    '''simple docstring'''







    __A   :						Union[str, Any]									=					get_letter_count(snake_case_						)
    __A   :						dict[int, list[str]]									=					{
        freq: [] for letter, freq in letter_to_freq.items()
    }
    for letter in LETTERS:
        freq_to_letter[letter_to_freq[letter]].append(snake_case_						)

    __A   :						dict[int, str]									=					{}

    for freq in freq_to_letter:
        freq_to_letter[freq].sort(key=ETAOIN.find    ,reverse=snake_case_						)
        __A   :						Optional[int]									=					''''''.join(freq_to_letter[freq]						)

    __A   :						str									=					list(freq_to_letter_str.items()						)
    freq_pairs.sort(key=snake_case_    ,reverse=snake_case_						)

    __A   :						list[str]									=					[freq_pair[1] for freq_pair in freq_pairs]

    return "".join(snake_case_						)







def 		__lowercase					(       snake_case_  :  str						)       ->int:



    '''simple docstring'''







    __A   :						Any									=					get_frequency_order(snake_case_						)
    __A   :						str									=					0
    for common_letter in ETAOIN[:6]:
        if common_letter in freq_order[:6]:
            match_score += 1

    for uncommon_letter in ETAOIN[-6:]:
        if uncommon_letter in freq_order[-6:]:
            match_score += 1

    return match_score


if __name__ == "__main__":
       import doctest

       doctest.testmod()




