





'''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 					a_     (				unittest.TestCase       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		A=7 ,		A=3 ,		A=18 ,		A=30 ,		A=400 ,		A=True ,		A=None ,		A=True ,		A=False ,		A=True ,		A=True ,		A=[0.5, 0.5, 0.5] ,		A=[0.5, 0.5, 0.5] ,		)		->   Union[str, Any]:
        _SCREAMING_SNAKE_CASE									=			parent
        _SCREAMING_SNAKE_CASE									=			batch_size
        _SCREAMING_SNAKE_CASE									=			num_channels
        _SCREAMING_SNAKE_CASE									=			image_size
        _SCREAMING_SNAKE_CASE									=			min_resolution
        _SCREAMING_SNAKE_CASE									=			max_resolution
        _SCREAMING_SNAKE_CASE									=			do_resize
        _SCREAMING_SNAKE_CASE									=			size if size is not None else {"""height""": 18, """width""": 20}
        _SCREAMING_SNAKE_CASE									=			do_thumbnail
        _SCREAMING_SNAKE_CASE									=			do_align_axis
        _SCREAMING_SNAKE_CASE									=			do_pad
        _SCREAMING_SNAKE_CASE									=			do_normalize
        _SCREAMING_SNAKE_CASE									=			image_mean
        _SCREAMING_SNAKE_CASE									=			image_std





    def 			snake_case_(		self       )		->   Dict:
        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 					a_     (				snake_case_      ,    unittest.TestCase       ):

    '''simple docstring'''
    UpperCamelCase     = DonutImageProcessor if is_vision_available() else None


    def 			snake_case_(		self       )		->   str:
        _SCREAMING_SNAKE_CASE									=			DonutImageProcessingTester(self       )


    @property
    def 			snake_case_(		self       )		->   Optional[int]:
        return self.image_processor_tester.prepare_image_processor_dict()


    def 			snake_case_(		self       )		->   Tuple:
        _SCREAMING_SNAKE_CASE									=			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 			snake_case_(		self       )		->   Union[str, Any]:
        _SCREAMING_SNAKE_CASE									=			self.image_processing_class.from_dict(self.image_processor_dict       )
        self.assertEqual(image_processor.size ,		{"""height""": 18, """width""": 20}       )

        _SCREAMING_SNAKE_CASE									=			self.image_processing_class.from_dict(self.image_processor_dict ,		size=42       )
        self.assertEqual(image_processor.size ,		{"""height""": 42, """width""": 42}       )

        # Previous config had dimensions in (width, height) order
        _SCREAMING_SNAKE_CASE									=			self.image_processing_class.from_dict(self.image_processor_dict ,		size=(42, 84)       )
        self.assertEqual(image_processor.size ,		{"""height""": 84, """width""": 42}       )


    def 			snake_case_(		self       )		->   Optional[int]:
        pass


    @is_flaky()
    def 			snake_case_(		self       )		->   Optional[int]:
        # Initialize image_processing
        _SCREAMING_SNAKE_CASE									=			self.image_processing_class(**self.image_processor_dict       )
        # create random PIL images
        _SCREAMING_SNAKE_CASE									=			prepare_image_inputs(self.image_processor_tester ,		equal_resolution=A       )
        for image in image_inputs:
            self.assertIsInstance(A ,		Image.Image       )

        # Test not batched input
        _SCREAMING_SNAKE_CASE									=			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
        _SCREAMING_SNAKE_CASE									=			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 			snake_case_(		self       )		->   List[Any]:
        # Initialize image_processing
        _SCREAMING_SNAKE_CASE									=			self.image_processing_class(**self.image_processor_dict       )
        # create random numpy tensors
        _SCREAMING_SNAKE_CASE									=			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
        _SCREAMING_SNAKE_CASE									=			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
        _SCREAMING_SNAKE_CASE									=			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 			snake_case_(		self       )		->   Any:
        # Initialize image_processing
        _SCREAMING_SNAKE_CASE									=			self.image_processing_class(**self.image_processor_dict       )
        # create random PyTorch tensors
        _SCREAMING_SNAKE_CASE									=			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
        _SCREAMING_SNAKE_CASE									=			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
        _SCREAMING_SNAKE_CASE									=			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"""],
            ) ,		)










'''simple docstring'''

from typing import List, Optional, Union

import torch

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


lowercase_					= logging.get_logger(__name__)  # pylint: disable=invalid-name

lowercase_					= """
    Examples:
        ```py
        >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline
        >>> import torch

        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\")
        >>> pipe_prior.to(\"cuda\")
        >>> prompt = \"red cat, 4k photo\"
        >>> out = pipe_prior(prompt)
        >>> image_emb = out.image_embeds
        >>> zero_image_emb = out.negative_image_embeds
        >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\")
        >>> pipe.to(\"cuda\")
        >>> image = pipe(
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     height=768,
        ...     width=768,
        ...     num_inference_steps=50,
        ... ).images
        >>> image[0].save(\"cat.png\")
        ```
"""





def lowerCamelCase						(     __lowerCamelCase :    str					,       __lowerCamelCase :    Optional[Any]					,       __lowerCamelCase :    List[Any]=8    )						->Tuple:
    _SCREAMING_SNAKE_CASE									=			height // scale_factor**2
    if height % scale_factor**2 != 0:
        new_height += 1
    _SCREAMING_SNAKE_CASE									=			width // scale_factor**2
    if width % scale_factor**2 != 0:
        new_width += 1
    return new_height * scale_factor, new_width * scale_factor






class 					a_     (				snake_case_       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		A ,		A ,		)		->   Union[str, Any]:
        super().__init__()

        self.register_modules(
            unet=A ,		scheduler=A ,		movq=A ,		)
        _SCREAMING_SNAKE_CASE									=			2 ** (len(self.movq.config.block_out_channels       ) - 1)


    def 			snake_case_(		self ,		A ,		A ,		A ,		A ,		A ,		A       )		->   Union[str, Any]:
        if latents is None:
            _SCREAMING_SNAKE_CASE									=			randn_tensor(A ,		generator=A ,		device=A ,		dtype=A       )
        else:
            if latents.shape != shape:
                raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'       )
            _SCREAMING_SNAKE_CASE									=			latents.to(A       )

        _SCREAMING_SNAKE_CASE									=			latents * scheduler.init_noise_sigma
        return latents


    def 			snake_case_(		self ,		A=0       )		->   Dict:
        if is_accelerate_available():
            from accelerate import cpu_offload
        else:
            raise ImportError("""Please install accelerate via `pip install accelerate`"""       )

        _SCREAMING_SNAKE_CASE									=			torch.device(f'cuda:{gpu_id}'       )

        _SCREAMING_SNAKE_CASE									=			[
            self.unet,
            self.movq,
        ]
        for cpu_offloaded_model in models:
            if cpu_offloaded_model is not None:
                cpu_offload(A ,		A       )


    def 			snake_case_(		self ,		A=0       )		->   str:
        if is_accelerate_available() and is_accelerate_version(""">=""" ,		"""0.17.0.dev0"""       ):
            from accelerate import cpu_offload_with_hook
        else:
            raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."""       )

        _SCREAMING_SNAKE_CASE									=			torch.device(f'cuda:{gpu_id}'       )

        if self.device.type != "cpu":
            self.to("""cpu""" ,		silence_dtype_warnings=A       )
            torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

        _SCREAMING_SNAKE_CASE									=			None
        for cpu_offloaded_model in [self.unet, self.movq]:
            _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			cpu_offload_with_hook(A ,		A ,		prev_module_hook=A       )

        # We'll offload the last model manually.
        _SCREAMING_SNAKE_CASE									=			hook


    @property
    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
    def 			snake_case_(		self       )		->   Tuple:
        if not hasattr(self.unet ,		"""_hf_hook"""       ):
            return self.device
        for module in self.unet.modules():
            if (
                hasattr(A ,		"""_hf_hook"""       )
                and hasattr(module._hf_hook ,		"""execution_device"""       )
                and module._hf_hook.execution_device is not None
            ):
                return torch.device(module._hf_hook.execution_device       )
        return self.device





    @torch.no_grad()
    @replace_example_docstring(A       )
    def __call__(		self ,		A ,		A ,		A = 512 ,		A = 512 ,		A = 100 ,		A = 4.0 ,		A = 1 ,		A = None ,		A = None ,		A = "pil" ,		A = True ,		)		->   List[str]:
        _SCREAMING_SNAKE_CASE									=			self._execution_device

        _SCREAMING_SNAKE_CASE									=			guidance_scale > 1.0

        if isinstance(A ,		A       ):
            _SCREAMING_SNAKE_CASE									=			torch.cat(A ,		dim=0       )
        _SCREAMING_SNAKE_CASE									=			image_embeds.shape[0] * num_images_per_prompt
        if isinstance(A ,		A       ):
            _SCREAMING_SNAKE_CASE									=			torch.cat(A ,		dim=0       )

        if do_classifier_free_guidance:
            _SCREAMING_SNAKE_CASE									=			image_embeds.repeat_interleave(A ,		dim=0       )
            _SCREAMING_SNAKE_CASE									=			negative_image_embeds.repeat_interleave(A ,		dim=0       )

        _SCREAMING_SNAKE_CASE									=			torch.cat([negative_image_embeds, image_embeds] ,		dim=0       ).to(dtype=self.unet.dtype ,		device=A       )

        self.scheduler.set_timesteps(A ,		device=A       )
        _SCREAMING_SNAKE_CASE									=			self.scheduler.timesteps

        _SCREAMING_SNAKE_CASE									=			self.unet.config.in_channels

        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			downscale_height_and_width(A ,		A ,		self.movq_scale_factor       )

        # create initial latent
        _SCREAMING_SNAKE_CASE									=			self.prepare_latents(
            (batch_size, num_channels_latents, height, width) ,		image_embeds.dtype ,		A ,		A ,		A ,		self.scheduler ,		)

        for i, t in enumerate(self.progress_bar(A       )       ):
            # expand the latents if we are doing classifier free guidance
            _SCREAMING_SNAKE_CASE									=			torch.cat([latents] * 2       ) if do_classifier_free_guidance else latents

            _SCREAMING_SNAKE_CASE									=			{"""image_embeds""": image_embeds}
            _SCREAMING_SNAKE_CASE									=			self.unet(
                sample=A ,		timestep=A ,		encoder_hidden_states=A ,		added_cond_kwargs=A ,		return_dict=A ,		)[0]

            if do_classifier_free_guidance:
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			noise_pred.split(latents.shape[1] ,		dim=1       )
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			noise_pred.chunk(2       )
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			variance_pred.chunk(2       )
                _SCREAMING_SNAKE_CASE									=			noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                _SCREAMING_SNAKE_CASE									=			torch.cat([noise_pred, variance_pred_text] ,		dim=1       )

            if not (
                hasattr(self.scheduler.config ,		"""variance_type"""       )
                and self.scheduler.config.variance_type in ["learned", "learned_range"]
            ):
                _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			noise_pred.split(latents.shape[1] ,		dim=1       )

            # compute the previous noisy sample x_t -> x_t-1
            _SCREAMING_SNAKE_CASE									=			self.scheduler.step(
                A ,		A ,		A ,		generator=A ,		)[0]
        # post-processing
        _SCREAMING_SNAKE_CASE									=			self.movq.decode(A ,		force_not_quantize=A       )["""sample"""]

        if output_type not in ["pt", "np", "pil"]:
            raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}'       )

        if output_type in ["np", "pil"]:
            _SCREAMING_SNAKE_CASE									=			image * 0.5 + 0.5
            _SCREAMING_SNAKE_CASE									=			image.clamp(0 ,		1       )
            _SCREAMING_SNAKE_CASE									=			image.cpu().permute(0 ,		2 ,		3 ,		1       ).float().numpy()

        if output_type == "pil":
            _SCREAMING_SNAKE_CASE									=			self.numpy_to_pil(A       )

        if not return_dict:
            return (image,)

        return ImagePipelineOutput(images=A       )



