
import unittest

import numpy as np
import torch

from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


class 						__lowerCAmelCase	(	lowerCAmelCase_ , unittest.TestCase      ):



      """simple docstring"""







      A__	:			Any        =    DDIMPipeline
      A__	:			Any        =    UNCONDITIONAL_IMAGE_GENERATION_PARAMS
      A__	:			Tuple        =    PipelineTesterMixin.required_optional_params - {
          '''num_images_per_prompt''',
          '''latents''',
          '''callback''',
          '''callback_steps''',
      }
      A__	:			List[str]        =    UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
      A__	:			Tuple        =    False




      def 		snake_case_			(      self		:       int				):
          torch.manual_seed(0				)
          __lowercase		:			str	    =       UNetaDModel(
              block_out_channels=(32, 64)				,       layers_per_block=2				,       sample_size=32				,       in_channels=3				,       out_channels=3				,       down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')				,       up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')				,       )
          __lowercase		:			Optional[Any]	    =       DDIMScheduler()
          __lowercase		:			List[str]	    =       {'''unet''': unet, '''scheduler''': scheduler}
          return components




      def 		snake_case_			(      self		:       Optional[int]				,       _snake_case		:       Optional[int]				,       _snake_case		:       List[Any]=0				):
          if str(_snake_case				).startswith('''mps'''				):
              __lowercase		:			Union[str, Any]	    =       torch.manual_seed(_snake_case				)
          else:
              __lowercase		:			Tuple	    =       torch.Generator(device=_snake_case				).manual_seed(_snake_case				)
          __lowercase		:			List[str]	    =       {
              '''batch_size''': 1,
              '''generator''': generator,
              '''num_inference_steps''': 2,
              '''output_type''': '''numpy''',
          }
          return inputs




      def 		snake_case_			(      self		:       List[str]				):
          __lowercase		:			str	    =       '''cpu'''

          __lowercase		:			Tuple	    =       self.get_dummy_components()
          __lowercase		:			Optional[Any]	    =       self.pipeline_class(**_snake_case				)
          pipe.to(_snake_case				)
          pipe.set_progress_bar_config(disable=_snake_case				)

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

          self.assertEqual(image.shape				,       (1, 32, 32, 3)				)
          __lowercase		:			Any	    =       np.array(
              [1.0_0_0E0_0, 5.7_1_7E-0_1, 4.7_1_7E-0_1, 1.0_0_0E0_0, 0.0_0_0E0_0, 1.0_0_0E0_0, 3.0_0_0E-0_4, 0.0_0_0E0_0, 9.0_0_0E-0_4]				)
          __lowercase		:			int	    =       np.abs(image_slice.flatten() - expected_slice				).max()
          self.assertLessEqual(_snake_case				,       1E-3				)




      def 		snake_case_			(      self		:       List[str]				):
          super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3				)




      def 		snake_case_			(      self		:       Optional[int]				):
          super().test_save_load_local(expected_max_difference=3E-3				)




      def 		snake_case_			(      self		:       List[str]				):
          super().test_save_load_optional_components(expected_max_difference=3E-3				)




      def 		snake_case_			(      self		:       Union[str, Any]				):
          super().test_inference_batch_single_identical(expected_max_diff=3E-3				)






@slow
@require_torch_gpu
class 						__lowerCAmelCase	(	unittest.TestCase      ):



      """simple docstring"""







      def 		snake_case_			(      self		:       int				):
          __lowercase		:			List[Any]	    =       '''google/ddpm-cifar10-32'''

          __lowercase		:			Optional[Any]	    =       UNetaDModel.from_pretrained(_snake_case				)
          __lowercase		:			Optional[int]	    =       DDIMScheduler()

          __lowercase		:			Any	    =       DDIMPipeline(unet=_snake_case				,       scheduler=_snake_case				)
          ddim.to(_snake_case				)
          ddim.set_progress_bar_config(disable=_snake_case				)

          __lowercase		:			Union[str, Any]	    =       torch.manual_seed(0				)
          __lowercase		:			Optional[int]	    =       ddim(generator=_snake_case				,       eta=0.0				,       output_type='''numpy'''				).images

          __lowercase		:			Dict	    =       image[0, -3:, -3:, -1]

          assert image.shape == (1, 32, 32, 3)
          __lowercase		:			Optional[int]	    =       np.array([0.17_23, 0.16_17, 0.16_00, 0.16_26, 0.14_97, 0.15_13, 0.15_05, 0.14_42, 0.14_53]				)

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




      def 		snake_case_			(      self		:       Optional[Any]				):
          __lowercase		:			Union[str, Any]	    =       '''google/ddpm-ema-bedroom-256'''

          __lowercase		:			int	    =       UNetaDModel.from_pretrained(_snake_case				)
          __lowercase		:			List[Any]	    =       DDIMScheduler.from_pretrained(_snake_case				)

          __lowercase		:			List[Any]	    =       DDIMPipeline(unet=_snake_case				,       scheduler=_snake_case				)
          ddpm.to(_snake_case				)
          ddpm.set_progress_bar_config(disable=_snake_case				)

          __lowercase		:			List[str]	    =       torch.manual_seed(0				)
          __lowercase		:			List[Any]	    =       ddpm(generator=_snake_case				,       output_type='''numpy'''				).images

          __lowercase		:			Any	    =       image[0, -3:, -3:, -1]

          assert image.shape == (1, 256, 256, 3)
          __lowercase		:			Optional[int]	    =       np.array([0.00_60, 0.02_01, 0.03_44, 0.00_24, 0.00_18, 0.00_02, 0.00_22, 0.00_00, 0.00_69]				)

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




import unittest

import numpy as np

from diffusers import OnnxStableDiffusionInpaintPipelineLegacy
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    load_numpy,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)


if is_onnx_available():
 import onnxruntime as ort


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



      """simple docstring"""







      @property
      def 		snake_case_			(      self		:       Union[str, Any]				):
          return (
              "CUDAExecutionProvider",
              {
                  "gpu_mem_limit": "15000000000",  # 15GB
                  "arena_extend_strategy": "kSameAsRequested",
              },
          )




      @property
      def 		snake_case_			(      self		:       Optional[Any]				):
          __lowercase		:			Tuple	    =       ort.SessionOptions()
          __lowercase		:			List[Any]	    =       False
          return options




      def 		snake_case_			(      self		:       Dict				):
          __lowercase		:			int	    =       load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/in_paint/overture-creations-5sI6fQgYIuo.png'''				)
          __lowercase		:			int	    =       load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/in_paint/overture-creations-5sI6fQgYIuo_mask.png'''				)
          __lowercase		:			Optional[Any]	    =       load_numpy(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy'''				)

          # using the PNDM scheduler by default
          __lowercase		:			Union[str, Any]	    =       OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained(
              '''CompVis/stable-diffusion-v1-4'''				,       revision='''onnx'''				,       safety_checker=_snake_case				,       feature_extractor=_snake_case				,       provider=self.gpu_provider				,       sess_options=self.gpu_options				,       )
          pipe.set_progress_bar_config(disable=_snake_case				)

          __lowercase		:			Tuple	    =       '''A red cat sitting on a park bench'''

          __lowercase		:			int	    =       np.random.RandomState(0				)
          __lowercase		:			int	    =       pipe(
              prompt=_snake_case				,       image=_snake_case				,       mask_image=_snake_case				,       strength=0.75				,       guidance_scale=7.5				,       num_inference_steps=15				,       generator=_snake_case				,       output_type='''np'''				,       )

          __lowercase		:			Dict	    =       output.images[0]

          assert image.shape == (512, 512, 3)
          assert np.abs(expected_image - image				).max() < 1E-2


