


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__     ( A__				,		unittest.TestCase  ):



  """simple docstring"""



  _lowercase									=		'ssube/stable-diffusion-x4-upscaler-onnx'

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

        a__	:  Optional[Any]     =   self.get_dummy_inputs()
        a__	:  Any     =   pipe(**lowerCamelCase__       ).images
        a__	:  Dict     =   image[0, -3:, -3:, -1].flatten()

        # started as 128, should now be 512
        assert image.shape == (1, 512, 512, 3)
        a__	:  Union[str, Any]     =   np.array(
            [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223]       )
        assert np.abs(image_slice - expected_slice       ).max() < 1E-1

  def    _UpperCamelCase( self			:  Union[str, Any]       ):
        a__	:  Optional[Any]     =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider="CPUExecutionProvider"       )
        a__	:  List[Any]     =   PNDMScheduler.from_config(pipe.scheduler.config				,				skip_prk_steps=lowerCamelCase__       )
        pipe.set_progress_bar_config(disable=lowerCamelCase__       )

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

        assert image.shape == (1, 512, 512, 3)
        a__	:  Tuple     =   np.array(
            [0.689_8892, 0.5924_0556, 0.5249_9527, 0.5886_6215, 0.5225_8235, 0.5257_2715, 0.6241_4473, 0.617_4387, 0.621_4964]       )
        assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-1

  def    _UpperCamelCase( self			:  List[Any]       ):
        a__	:  List[Any]     =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider="CPUExecutionProvider"       )
        a__	:  List[str]     =   DPMSolverMultistepScheduler.from_config(pipe.scheduler.config       )
        pipe.set_progress_bar_config(disable=lowerCamelCase__       )

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

        assert image.shape == (1, 512, 512, 3)
        a__	:  Optional[int]     =   np.array(
            [0.765_9278, 0.7643_7664, 0.7557_9107, 0.769_1116, 0.7766_6986, 0.772_7672, 0.775_8664, 0.781_2226, 0.7694_2515]       )

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

  def    _UpperCamelCase( self			:  List[str]       ):
        a__	:  Optional[Any]     =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider="CPUExecutionProvider"       )
        a__	:  Union[str, Any]     =   EulerDiscreteScheduler.from_config(pipe.scheduler.config       )
        pipe.set_progress_bar_config(disable=lowerCamelCase__       )

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

        assert image.shape == (1, 512, 512, 3)
        a__	:  Optional[int]     =   np.array(
            [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223]       )
        assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-1

  def    _UpperCamelCase( self			:  Any       ):
        a__	:  List[str]     =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider="CPUExecutionProvider"       )
        a__	:  Any     =   EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config       )
        pipe.set_progress_bar_config(disable=lowerCamelCase__       )

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

        assert image.shape == (1, 512, 512, 3)
        a__	:  Optional[int]     =   np.array(
            [0.7742_4496, 0.77_3601, 0.764_5288, 0.776_9598, 0.777_2739, 0.773_8688, 0.7818_7233, 0.7787_9584, 0.76_7043]       )

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




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



  """simple docstring"""



  @property
  def    _UpperCamelCase( self			:  Any       ):
        return (
            "CUDAExecutionProvider",
            {
                "gpu_mem_limit": "15000000000",  # 15GB
                "arena_extend_strategy": "kSameAsRequested",
            },
        )

  @property
  def    _UpperCamelCase( self			:  Any       ):
        a__	:  Any     =   ort.SessionOptions()
        a__	:  Tuple     =   False
        return options

  def    _UpperCamelCase( self			:  List[Any]       ):
        a__	:  Optional[Any]     =   load_image(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
            "/img2img/sketch-mountains-input.jpg"       )
        a__	:  int     =   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=lowerCamelCase__       )

        a__	:  Any     =   "A fantasy landscape, trending on artstation"

        a__	:  Dict     =   torch.manual_seed(0       )
        a__	:  Tuple     =   pipe(
            prompt=lowerCamelCase__				,				image=lowerCamelCase__				,				guidance_scale=7.5				,				num_inference_steps=10				,				generator=lowerCamelCase__				,				output_type="np"				,				)
        a__	:  Any     =   output.images
        a__	:  Any     =   images[0, 255:258, 383:386, -1]

        assert images.shape == (1, 512, 512, 3)
        a__	:  List[str]     =   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    _UpperCamelCase( self			:  Optional[int]       ):
        a__	:  Optional[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)       )
        a__	:  Optional[int]     =   LMSDiscreteScheduler.from_pretrained(
            "ssube/stable-diffusion-x4-upscaler-onnx"				,				subfolder="scheduler"       )
        a__	:  Optional[int]     =   OnnxStableDiffusionUpscalePipeline.from_pretrained(
            "ssube/stable-diffusion-x4-upscaler-onnx"				,				scheduler=lowerCamelCase__				,				provider=self.gpu_provider				,				sess_options=self.gpu_options				,				)
        pipe.set_progress_bar_config(disable=lowerCamelCase__       )

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

        a__	:  Optional[int]     =   torch.manual_seed(0       )
        a__	:  Tuple     =   pipe(
            prompt=lowerCamelCase__				,				image=lowerCamelCase__				,				guidance_scale=7.5				,				num_inference_steps=20				,				generator=lowerCamelCase__				,				output_type="np"				,				)
        a__	:  Dict     =   output.images
        a__	:  Tuple     =   images[0, 255:258, 383:386, -1]

        assert images.shape == (1, 512, 512, 3)
        a__	:  Tuple     =   np.array(
            [0.5017_3753, 0.5022_3356, 0.50_2039, 0.5023_3036, 0.502_3725, 0.502_2601, 0.501_8758, 0.5023_4085, 0.5024_1566]       )
        # 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'''




from . import (
    albert,
    align,
    altclip,
    audio_spectrogram_transformer,
    auto,
    autoformer,
    bark,
    bart,
    barthez,
    bartpho,
    beit,
    bert,
    bert_generation,
    bert_japanese,
    bertweet,
    big_bird,
    bigbird_pegasus,
    biogpt,
    bit,
    blenderbot,
    blenderbot_small,
    blip,
    blip_a,
    bloom,
    bridgetower,
    byta,
    camembert,
    canine,
    chinese_clip,
    clap,
    clip,
    clipseg,
    codegen,
    conditional_detr,
    convbert,
    convnext,
    convnextva,
    cpm,
    cpmant,
    ctrl,
    cvt,
    dataavec,
    deberta,
    deberta_va,
    decision_transformer,
    deformable_detr,
    deit,
    deprecated,
    deta,
    detr,
    dialogpt,
    dinat,
    distilbert,
    dit,
    donut,
    dpr,
    dpt,
    efficientformer,
    efficientnet,
    electra,
    encodec,
    encoder_decoder,
    ernie,
    ernie_m,
    esm,
    falcon,
    flaubert,
    flava,
    fnet,
    focalnet,
    fsmt,
    funnel,
    git,
    glpn,
    gpta,
    gpt_bigcode,
    gpt_neo,
    gpt_neox,
    gpt_neox_japanese,
    gpt_swa,
    gptj,
    gptsan_japanese,
    graphormer,
    groupvit,
    herbert,
    hubert,
    ibert,
    imagegpt,
    informer,
    instructblip,
    jukebox,
    layoutlm,
    layoutlmva,
    layoutlmva,
    layoutxlm,
    led,
    levit,
    lilt,
    llama,
    longformer,
    longta,
    luke,
    lxmert,
    mam_aaa,
    marian,
    markuplm,
    maskaformer,
    maskformer,
    mbart,
    mbartaa,
    mega,
    megatron_bert,
    megatron_gpta,
    mgp_str,
    mluke,
    mobilebert,
    mobilenet_va,
    mobilenet_va,
    mobilevit,
    mobilevitva,
    mpnet,
    mra,
    mta,
    musicgen,
    mvp,
    nat,
    nezha,
    nllb,
    nllb_moe,
    nystromformer,
    oneformer,
    open_llama,
    openai,
    opt,
    owlvit,
    pegasus,
    pegasus_x,
    perceiver,
    phobert,
    pixastruct,
    plbart,
    poolformer,
    prophetnet,
    qdqbert,
    rag,
    realm,
    reformer,
    regnet,
    rembert,
    resnet,
    roberta,
    roberta_prelayernorm,
    roc_bert,
    roformer,
    rwkv,
    sam,
    segformer,
    sew,
    sew_d,
    speech_encoder_decoder,
    speech_to_text,
    speech_to_text_a,
    speechta,
    splinter,
    squeezebert,
    swiftformer,
    swin,
    swinasr,
    swinva,
    switch_transformers,
    ta,
    table_transformer,
    tapas,
    time_series_transformer,
    timesformer,
    timm_backbone,
    transfo_xl,
    trocr,
    tvlt,
    umta,
    unispeech,
    unispeech_sat,
    upernet,
    videomae,
    vilt,
    vision_encoder_decoder,
    vision_text_dual_encoder,
    visual_bert,
    vit,
    vit_hybrid,
    vit_mae,
    vit_msn,
    vivit,
    wavaveca,
    wavaveca_conformer,
    wavaveca_phoneme,
    wavaveca_with_lm,
    wavlm,
    whisper,
    x_clip,
    xglm,
    xlm,
    xlm_prophetnet,
    xlm_roberta,
    xlm_roberta_xl,
    xlnet,
    xmod,
    yolos,
    yoso,
)

