

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        lowerCAmelCase__  (					__magic_name__				,							unittest.TestCase			):



       '''simple docstring'''







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

       def     __UpperCamelCase     (							self ,   lowercase__=0     ):







             '''simple docstring'''



             __A    =floats_tensor((1, 3, 1_2_8, 1_2_8) ,   rng=random.Random(lowercase__     )     )
             __A    =torch.manual_seed(lowercase__     )
             __A    ={
                 '''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    =OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,   provider='''CPUExecutionProvider'''     )
             pipe.set_progress_bar_config(disable=lowercase__     )

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

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







             '''simple docstring'''



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

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

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







             '''simple docstring'''



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

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

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







             '''simple docstring'''



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

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

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







             '''simple docstring'''



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

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

             assert image.shape == (1, 5_1_2, 5_1_2, 3)
             __A    =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        lowerCAmelCase__  (					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    =ort.SessionOptions()
             __A    =False
             return options

       def     __UpperCamelCase     (							self     ):







             '''simple docstring'''



             __A    =load_image(
                 '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
                 '''/img2img/sketch-mountains-input.jpg'''     )
             __A    =init_image.resize((1_2_8, 1_2_8)     )
             # using the PNDM scheduler by default
             __A    =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    ='''A fantasy landscape, trending on artstation'''

             __A    =torch.manual_seed(0     )
             __A    =pipe(
                 prompt=lowercase__ ,   image=lowercase__ ,   guidance_scale=7.5 ,   num_inference_steps=1_0 ,   generator=lowercase__ ,   output_type='''np''' ,   )
             __A    =output.images
             __A    =images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

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







             '''simple docstring'''



             __A    =load_image(
                 '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
                 '''/img2img/sketch-mountains-input.jpg'''     )
             __A    =init_image.resize((1_2_8, 1_2_8)     )
             __A    =LMSDiscreteScheduler.from_pretrained(
                 '''ssube/stable-diffusion-x4-upscaler-onnx''' ,   subfolder='''scheduler'''     )
             __A    =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    ='''A fantasy landscape, trending on artstation'''

             __A    =torch.manual_seed(0     )
             __A    =pipe(
                 prompt=lowercase__ ,   image=lowercase__ ,   guidance_scale=7.5 ,   num_inference_steps=2_0 ,   generator=lowercase__ ,   output_type='''np''' ,   )
             __A    =output.images
             __A    =images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

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





import inspect
import re
from hashlib import shaaaa
from typing import Dict, List

from .arrow import arrow
from .audiofolder import audiofolder
from .csv import csv
from .imagefolder import imagefolder
from .json import json
from .pandas import pandas
from .parquet import parquet
from .sql import sql  # noqa F401
from .text import text





def      A__					(			__A  :						List[str]			)					->str:
      __A    =[]
      for line in lines:
            __A    =re.sub(r'''#.*'''     ,				''''''     ,				__A			)  # remove comments
            if line:
                  filtered_lines.append(__A			)
      __A    ='''\n'''.join(__A			)

      # Make a hash from all this code
      __A    =full_str.encode('''utf-8'''			)
      return shaaaa(__A			).hexdigest()


# get importable module names and hash for caching
_lowerCamelCase      :					Dict					    =      {
    '''csv''': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())),
    '''json''': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())),
    '''pandas''': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())),
    '''parquet''': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())),
    '''arrow''': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())),
    '''text''': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())),
    '''imagefolder''': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())),
    '''audiofolder''': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())),
}

# Used to infer the module to use based on the data files extensions
_lowerCamelCase      :					int					    =      {
    '''.csv''': ('''csv''', {}),
    '''.tsv''': ('''csv''', {'''sep''': '''\t'''}),
    '''.json''': ('''json''', {}),
    '''.jsonl''': ('''json''', {}),
    '''.parquet''': ('''parquet''', {}),
    '''.arrow''': ('''arrow''', {}),
    '''.txt''': ('''text''', {}),
}
_EXTENSION_TO_MODULE.update({ext: ('''imagefolder''', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('''imagefolder''', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext: ('''audiofolder''', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('''audiofolder''', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
_lowerCamelCase      :					List[str]					    =      {'''imagefolder''', '''audiofolder'''}

# Used to filter data files based on extensions given a module name
_lowerCamelCase      :					Dict[str, List[str]]					    =      {}
for _ext, (_module, _) in _EXTENSION_TO_MODULE.items():
   _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext)

_MODULE_TO_EXTENSIONS["imagefolder"].append('''.zip''')


_MODULE_TO_EXTENSIONS["audiofolder"].append('''.zip''')


