






"""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        a     (   __snake_case,				unittest.TestCase	):
    # TODO: is there an appropriate internal test set?
    UpperCAmelCase_ :     int	     ="""ssube/stable-diffusion-x4-upscaler-onnx"""







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

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

      # started as 128, should now be 512
      assert image.shape == (1, 5_1_2, 5_1_2, 3)
      lowercase							    =       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       ):
      lowercase							    =       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,		provider='CPUExecutionProvider'       )
      lowercase							    =       PNDMScheduler.from_config(pipe.scheduler.config							,		skip_prk_steps=_lowerCamelCase       )
      pipe.set_progress_bar_config(disable=_lowerCamelCase       )

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

      assert image.shape == (1, 5_1_2, 5_1_2, 3)
      lowercase							    =       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       ):
      lowercase							    =       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,		provider='CPUExecutionProvider'       )
      lowercase							    =       DPMSolverMultistepScheduler.from_config(pipe.scheduler.config       )
      pipe.set_progress_bar_config(disable=_lowerCamelCase       )

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

      assert image.shape == (1, 5_1_2, 5_1_2, 3)
      lowercase							    =       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       ):
      lowercase							    =       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,		provider='CPUExecutionProvider'       )
      lowercase							    =       EulerDiscreteScheduler.from_config(pipe.scheduler.config       )
      pipe.set_progress_bar_config(disable=_lowerCamelCase       )

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

      assert image.shape == (1, 5_1_2, 5_1_2, 3)
      lowercase							    =       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       ):
      lowercase							    =       OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint							,		provider='CPUExecutionProvider'       )
      lowercase							    =       EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config       )
      pipe.set_progress_bar_config(disable=_lowerCamelCase       )

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

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







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







    @property
    def 			UpperCamelCase_      (			self       ):
      lowercase							    =       ort.SessionOptions()
      lowercase							    =       False
      return options







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

      lowercase							    =       'A fantasy landscape, trending on artstation'

      lowercase							    =       torch.manual_seed(0       )
      lowercase							    =       pipe(
          prompt=_lowerCamelCase							,		image=_lowerCamelCase							,		guidance_scale=7.5							,		num_inference_steps=1_0							,		generator=_lowerCamelCase							,		output_type='np'							,		)
      lowercase							    =       output.images
      lowercase							    =       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)
      lowercase							    =       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       ):
      lowercase							    =       load_image(
          'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
          '/img2img/sketch-mountains-input.jpg'       )
      lowercase							    =       init_image.resize((1_2_8, 1_2_8)       )
      lowercase							    =       LMSDiscreteScheduler.from_pretrained(
          'ssube/stable-diffusion-x4-upscaler-onnx'							,		subfolder='scheduler'       )
      lowercase							    =       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       )

      lowercase							    =       'A fantasy landscape, trending on artstation'

      lowercase							    =       torch.manual_seed(0       )
      lowercase							    =       pipe(
          prompt=_lowerCamelCase							,		image=_lowerCamelCase							,		guidance_scale=7.5							,		num_inference_steps=2_0							,		generator=_lowerCamelCase							,		output_type='np'							,		)
      lowercase							    =       output.images
      lowercase							    =       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)
      lowercase							    =       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





import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


snake_case_			  = datasets.utils.logging.get_logger(__name__)

snake_case_			  = ['''names''', '''prefix''']
snake_case_			  = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols''']
snake_case_			  = ['''encoding_errors''', '''on_bad_lines''']
snake_case_			  = ['''date_format''']


@dataclass
class       SCREAMING_SNAKE_CASE__					(datasets.BuilderConfig     ):
    __lowerCamelCase						:       str														=     ","
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[Union[int, List[int], str]]														=     "infer"
    __lowerCamelCase						:       Optional[List[str]]														=     None
    __lowerCamelCase						:       Optional[List[str]]														=     None
    __lowerCamelCase						:       Optional[Union[int, str, List[int], List[str]]]														=     None
    __lowerCamelCase						:       Optional[Union[List[int], List[str]]]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       Optional[Literal["c", "python", "pyarrow"]]														=     None
    __lowerCamelCase						:       Dict[Union[int, str], Callable[[Any], Any]]														=     None
    __lowerCamelCase						:       Optional[list]														=     None
    __lowerCamelCase						:       Optional[list]														=     None
    __lowerCamelCase						:       bool														=     False
    __lowerCamelCase						:       Optional[Union[int, List[int]]]														=     None
    __lowerCamelCase						:       Optional[int]														=     None
    __lowerCamelCase						:       Optional[Union[str, List[str]]]														=     None
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     False
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       str														=     "."
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       str														=     '"'
    __lowerCamelCase						:       int														=     0
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       int														=     0
    __lowerCamelCase						:       bool														=     True
    __lowerCamelCase						:       bool														=     False
    __lowerCamelCase						:       Optional[str]														=     None
    __lowerCamelCase						:       int														=     1_0000
    __lowerCamelCase						:       Optional[datasets.Features]														=     None
    __lowerCamelCase						:       Optional[str]														=     "strict"
    __lowerCamelCase						:       Literal["error", "warn", "skip"]														=     "error"
    __lowerCamelCase						:       Optional[str]														=     None





    def       snake_case_				(      self):
         if self.delimiter is not None:
              lowercase__    :   List[Any]      =       self.delimiter
         if self.column_names is not None:
              lowercase__    :   Optional[int]      =       self.column_names





    @property
    def       snake_case_				(      self):
         lowercase__    :   Dict      =       {
             'sep': self.sep,
             'header': self.header,
             'names': self.names,
             'index_col': self.index_col,
             'usecols': self.usecols,
             'prefix': self.prefix,
             'mangle_dupe_cols': self.mangle_dupe_cols,
             'engine': self.engine,
             'converters': self.converters,
             'true_values': self.true_values,
             'false_values': self.false_values,
             'skipinitialspace': self.skipinitialspace,
             'skiprows': self.skiprows,
             'nrows': self.nrows,
             'na_values': self.na_values,
             'keep_default_na': self.keep_default_na,
             'na_filter': self.na_filter,
             'verbose': self.verbose,
             'skip_blank_lines': self.skip_blank_lines,
             'thousands': self.thousands,
             'decimal': self.decimal,
             'lineterminator': self.lineterminator,
             'quotechar': self.quotechar,
             'quoting': self.quoting,
             'escapechar': self.escapechar,
             'comment': self.comment,
             'encoding': self.encoding,
             'dialect': self.dialect,
             'error_bad_lines': self.error_bad_lines,
             'warn_bad_lines': self.warn_bad_lines,
             'skipfooter': self.skipfooter,
             'doublequote': self.doublequote,
             'memory_map': self.memory_map,
             'float_precision': self.float_precision,
             'chunksize': self.chunksize,
             'encoding_errors': self.encoding_errors,
             'on_bad_lines': self.on_bad_lines,
             'date_format': self.date_format,
         }

         # some kwargs must not be passed if they don't have a default value
         # some others are deprecated and we can also not pass them if they are the default value
         for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
              if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()						,   a):
                   del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
         if not (datasets.config.PANDAS_VERSION.major >= 2):
              for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
                   del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
         if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
              for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
                   del pd_read_csv_kwargs[pd_read_csv_parameter]

         return pd_read_csv_kwargs



class       SCREAMING_SNAKE_CASE__					(datasets.ArrowBasedBuilder     ):
    __lowerCamelCase						:       Optional[Any]														=     CsvConfig





    def       snake_case_				(      self):
         return datasets.DatasetInfo(features=self.config.features)





    def       snake_case_				(      self						,   a):
         if not self.config.data_files:
              raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""")
         lowercase__    :   Any      =       dl_manager.download_and_extract(self.config.data_files)
         if isinstance(a						,   (str, list, tuple)):
              lowercase__    :   List[str]      =       data_files
              if isinstance(a						,   a):
                   lowercase__    :   Optional[Any]      =       [files]
              lowercase__    :   Optional[int]      =       [dl_manager.iter_files(a) for file in files]
              return [datasets.SplitGenerator(name=datasets.Split.TRAIN						,   gen_kwargs={'files': files})]
         lowercase__    :   int      =       []
         for split_name, files in data_files.items():
              if isinstance(a						,   a):
                   lowercase__    :   Optional[int]      =       [files]
              lowercase__    :   Tuple      =       [dl_manager.iter_files(a) for file in files]
              splits.append(datasets.SplitGenerator(name=a						,   gen_kwargs={'files': files}))
         return splits





    def       snake_case_				(      self						,   a):
         if self.config.features is not None:
              lowercase__    :   Optional[int]      =       self.config.features.arrow_schema
              if all(not require_storage_cast(a) for feature in self.config.features.values()):
                   # cheaper cast
                   lowercase__    :   Dict      =       pa.Table.from_arrays([pa_table[field.name] for field in schema]						,   schema=a)
              else:
                   # more expensive cast; allows str <-> int/float or str to Audio for example
                   lowercase__    :   Optional[Any]      =       table_cast(a						,   a)
         return pa_table





    def       snake_case_				(      self						,   a):
         lowercase__    :   List[Any]      =       self.config.features.arrow_schema if self.config.features else None
         # dtype allows reading an int column as str
         lowercase__    :   Optional[int]      =       (
             {
                 name: dtype.to_pandas_dtype() if not require_storage_cast(a) else object
                 for name, dtype, feature in zip(schema.names						,   schema.types						,   self.config.features.values())
             }
             if schema is not None
             else None
         )
         for file_idx, file in enumerate(itertools.chain.from_iterable(a)):
              lowercase__    :   int      =       pd.read_csv(a						,   iterator=a						,   dtype=a						,   **self.config.pd_read_csv_kwargs)
              try:
                   for batch_idx, df in enumerate(a):
                        lowercase__    :   List[str]      =       pa.Table.from_pandas(a)
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                        yield (file_idx, batch_idx), self._cast_table(a)
              except ValueError as e:
                   logger.error(f"""Failed to read file '{file}' with error {type(a)}: {e}""")
                   raise

