"""simple docstring"""






from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

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,
)


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

__lowerCAmelCase					: Optional[int]        ="""
    Examples:
        ```py
        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline
        >>> from diffusers.utils import load_image
        >>> import torch

        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16
        ... )
        >>> pipe_prior.to(\"cuda\")

        >>> prompt = \"A red cartoon frog, 4k\"
        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)

        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16
        ... )
        >>> pipe.to(\"cuda\")

        >>> init_image = load_image(
        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"
        ...     \"/kandinsky/frog.png\"
        ... )

        >>> image = pipe(
        ...     image=init_image,
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     height=768,
        ...     width=768,
        ...     num_inference_steps=100,
        ...     strength=0.2,
        ... ).images

        >>> image[0].save(\"red_frog.png\")
        ```
"""


def     UpperCAmelCase__ (       lowerCAmelCase__  :Any      ,	lowerCAmelCase__  :Dict      ,	lowerCAmelCase__  :Optional[Any]=8	)				->					List[str]:
      '''simple docstring'''


      lowercase														=			height // scale_factor**2
      if height % scale_factor**2 != 0:
            new_height += 1
      lowercase														=			width // scale_factor**2
      if width % scale_factor**2 != 0:
            new_width += 1
      return new_height * scale_factor, new_width * scale_factor


def     UpperCAmelCase__ (       lowerCAmelCase__  :str      ,	lowerCAmelCase__  :List[Any]=5_1_2      ,	lowerCAmelCase__  :Union[str, Any]=5_1_2	)				->					Optional[Any]:
      '''simple docstring'''


      lowercase														=			pil_image.resize((w, h)      ,	resample=Image.BICUBIC      ,	reducing_gap=1	)
      lowercase														=			np.array(pil_image.convert("""RGB"""	)	)
      lowercase														=			arr.astype(np.floataa	) / 127.5 - 1
      lowercase														=			np.transpose(lowerCAmelCase__      ,	[2, 0, 1]	)
      lowercase														=			torch.from_numpy(lowerCAmelCase__	).unsqueeze(0	)
      return image






class 				_A		( A_			):

      '''simple docstring'''





      def __init__(		self	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, ):







            """simple docstring"""



            super().__init__()

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

      def        A__ (		self	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		):







            """simple docstring"""



            lowercase														=			min(int(num_inference_steps * strength		)	, __lowerCAmelCase		)

            lowercase														=			max(num_inference_steps - init_timestep	, 0		)
            lowercase														=			self.scheduler.timesteps[t_start:]

            return timesteps, num_inference_steps - t_start

      def        A__ (		self	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase=None		):







            """simple docstring"""



            if not isinstance(__lowerCAmelCase	, (torch.Tensor, PIL.Image.Image, list)		):
                  raise ValueError(
                      f'`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(__lowerCAmelCase		)}'		)

            lowercase														=			image.to(device=__lowerCAmelCase	, dtype=__lowerCAmelCase		)

            lowercase														=			batch_size * num_images_per_prompt

            if image.shape[1] == 4:
                  lowercase														=			image

            else:
                  if isinstance(__lowerCAmelCase	, __lowerCAmelCase		) and len(__lowerCAmelCase		) != batch_size:
                        raise ValueError(
                            f'You have passed a list of generators of length {len(__lowerCAmelCase		)}, but requested an effective batch'
                            f' size of {batch_size}. Make sure the batch size matches the length of the generators.'		)

                  elif isinstance(__lowerCAmelCase	, __lowerCAmelCase		):
                        lowercase														=			[
                            self.movq.encode(image[i : i + 1]		).latent_dist.sample(generator[i]		) for i in range(__lowerCAmelCase		)
                        ]
                        lowercase														=			torch.cat(__lowerCAmelCase	, dim=0		)
                  else:
                        lowercase														=			self.movq.encode(__lowerCAmelCase		).latent_dist.sample(__lowerCAmelCase		)

                  lowercase														=			self.movq.config.scaling_factor * init_latents

            lowercase														=			torch.cat([init_latents]	, dim=0		)

            lowercase														=			init_latents.shape
            lowercase														=			randn_tensor(__lowerCAmelCase	, generator=__lowerCAmelCase	, device=__lowerCAmelCase	, dtype=__lowerCAmelCase		)

            # get latents
            lowercase														=			self.scheduler.add_noise(__lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		)

            lowercase														=			init_latents

            return latents

      def        A__ (		self	, __lowerCAmelCase=0		):







            """simple docstring"""



            if is_accelerate_available():
                  from accelerate import cpu_offload
            else:
                  raise ImportError("""Please install accelerate via `pip install accelerate`"""		)

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

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

      def        A__ (		self	, __lowerCAmelCase=0		):







            """simple docstring"""



            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."""		)

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

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

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

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

      @property
      # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
      def        A__ (		self		):







            """simple docstring"""



            if not hasattr(self.unet	, """_hf_hook"""		):
                  return self.device
            for module in self.unet.modules():
                  if (
                      hasattr(__lowerCAmelCase	, """_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(__lowerCAmelCase		)
      def __call__(		self	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase = 512	, __lowerCAmelCase = 512	, __lowerCAmelCase = 100	, __lowerCAmelCase = 4.0	, __lowerCAmelCase = 0.3	, __lowerCAmelCase = 1	, __lowerCAmelCase = None	, __lowerCAmelCase = "pil"	, __lowerCAmelCase = True	, ):







            """simple docstring"""



            lowercase														=			self._execution_device

            lowercase														=			guidance_scale > 1.0

            if isinstance(__lowerCAmelCase	, __lowerCAmelCase		):
                  lowercase														=			torch.cat(__lowerCAmelCase	, dim=0		)
            lowercase														=			image_embeds.shape[0]
            if isinstance(__lowerCAmelCase	, __lowerCAmelCase		):
                  lowercase														=			torch.cat(__lowerCAmelCase	, dim=0		)

            if do_classifier_free_guidance:
                  lowercase														=			image_embeds.repeat_interleave(__lowerCAmelCase	, dim=0		)
                  lowercase														=			negative_image_embeds.repeat_interleave(__lowerCAmelCase	, dim=0		)

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

            if not isinstance(__lowerCAmelCase	, __lowerCAmelCase		):
                  lowercase														=			[image]
            if not all(isinstance(__lowerCAmelCase	, (PIL.Image.Image, torch.Tensor)		) for i in image		):
                  raise ValueError(
                      f'Input is in incorrect format: {[type(__lowerCAmelCase		) for i in image]}. Currently, we only support  PIL image and pytorch tensor'		)

            lowercase														=			torch.cat([prepare_image(__lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		) for i in image]	, dim=0		)
            lowercase														=			image.to(dtype=image_embeds.dtype	, device=__lowerCAmelCase		)

            lowercase														=			self.movq.encode(__lowerCAmelCase		)["""latents"""]
            lowercase														=			latents.repeat_interleave(__lowerCAmelCase	, dim=0		)
            self.scheduler.set_timesteps(__lowerCAmelCase	, device=__lowerCAmelCase		)
            lowercase														=			self.get_timesteps(__lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase		)
            lowercase														=			timesteps[:1].repeat(batch_size * num_images_per_prompt		)
            lowercase														=			downscale_height_and_width(__lowerCAmelCase	, __lowerCAmelCase	, self.movq_scale_factor		)
            lowercase														=			self.prepare_latents(
                __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, image_embeds.dtype	, __lowerCAmelCase	, __lowerCAmelCase		)
            for i, t in enumerate(self.progress_bar(__lowerCAmelCase		)		):
                  # expand the latents if we are doing classifier free guidance
                  lowercase														=			torch.cat([latents] * 2		) if do_classifier_free_guidance else latents

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

                  if do_classifier_free_guidance:
                        lowercase														=			noise_pred.split(latents.shape[1]	, dim=1		)
                        lowercase														=			noise_pred.chunk(2		)
                        lowercase														=			variance_pred.chunk(2		)
                        lowercase														=			noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                        lowercase														=			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"]
                  ):
                        lowercase														=			noise_pred.split(latents.shape[1]	, dim=1		)

                  # compute the previous noisy sample x_t -> x_t-1
                  lowercase														=			self.scheduler.step(
                      __lowerCAmelCase	, __lowerCAmelCase	, __lowerCAmelCase	, generator=__lowerCAmelCase	, )[0]

            # post-processing
            lowercase														=			self.movq.decode(__lowerCAmelCase	, force_not_quantize=__lowerCAmelCase		)["""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"]:
                  lowercase														=			image * 0.5 + 0.5
                  lowercase														=			image.clamp(0	, 1		)
                  lowercase														=			image.cpu().permute(0	, 2	, 3	, 1		).float().numpy()

            if output_type == "pil":
                  lowercase														=			self.numpy_to_pil(__lowerCAmelCase		)

            if not return_dict:
                  return (image,)

            return ImagePipelineOutput(images=__lowerCAmelCase		)




"""simple docstring"""






import os
from pathlib import Path
from unittest.mock import patch

import pytest
import zstandard as zstd

from datasets.download.download_config import DownloadConfig
from datasets.utils.file_utils import (
    OfflineModeIsEnabled,
    cached_path,
    fsspec_get,
    fsspec_head,
    ftp_get,
    ftp_head,
    get_from_cache,
    http_get,
    http_head,
)


__lowerCAmelCase					: List[Any]        ="""\
    Text data.
    Second line of data."""

__lowerCAmelCase					: Any        ="""file"""


@pytest.fixture(scope="""session"""	)
def     UpperCAmelCase__ (       lowerCAmelCase__  :str	)				->					Union[str, Any]:
      '''simple docstring'''


      lowercase														=			tmp_path_factory.mktemp("""data"""	) / (FILE_PATH + """.zstd""")
      lowercase														=			bytes(lowerCAmelCase__      ,	"""utf-8"""	)
      with zstd.open(lowerCAmelCase__      ,	"""wb"""	) as f:
            f.write(lowerCAmelCase__	)
      return path


@pytest.fixture
def     UpperCAmelCase__ (       lowerCAmelCase__  :Tuple	)				->					Dict:
      '''simple docstring'''


      with open(os.path.join(tmpfs.local_root_dir      ,	lowerCAmelCase__	)      ,	"""w"""	) as f:
            f.write(lowerCAmelCase__	)
      return FILE_PATH


@pytest.mark.parametrize("""compression_format"""      ,	["""gzip""", """xz""", """zstd"""]	)
def     UpperCAmelCase__ (       lowerCAmelCase__  :Any      ,	lowerCAmelCase__  :Any      ,	lowerCAmelCase__  :List[Any]      ,	lowerCAmelCase__  :Optional[Any]      ,	lowerCAmelCase__  :Any      ,	lowerCAmelCase__  :int	)				->					Union[str, Any]:
      '''simple docstring'''


      lowercase														=			{"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path}
      lowercase														=			input_paths[compression_format]
      lowercase														=			tmp_path / """cache"""
      lowercase														=			DownloadConfig(cache_dir=lowerCAmelCase__      ,	extract_compressed_file=lowerCAmelCase__	)
      lowercase														=			cached_path(lowerCAmelCase__      ,	download_config=lowerCAmelCase__	)
      with open(lowerCAmelCase__	) as f:
            lowercase														=			f.read()
      with open(lowerCAmelCase__	) as f:
            lowercase														=			f.read()
      assert extracted_file_content == expected_file_content


@pytest.mark.parametrize("""default_extracted"""      ,	[True, False]	)
@pytest.mark.parametrize("""default_cache_dir"""      ,	[True, False]	)
def     UpperCAmelCase__ (       lowerCAmelCase__  :Dict      ,	lowerCAmelCase__  :Tuple      ,	lowerCAmelCase__  :Tuple      ,	lowerCAmelCase__  :Union[str, Any]      ,	lowerCAmelCase__  :List[str]	)				->					Any:
      '''simple docstring'''


      lowercase														=			"""custom_cache"""
      lowercase														=			"""custom_extracted_dir"""
      lowercase														=			tmp_path / """custom_extracted_path"""
      if default_extracted:
            lowercase														=			("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""")
      else:
            monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR"""      ,	lowerCAmelCase__	)
            monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH"""      ,	str(lowerCAmelCase__	)	)
            lowercase														=			custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir)

      lowercase														=			xz_file
      lowercase														=			(
          DownloadConfig(extract_compressed_file=lowerCAmelCase__	)
          if default_cache_dir
          else DownloadConfig(cache_dir=tmp_path / custom_cache_dir      ,	extract_compressed_file=lowerCAmelCase__	)
      )
      lowercase														=			cached_path(lowerCAmelCase__      ,	download_config=lowerCAmelCase__	)
      assert Path(lowerCAmelCase__	).parent.parts[-2:] == expected


def     UpperCAmelCase__ (       lowerCAmelCase__  :List[str]	)				->					Tuple:
      '''simple docstring'''


      lowercase														=			str(Path(lowerCAmelCase__	).resolve()	)
      assert cached_path(lowerCAmelCase__	) == text_file
      # relative path
      lowercase														=			str(Path(lowerCAmelCase__	).resolve().relative_to(Path(os.getcwd()	)	)	)
      assert cached_path(lowerCAmelCase__	) == text_file


def     UpperCAmelCase__ (       lowerCAmelCase__  :Any	)				->					List[Any]:
      '''simple docstring'''


      lowercase														=			str(tmp_path.resolve() / """__missing_file__.txt"""	)
      with pytest.raises(lowerCAmelCase__	):
            cached_path(lowerCAmelCase__	)
      # relative path
      lowercase														=			"""./__missing_file__.txt"""
      with pytest.raises(lowerCAmelCase__	):
            cached_path(lowerCAmelCase__	)


def     UpperCAmelCase__ (       lowerCAmelCase__  :Any	)				->					Union[str, Any]:
      '''simple docstring'''


      lowercase														=			get_from_cache(f'tmp://{tmpfs_file}'	)
      with open(lowerCAmelCase__	) as f:
            lowercase														=			f.read()
      assert output_file_content == FILE_CONTENT


@patch("""datasets.config.HF_DATASETS_OFFLINE"""      ,	lowerCAmelCase__	)
def     UpperCAmelCase__ (       )				->					str:
      '''simple docstring'''


      with pytest.raises(lowerCAmelCase__	):
            cached_path("""https://huggingface.co"""	)


@patch("""datasets.config.HF_DATASETS_OFFLINE"""      ,	lowerCAmelCase__	)
def     UpperCAmelCase__ (       lowerCAmelCase__  :Tuple	)				->					Any:
      '''simple docstring'''


      lowercase														=			tmp_path_factory.mktemp("""data"""	) / """file.html"""
      with pytest.raises(lowerCAmelCase__	):
            http_get("""https://huggingface.co"""      ,	temp_file=lowerCAmelCase__	)
      with pytest.raises(lowerCAmelCase__	):
            http_head("""https://huggingface.co"""	)


@patch("""datasets.config.HF_DATASETS_OFFLINE"""      ,	lowerCAmelCase__	)
def     UpperCAmelCase__ (       lowerCAmelCase__  :str	)				->					Any:
      '''simple docstring'''


      lowercase														=			tmp_path_factory.mktemp("""data"""	) / """file.html"""
      with pytest.raises(lowerCAmelCase__	):
            ftp_get("""ftp://huggingface.co"""      ,	temp_file=lowerCAmelCase__	)
      with pytest.raises(lowerCAmelCase__	):
            ftp_head("""ftp://huggingface.co"""	)






@patch("""datasets.config.HF_DATASETS_OFFLINE"""      ,	lowerCAmelCase__	)
def     UpperCAmelCase__ (       lowerCAmelCase__  :Any	)				->					Dict:
      '''simple docstring'''


      lowercase														=			tmp_path_factory.mktemp("""data"""	) / """file.html"""
      with pytest.raises(lowerCAmelCase__	):
            fsspec_get("""s3://huggingface.co"""      ,	temp_file=lowerCAmelCase__	)
      with pytest.raises(lowerCAmelCase__	):
            fsspec_head("""s3://huggingface.co"""	)



