


# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse

from ...utils.dataclasses import (
    ComputeEnvironment,
    DistributedType,
    DynamoBackend,
    PrecisionType,
    SageMakerDistributedType,
)
from ..menu import BulletMenu


SCREAMING_SNAKE_CASE__					:     List[Any]       =     [
    'EAGER',
    'AOT_EAGER',
    'INDUCTOR',
    'NVFUSER',
    'AOT_NVFUSER',
    'AOT_CUDAGRAPHS',
    'OFI',
    'FX2TRT',
    'ONNXRT',
    'IPEX',
]




def    a__    (		snake_case__					:							int						,   snake_case__					:							Optional[Any]=None						,   snake_case__					:							List[Any]=None						,   snake_case__					:							Union[str, Any]=None     ):
  _UpperCAmelCase		:							List[Any]							=     True
  while ask_again:
    _UpperCAmelCase		:							Any							=     input(snake_case__     )
    try:
      if default is not None and len(snake_case__     ) == 0:
        return default
      return convert_value(snake_case__     ) if convert_value is not None else result
    except Exception:
      if error_message is not None:
        print(snake_case__     )




def    a__    (		snake_case__					:							Union[str, Any]						,   snake_case__					:							str=[]						,   snake_case__					:							Tuple=None						,   snake_case__					:							Any=0     ):
  _UpperCAmelCase		:							Union[str, Any]							=     BulletMenu(snake_case__						,   snake_case__     )
  _UpperCAmelCase		:							str							=     menu.run(default_choice=snake_case__     )
  return convert_value(snake_case__     ) if convert_value is not None else result




def    a__    (		snake_case__					:							Any     ):
  _UpperCAmelCase		:							Optional[int]							=     int(snake_case__     )
  return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value]     )




def    a__    (		snake_case__					:							int     ):
  _UpperCAmelCase		:							Any							=     int(snake_case__     )
  return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value]     )




def    a__    (		snake_case__					:							Optional[int]     ):
  _UpperCAmelCase		:							Union[str, Any]							=     int(snake_case__     )
  return DynamoBackend(DYNAMO_BACKENDS[value]     ).value




def    a__    (		snake_case__					:							List[Any]     ):
  _UpperCAmelCase		:							str							=     int(snake_case__     )
  return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value]     )




def    a__    (		snake_case__					:							List[str]     ):
  _UpperCAmelCase		:							int							=     int(snake_case__     )
  return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value]     )




def    a__    (		snake_case__					:							Dict     ):
  return {"yes": True, "no": False}[value.lower()]





class 		_SCREAMING_SNAKE_CASE     (						argparse.RawDescriptionHelpFormatter     ):


     def        __snake_case(  self							,					A_							,					A_							,					A_							,					A_    ):
       _UpperCAmelCase		:							Optional[Any]							=     super()._format_usage(A_							,					A_							,					A_							,					A_    )
       _UpperCAmelCase		:							Optional[int]							=     usage.replace("""<command> [<args>] """							,					""""""    )
       return usage









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 		_SCREAMING_SNAKE_CASE     (						A							,	unittest.TestCase     ):
     # TODO: is there an appropriate internal test set?
     __SCREAMING_SNAKE_CASE     					=    '''ssube/stable-diffusion-x4-upscaler-onnx'''


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

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

       # started as 128, should now be 512
       assert image.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							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 - expected_slice    ).max() < 1e-1


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							int							=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,					provider="""CPUExecutionProvider"""    )
       _UpperCAmelCase		:							Tuple							=     PNDMScheduler.from_config(pipe.scheduler.config							,					skip_prk_steps=A_    )
       pipe.set_progress_bar_config(disable=A_    )

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

       assert image.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							Optional[Any]							=     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        __snake_case(  self    ):
       _UpperCAmelCase		:							List[str]							=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,					provider="""CPUExecutionProvider"""    )
       _UpperCAmelCase		:							Dict							=     DPMSolverMultistepScheduler.from_config(pipe.scheduler.config    )
       pipe.set_progress_bar_config(disable=A_    )

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

       assert image.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							Tuple							=     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        __snake_case(  self    ):
       _UpperCAmelCase		:							Tuple							=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,					provider="""CPUExecutionProvider"""    )
       _UpperCAmelCase		:							Dict							=     EulerDiscreteScheduler.from_config(pipe.scheduler.config    )
       pipe.set_progress_bar_config(disable=A_    )

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

       assert image.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							List[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        __snake_case(  self    ):
       _UpperCAmelCase		:							List[str]							=     OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,					provider="""CPUExecutionProvider"""    )
       _UpperCAmelCase		:							List[Any]							=     EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config    )
       pipe.set_progress_bar_config(disable=A_    )

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

       assert image.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							Tuple							=     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 		_SCREAMING_SNAKE_CASE     (						unittest.TestCase     ):


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


     @property
     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[str]							=     ort.SessionOptions()
       _UpperCAmelCase		:							Union[str, Any]							=     False
       return options


     def        __snake_case(  self    ):
       _UpperCAmelCase		:							List[Any]							=     load_image(
           """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
           """/img2img/sketch-mountains-input.jpg"""    )
       _UpperCAmelCase		:							Any							=     init_image.resize((1_28, 1_28)    )
       # using the PNDM scheduler by default
       _UpperCAmelCase		:							Union[str, Any]							=     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_    )

       _UpperCAmelCase		:							Union[str, Any]							=     """A fantasy landscape, trending on artstation"""

       _UpperCAmelCase		:							Tuple							=     torch.manual_seed(0    )
       _UpperCAmelCase		:							Tuple							=     pipe(
           prompt=A_							,					image=A_							,					guidance_scale=7.5							,					num_inference_steps=10							,					generator=A_							,					output_type="""np"""							,					)
       _UpperCAmelCase		:							Dict							=     output.images
       _UpperCAmelCase		:							List[Any]							=     images[0, 2_55:2_58, 3_83:3_86, -1]

       assert images.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							List[str]							=     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        __snake_case(  self    ):
       _UpperCAmelCase		:							List[str]							=     load_image(
           """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
           """/img2img/sketch-mountains-input.jpg"""    )
       _UpperCAmelCase		:							Optional[int]							=     init_image.resize((1_28, 1_28)    )
       _UpperCAmelCase		:							Optional[int]							=     LMSDiscreteScheduler.from_pretrained(
           """ssube/stable-diffusion-x4-upscaler-onnx"""							,					subfolder="""scheduler"""    )
       _UpperCAmelCase		:							Union[str, Any]							=     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_    )

       _UpperCAmelCase		:							Union[str, Any]							=     """A fantasy landscape, trending on artstation"""

       _UpperCAmelCase		:							str							=     torch.manual_seed(0    )
       _UpperCAmelCase		:							Optional[int]							=     pipe(
           prompt=A_							,					image=A_							,					guidance_scale=7.5							,					num_inference_steps=20							,					generator=A_							,					output_type="""np"""							,					)
       _UpperCAmelCase		:							Dict							=     output.images
       _UpperCAmelCase		:							Dict							=     images[0, 2_55:2_58, 3_83:3_86, -1]

       assert images.shape == (1, 5_12, 5_12, 3)
       _UpperCAmelCase		:							Optional[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





