






"""simple docstring"""





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      _lowercase (     SCREAMING_SNAKE_CASE__		,  unittest.TestCase						):
      _a   :     Union[str, Any]								=   DDIMPipeline
      _a   :     Any								=   UNCONDITIONAL_IMAGE_GENERATION_PARAMS
      _a   :     Any								=   PipelineTesterMixin.required_optional_params - {
          '''num_images_per_prompt''',
          '''latents''',
          '''callback''',
          '''callback_steps''',
      }
      _a   :     List[str]								=   UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
      _a   :     Tuple								=   False


      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            torch.manual_seed(0						)
            __snake_case      :    List[str]  			=UNetaDModel(
                block_out_channels=(3_2, 6_4)							,   layers_per_block=2							,   sample_size=3_2							,   in_channels=3							,   out_channels=3							,   down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')							,   up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')							,   )
            __snake_case      :    Optional[Any]  			=DDIMScheduler()
            __snake_case      :    Any  			={"""unet""": unet, """scheduler""": scheduler}
            return components


      def _UpperCamelCase						(    self				:	List[str]							,   a				:	Any							,   a				:	Any=0						):





            """simple docstring"""







            if str(_lowercase						).startswith('''mps'''						):
                  __snake_case      :    int  			=torch.manual_seed(_lowercase						)
            else:
                  __snake_case      :    Dict  			=torch.Generator(device=_lowercase						).manual_seed(_lowercase						)
            __snake_case      :    Optional[int]  			={
                """batch_size""": 1,
                """generator""": generator,
                """num_inference_steps""": 2,
                """output_type""": """numpy""",
            }
            return inputs


      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            __snake_case      :    Tuple  			="""cpu"""

            __snake_case      :    int  			=self.get_dummy_components()
            __snake_case      :    Tuple  			=self.pipeline_class(**_lowercase						)
            pipe.to(_lowercase						)
            pipe.set_progress_bar_config(disable=_lowercase						)

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

            self.assertEqual(image.shape							,   (1, 3_2, 3_2, 3)						)
            __snake_case      :    Optional[int]  			=np.array(
                [1.0_00e00, 5.7_17e-01, 4.7_17e-01, 1.0_00e00, 0.0_00e00, 1.0_00e00, 3.0_00e-04, 0.0_00e00, 9.0_00e-04]						)
            __snake_case      :    Union[str, Any]  			=np.abs(image_slice.flatten() - expected_slice						).max()
            self.assertLessEqual(_lowercase							,   1e-3						)


      def _UpperCamelCase						(    self				:	Dict						):





            """simple docstring"""







            super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3						)


      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            super().test_save_load_local(expected_max_difference=3e-3						)


      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            super().test_save_load_optional_components(expected_max_difference=3e-3						)







      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            super().test_inference_batch_single_identical(expected_max_diff=3e-3						)



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


      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    str  			="""google/ddpm-cifar10-32"""

            __snake_case      :    Optional[Any]  			=UNetaDModel.from_pretrained(_lowercase						)
            __snake_case      :    int  			=DDIMScheduler()

            __snake_case      :    Union[str, Any]  			=DDIMPipeline(unet=_lowercase							,   scheduler=_lowercase						)
            ddim.to(_lowercase						)
            ddim.set_progress_bar_config(disable=_lowercase						)

            __snake_case      :    List[Any]  			=torch.manual_seed(0						)
            __snake_case      :    Union[str, Any]  			=ddim(generator=_lowercase							,   eta=0.0							,   output_type='''numpy'''						).images

            __snake_case      :    List[Any]  			=image[0, -3:, -3:, -1]

            assert image.shape == (1, 3_2, 3_2, 3)
            __snake_case      :    Tuple  			=np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3]						)

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







      def _UpperCamelCase						(    self				:	Optional[Any]						):





            """simple docstring"""







            __snake_case      :    Dict  			="""google/ddpm-ema-bedroom-256"""

            __snake_case      :    Tuple  			=UNetaDModel.from_pretrained(_lowercase						)
            __snake_case      :    List[Any]  			=DDIMScheduler.from_pretrained(_lowercase						)

            __snake_case      :    List[str]  			=DDIMPipeline(unet=_lowercase							,   scheduler=_lowercase						)
            ddpm.to(_lowercase						)
            ddpm.set_progress_bar_config(disable=_lowercase						)

            __snake_case      :    Union[str, Any]  			=torch.manual_seed(0						)
            __snake_case      :    Any  			=ddpm(generator=_lowercase							,   output_type='''numpy'''						).images

            __snake_case      :    Optional[int]  			=image[0, -3:, -3:, -1]

            assert image.shape == (1, 2_5_6, 2_5_6, 3)
            __snake_case      :    Optional[Any]  			=np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9]						)

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










"""simple docstring"""





import unittest

import numpy as np

from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import DonutImageProcessor


class      _lowercase (     unittest.TestCase						):


      def __init__(    self				:	List[Any]							,   a				:	int							,   a				:	Dict=7							,   a				:	int=3							,   a				:	int=1_8							,   a				:	Dict=3_0							,   a				:	Dict=4_0_0							,   a				:	Optional[Any]=True							,   a				:	Dict=None							,   a				:	int=True							,   a				:	Dict=False							,   a				:	int=True							,   a				:	str=True							,   a				:	List[str]=[0.5, 0.5, 0.5]							,   a				:	Optional[Any]=[0.5, 0.5, 0.5]							,   ):





            """simple docstring"""







            __snake_case      :    List[Any]  			=parent
            __snake_case      :    List[Any]  			=batch_size
            __snake_case      :    str  			=num_channels
            __snake_case      :    Dict  			=image_size
            __snake_case      :    str  			=min_resolution
            __snake_case      :    Tuple  			=max_resolution
            __snake_case      :    str  			=do_resize
            __snake_case      :    Any  			=size if size is not None else {'''height''': 1_8, '''width''': 2_0}
            __snake_case      :    List[Any]  			=do_thumbnail
            __snake_case      :    Tuple  			=do_align_axis
            __snake_case      :    Any  			=do_pad
            __snake_case      :    Dict  			=do_normalize
            __snake_case      :    List[Any]  			=image_mean
            __snake_case      :    Any  			=image_std







      def _UpperCamelCase						(    self				:	str						):





            """simple docstring"""







            return {
                "do_resize": self.do_resize,
                "size": self.size,
                "do_thumbnail": self.do_thumbnail,
                "do_align_long_axis": self.do_align_axis,
                "do_pad": self.do_pad,
                "do_normalize": self.do_normalize,
                "image_mean": self.image_mean,
                "image_std": self.image_std,
            }



@require_torch
@require_vision
class      _lowercase (     lowerCAmelCase		,  unittest.TestCase						):
      _a   :     str								=   DonutImageProcessor if is_vision_available() else None


      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=DonutImageProcessingTester(self						)


      @property
      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            return self.image_processor_tester.prepare_image_processor_dict()


      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    Optional[Any]  			=self.image_processing_class(**self.image_processor_dict						)
            self.assertTrue(hasattr(a							,   '''do_resize'''						)						)
            self.assertTrue(hasattr(a							,   '''size'''						)						)
            self.assertTrue(hasattr(a							,   '''do_thumbnail'''						)						)
            self.assertTrue(hasattr(a							,   '''do_align_long_axis'''						)						)
            self.assertTrue(hasattr(a							,   '''do_pad'''						)						)
            self.assertTrue(hasattr(a							,   '''do_normalize'''						)						)
            self.assertTrue(hasattr(a							,   '''image_mean'''						)						)
            self.assertTrue(hasattr(a							,   '''image_std'''						)						)


      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Dict  			=self.image_processing_class.from_dict(self.image_processor_dict						)
            self.assertEqual(image_processor.size							,   {'''height''': 1_8, '''width''': 2_0}						)

            __snake_case      :    List[Any]  			=self.image_processing_class.from_dict(self.image_processor_dict							,   size=4_2						)
            self.assertEqual(image_processor.size							,   {'''height''': 4_2, '''width''': 4_2}						)

            # Previous config had dimensions in (width, height) order
            __snake_case      :    Tuple  			=self.image_processing_class.from_dict(self.image_processor_dict							,   size=(4_2, 8_4)						)
            self.assertEqual(image_processor.size							,   {'''height''': 8_4, '''width''': 4_2}						)


      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            pass


      @is_flaky()
      def _UpperCamelCase						(    self				:	Union[str, Any]						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=self.image_processing_class(**self.image_processor_dict						)
            # create random PIL images
            __snake_case      :    List[Any]  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   Image.Image						)

            # Test not batched input
            __snake_case      :    str  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    Optional[int]  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )


      @is_flaky()
      def _UpperCamelCase						(    self				:	Tuple						):





            """simple docstring"""







            __snake_case      :    Tuple  			=self.image_processing_class(**self.image_processor_dict						)
            # create random numpy tensors
            __snake_case      :    Optional[int]  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a							,   numpify=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   np.ndarray						)

            # Test not batched input
            __snake_case      :    List[Any]  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    int  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )







      @is_flaky()
      def _UpperCamelCase						(    self				:	List[str]						):





            """simple docstring"""







            __snake_case      :    Dict  			=self.image_processing_class(**self.image_processor_dict						)
            # create random PyTorch tensors
            __snake_case      :    Dict  			=prepare_image_inputs(self.image_processor_tester							,   equal_resolution=a							,   torchify=a						)
            for image in image_inputs:
                  self.assertIsInstance(a							,   torch.Tensor						)

            # Test not batched input
            __snake_case      :    Dict  			=image_processing(image_inputs[0]							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    1,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )

            # Test batched
            __snake_case      :    Optional[int]  			=image_processing(a							,   return_tensors='''pt'''						).pixel_values
            self.assertEqual(
                encoded_images.shape							,   (
                    self.image_processor_tester.batch_size,
                    self.image_processor_tester.num_channels,
                    self.image_processor_tester.size['''height'''],
                    self.image_processor_tester.size['''width'''],
                )							,   )


