






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


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

A_			:List[Any]	    =		'''
    Examples:
        ```py
        >>> import torch
        >>> import numpy as np

        >>> from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22ControlnetImg2ImgPipeline
        >>> from transformers import pipeline
        >>> from diffusers.utils import load_image


        >>> def make_hint(image, depth_estimator):
        ...     image = depth_estimator(image)["depth"]
        ...     image = np.array(image)
        ...     image = image[:, :, None]
        ...     image = np.concatenate([image, image, image], axis=2)
        ...     detected_map = torch.from_numpy(image).float() / 255.0
        ...     hint = detected_map.permute(2, 0, 1)
        ...     return hint


        >>> depth_estimator = pipeline("depth-estimation")

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

        >>> pipe = KandinskyV22ControlnetImg2ImgPipeline.from_pretrained(
        ...     "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16
        ... )
        >>> pipe = pipe.to("cuda")

        >>> img = load_image(
        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
        ...     "/kandinsky/cat.png"
        ... ).resize((768, 768))


        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")

        >>> prompt = "A robot, 4k photo"
        >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"

        >>> generator = torch.Generator(device="cuda").manual_seed(43)

        >>> img_emb = pipe_prior(prompt=prompt, image=img, strength=0.85, generator=generator)
        >>> negative_emb = pipe_prior(prompt=negative_prior_prompt, image=img, strength=1, generator=generator)

        >>> images = pipe(
        ...     image=img,
        ...     strength=0.5,
        ...     image_embeds=img_emb.image_embeds,
        ...     negative_image_embeds=negative_emb.image_embeds,
        ...     hint=hint,
        ...     num_inference_steps=50,
        ...     generator=generator,
        ...     height=768,
        ...     width=768,
        ... ).images

        >>> images[0].save("robot_cat.png")
        ```
'''






def 				A	(			a_				,a_				,a_=8   )	->		Dict:
					__UpperCamelCase :   str									=height // scale_factor**2
					if height % scale_factor**2 != 0:
										new_height += 1
					__UpperCamelCase :   List[Any]									=width // scale_factor**2
					if width % scale_factor**2 != 0:
										new_width += 1
					return new_height * scale_factor, new_width * scale_factor






def 				A	(			a_				,a_=512				,a_=512   )	->		Optional[Any]:
					__UpperCamelCase :   Optional[Any]									=pil_image.resize((w, h)				,resample=Image.BICUBIC				,reducing_gap=1   )
					__UpperCamelCase :   List[Any]									=np.array(pil_image.convert('RGB'   )   )
					__UpperCamelCase :   List[Any]									=arr.astype(np.floataa   ) / 127.5 - 1
					__UpperCamelCase :   Tuple									=np.transpose(a_				,[2, 0, 1]   )
					__UpperCamelCase :   str									=torch.from_numpy(a_   ).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__				,    )
									__UpperCamelCase :   List[Any]									=2 ** (len(self.movq.config.block_out_channels       ) - 1)


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   Optional[int]									=min(int(num_inference_steps * strength       )				,    lowerCamelCase__       )

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

									return timesteps, num_inference_steps - t_start


				def  __lowercase				(					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__       )}'       )

									__UpperCamelCase :   Optional[int]									=image.to(device=lowerCamelCase__				,    dtype=lowerCamelCase__       )

									__UpperCamelCase :   Union[str, Any]									=batch_size * num_images_per_prompt

									if image.shape[1] == 4:
														__UpperCamelCase :   Optional[Any]									=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__       ):
																			__UpperCamelCase :   Any									=[
																			    self.movq.encode(image[i : i + 1]       ).latent_dist.sample(generator[i]       ) for i in range(lowerCamelCase__       )
																			]
																			__UpperCamelCase :   Union[str, Any]									=torch.cat(lowerCamelCase__				,    dim=0       )
														else:
																			__UpperCamelCase :   str									=self.movq.encode(lowerCamelCase__       ).latent_dist.sample(lowerCamelCase__       )

														__UpperCamelCase :   str									=self.movq.config.scaling_factor * init_latents

									__UpperCamelCase :   Optional[int]									=torch.cat([init_latents]				,    dim=0       )

									__UpperCamelCase :   Union[str, Any]									=init_latents.shape
									__UpperCamelCase :   Union[str, Any]									=randn_tensor(lowerCamelCase__				,    generator=lowerCamelCase__				,    device=lowerCamelCase__				,    dtype=lowerCamelCase__       )

									# get latents
									__UpperCamelCase :   Tuple									=self.scheduler.add_noise(lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       )

									__UpperCamelCase :   List[Any]									=init_latents

									return latents


				def  __lowercase				(					self				,    lowerCamelCase__=0       ):




									"""simple docstring"""

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

									__UpperCamelCase :   List[str]									=torch.device(f'cuda:{gpu_id}'       )

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


				def  __lowercase				(					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.'       )

									__UpperCamelCase :   str									=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)

									__UpperCamelCase :   Any									=None
									for cpu_offloaded_model in [self.unet, self.movq]:
														__UpperCamelCase						,							__UpperCamelCase :   List[str]									=cpu_offload_with_hook(lowerCamelCase__				,    lowerCamelCase__				,    prev_module_hook=lowerCamelCase__       )

									# We'll offload the last model manually.
									__UpperCamelCase :   List[Any]									=hook


				@property
				# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
				def  __lowercase				(					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__				,    lowerCamelCase__ = 512				,    lowerCamelCase__ = 512				,    lowerCamelCase__ = 100				,    lowerCamelCase__ = 4.0				,    lowerCamelCase__ = 0.3				,    lowerCamelCase__ = 1				,    lowerCamelCase__ = None				,    lowerCamelCase__ = "pil"				,    lowerCamelCase__ = True				,    ):




									"""simple docstring"""

									__UpperCamelCase :   Optional[int]									=self._execution_device

									__UpperCamelCase :   Optional[int]									=guidance_scale > 1.0

									if isinstance(lowerCamelCase__				,    lowerCamelCase__       ):
														__UpperCamelCase :   Tuple									=torch.cat(lowerCamelCase__				,    dim=0       )
									if isinstance(lowerCamelCase__				,    lowerCamelCase__       ):
														__UpperCamelCase :   Optional[Any]									=torch.cat(lowerCamelCase__				,    dim=0       )
									if isinstance(lowerCamelCase__				,    lowerCamelCase__       ):
														__UpperCamelCase :   int									=torch.cat(lowerCamelCase__				,    dim=0       )

									__UpperCamelCase :   Union[str, Any]									=image_embeds.shape[0]

									if do_classifier_free_guidance:
														__UpperCamelCase :   List[Any]									=image_embeds.repeat_interleave(lowerCamelCase__				,    dim=0       )
														__UpperCamelCase :   List[str]									=negative_image_embeds.repeat_interleave(lowerCamelCase__				,    dim=0       )
														__UpperCamelCase :   Any									=hint.repeat_interleave(lowerCamelCase__				,    dim=0       )

									__UpperCamelCase :   Dict									=torch.cat([negative_image_embeds, image_embeds]				,    dim=0       ).to(dtype=self.unet.dtype				,    device=lowerCamelCase__       )
									__UpperCamelCase :   str									=torch.cat([hint, hint]				,    dim=0       ).to(dtype=self.unet.dtype				,    device=lowerCamelCase__       )

									if not isinstance(lowerCamelCase__				,    lowerCamelCase__       ):
														__UpperCamelCase :   Dict									=[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'       )

									__UpperCamelCase :   List[str]									=torch.cat([prepare_image(lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ) for i in image]				,    dim=0       )
									__UpperCamelCase :   Union[str, Any]									=image.to(dtype=image_embeds.dtype				,    device=lowerCamelCase__       )

									__UpperCamelCase :   Tuple									=self.movq.encode(lowerCamelCase__       )['latents']
									__UpperCamelCase :   Union[str, Any]									=latents.repeat_interleave(lowerCamelCase__				,    dim=0       )
									self.scheduler.set_timesteps(lowerCamelCase__				,    device=lowerCamelCase__       )
									__UpperCamelCase						,							__UpperCamelCase :   str									=self.get_timesteps(lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       )
									__UpperCamelCase :   List[str]									=timesteps[:1].repeat(batch_size * num_images_per_prompt       )
									__UpperCamelCase						,							__UpperCamelCase :   List[str]									=downscale_height_and_width(lowerCamelCase__				,    lowerCamelCase__				,    self.movq_scale_factor       )
									__UpperCamelCase :   Optional[Any]									=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
														__UpperCamelCase :   Optional[Any]									=torch.cat([latents] * 2       ) if do_classifier_free_guidance else latents

														__UpperCamelCase :   List[str]									={'image_embeds': image_embeds, 'hint': hint}
														__UpperCamelCase :   List[Any]									=self.unet(
														    sample=lowerCamelCase__				,    timestep=lowerCamelCase__				,    encoder_hidden_states=lowerCamelCase__				,    added_cond_kwargs=lowerCamelCase__				,    return_dict=lowerCamelCase__				,    )[0]

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

														# compute the previous noisy sample x_t -> x_t-1

														__UpperCamelCase :   int									=self.scheduler.step(
														    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    generator=lowerCamelCase__				,    )[0]

									# post-processing
									__UpperCamelCase :   Any									=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"]:
														__UpperCamelCase :   List[Any]									=image * 0.5 + 0.5
														__UpperCamelCase :   Any									=image.clamp(0				,    1       )
														__UpperCamelCase :   Any									=image.cpu().permute(0				,    2				,    3				,    1       ).float().numpy()

									if output_type == "pil":
														__UpperCamelCase :   Optional[Any]									=self.numpy_to_pil(lowerCamelCase__       )

									if not return_dict:
														return (image,)

									return ImagePipelineOutput(images=lowerCamelCase__       )









import os

from packaging import version

from .. import __version__
from .accelerate_utils import apply_forward_hook
from .constants import (
    CONFIG_NAME,
    DEPRECATED_REVISION_ARGS,
    DIFFUSERS_CACHE,
    DIFFUSERS_DYNAMIC_MODULE_NAME,
    FLAX_WEIGHTS_NAME,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    ONNX_EXTERNAL_WEIGHTS_NAME,
    ONNX_WEIGHTS_NAME,
    SAFETENSORS_WEIGHTS_NAME,
    TEXT_ENCODER_ATTN_MODULE,
    WEIGHTS_NAME,
)
from .deprecation_utils import deprecate
from .doc_utils import replace_example_docstring
from .dynamic_modules_utils import get_class_from_dynamic_module
from .hub_utils import (
    HF_HUB_OFFLINE,
    _add_variant,
    _get_model_file,
    extract_commit_hash,
    http_user_agent,
)
from .import_utils import (
    BACKENDS_MAPPING,
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    is_accelerate_available,
    is_accelerate_version,
    is_bsa_available,
    is_flax_available,
    is_ftfy_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_omegaconf_available,
    is_onnx_available,
    is_safetensors_available,
    is_scipy_available,
    is_tensorboard_available,
    is_tf_available,
    is_torch_available,
    is_torch_version,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    is_wandb_available,
    is_xformers_available,
    requires_backends,
)
from .logging import get_logger
from .outputs import BaseOutput
from .pil_utils import PIL_INTERPOLATION, numpy_to_pil, pt_to_pil
from .torch_utils import is_compiled_module, randn_tensor


if is_torch_available():
							from .testing_utils import (
							    floats_tensor,
							    load_hf_numpy,
							    load_image,
							    load_numpy,
							    load_pt,
							    nightly,
							    parse_flag_from_env,
							    print_tensor_test,
							    require_torch_a,
							    require_torch_gpu,
							    skip_mps,
							    slow,
							    torch_all_close,
							    torch_device,
							)
							from .torch_utils import maybe_allow_in_graph

from .testing_utils import export_to_gif, export_to_video


A_			:List[str]	    =		get_logger(__name__)






def 				A	(			a_   )	->		Tuple:
					if version.parse(a_   ) < version.parse(a_   ):
										if "dev" in min_version:
															__UpperCamelCase :   List[str]									=(
															    'This example requires a source install from HuggingFace diffusers (see '
															    '`https://huggingface.co/docs/diffusers/installation#install-from-source`),'
															)
										else:
															__UpperCamelCase :   Tuple									=F'This example requires a minimum version of {min_version},'
										error_message += F' but the version found is {__version__}.\n'
										raise ImportError(a_   )

