




from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

__lowerCamelCase   :						List[str]				=			'''
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        >>> repo = "openai/shap-e-img2img"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 3.0
        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"
        >>> image = load_image(image_url).convert("RGB")

        >>> images = pipe(
        ...     image,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")
        ```
'''


@dataclass
class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			UpperCamelCase__								=42






class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			def __init__( self			:   Tuple       ,						lowerCamelCase_			:   PriorTransformer       ,						lowerCamelCase_			:   CLIPVisionModel       ,						lowerCamelCase_			:   CLIPImageProcessor       ,						lowerCamelCase_			:   HeunDiscreteScheduler       ,						lowerCamelCase_			:   ShapERenderer       ,						)						->   List[Any]:
								super().__init__()

								self.register_modules(
								    prior=lowerCamelCase_       ,						image_encoder=lowerCamelCase_       ,						image_processor=lowerCamelCase_       ,						scheduler=lowerCamelCase_       ,						renderer=lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   Optional[int]       ,						lowerCamelCase_			:   Union[str, Any]       ,						lowerCamelCase_			:   List[Any]       ,						lowerCamelCase_			:   Union[str, Any]       ,						lowerCamelCase_			:   List[Any]       ,						lowerCamelCase_			:   Tuple       ,						lowerCamelCase_			:   Dict  )						->   List[Any]:
								if latents is None:
													__magic_name__							:	int    							=							randn_tensor(lowerCamelCase_       ,						generator=lowerCamelCase_       ,						device=lowerCamelCase_       ,						dtype=lowerCamelCase_  )
								else:
													if latents.shape != shape:
																		raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}'''  )
													__magic_name__							:	int    							=							latents.to(lowerCamelCase_  )

								__magic_name__							:	Union[str, Any]    							=							latents * scheduler.init_noise_sigma
								return latents

			def 							UpperCAmelCase__       ( self			:   List[str]       ,						lowerCamelCase_			:   Optional[int]=0  )						->   Optional[int]:
								if is_accelerate_available():
													from accelerate import cpu_offload
								else:
													raise ImportError('''Please install accelerate via `pip install accelerate`'''  )

								__magic_name__							:	Tuple    							=							torch.device(F'''cuda:{gpu_id}'''  )

								__magic_name__							:	Optional[Any]    							=							[self.image_encoder, self.prior]
								for cpu_offloaded_model in models:
													if cpu_offloaded_model is not None:
																		cpu_offload(lowerCamelCase_       ,						lowerCamelCase_  )

			@property
			def 							UpperCAmelCase__       ( self			:   Tuple  )						->   Tuple:
								if self.device != torch.device('''meta'''  ) or not hasattr(self.image_encoder       ,						'''_hf_hook'''  ):
													return self.device
								for module in self.image_encoder.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

			def 							UpperCAmelCase__       ( self			:   Union[str, Any]       ,						lowerCamelCase_			:   Optional[int]       ,						lowerCamelCase_			:   List[Any]       ,						lowerCamelCase_			:   Tuple       ,						lowerCamelCase_			:   Union[str, Any]       ,						)						->   Any:
								if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) and isinstance(image[0]       ,						torch.Tensor  ):
													__magic_name__							:	str    							=							torch.cat(lowerCamelCase_       ,						axis=0  ) if image[0].ndim == 4 else torch.stack(lowerCamelCase_       ,						axis=0  )

								if not isinstance(lowerCamelCase_       ,						torch.Tensor  ):
													__magic_name__							:	int    							=							self.image_processor(lowerCamelCase_       ,						return_tensors='''pt'''  ).pixel_values[0].unsqueeze(0  )

								__magic_name__							:	Union[str, Any]    							=							image.to(dtype=self.image_encoder.dtype       ,						device=lowerCamelCase_  )

								__magic_name__							:	Dict    							=							self.image_encoder(lowerCamelCase_  )['''last_hidden_state''']
								__magic_name__							:	List[Any]    							=							image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

								__magic_name__							:	str    							=							image_embeds.repeat_interleave(lowerCamelCase_       ,						dim=0  )

								if do_classifier_free_guidance:
													__magic_name__							:	Tuple    							=							torch.zeros_like(lowerCamelCase_  )

													# For classifier free guidance, we need to do two forward passes.
													# Here we concatenate the unconditional and text embeddings into a single batch
													# to avoid doing two forward passes
													__magic_name__							:	Union[str, Any]    							=							torch.cat([negative_image_embeds, image_embeds]  )

								return image_embeds


			@torch.no_grad()
			@replace_example_docstring(lowerCamelCase_  )
			def __call__( self			:   List[Any]       ,						lowerCamelCase_			:   Union[PIL.Image.Image, List[PIL.Image.Image]]       ,						lowerCamelCase_			:   int = 1       ,						lowerCamelCase_			:   int = 25       ,						lowerCamelCase_			:   Optional[Union[torch.Generator, List[torch.Generator]]] = None       ,						lowerCamelCase_			:   Optional[torch.FloatTensor] = None       ,						lowerCamelCase_			:   float = 4.0       ,						lowerCamelCase_			:   int = 64       ,						lowerCamelCase_			:   Optional[str] = "pil"       ,						lowerCamelCase_			:   bool = True       ,						)						->   str:

								if isinstance(lowerCamelCase_       ,						PIL.Image.Image  ):
													__magic_name__							:	str    							=							1
								elif isinstance(lowerCamelCase_       ,						torch.Tensor  ):
													__magic_name__							:	str    							=							image.shape[0]
								elif isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) and isinstance(image[0]       ,						(torch.Tensor, PIL.Image.Image)  ):
													__magic_name__							:	int    							=							len(lowerCamelCase_  )
								else:
													raise ValueError(
													    F'''`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(lowerCamelCase_  )}'''  )

								__magic_name__							:	str    							=							self._execution_device

								__magic_name__							:	Tuple    							=							batch_size * num_images_per_prompt

								__magic_name__							:	Optional[Any]    							=							guidance_scale > 1.0
								__magic_name__							:	int    							=							self._encode_image(lowerCamelCase_       ,						lowerCamelCase_       ,						lowerCamelCase_       ,						lowerCamelCase_  )

								# prior

								self.scheduler.set_timesteps(lowerCamelCase_       ,						device=lowerCamelCase_  )
								__magic_name__							:	List[str]    							=							self.scheduler.timesteps

								__magic_name__							:	Union[str, Any]    							=							self.prior.config.num_embeddings
								__magic_name__							:	List[str]    							=							self.prior.config.embedding_dim

								__magic_name__							:	str    							=							self.prepare_latents(
								    (batch_size, num_embeddings * embedding_dim)       ,						image_embeds.dtype       ,						lowerCamelCase_       ,						lowerCamelCase_       ,						lowerCamelCase_       ,						self.scheduler       ,						)

								# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
								__magic_name__							:	Union[str, Any]    							=							latents.reshape(latents.shape[0]       ,						lowerCamelCase_       ,						lowerCamelCase_  )

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

													__magic_name__							:	int    							=							self.prior(
													    lowerCamelCase_       ,						timestep=lowerCamelCase_       ,						proj_embedding=lowerCamelCase_       ,						).predicted_image_embedding

													# remove the variance
													__magic_name__							,    __magic_name__							:	Dict    							=							noise_pred.split(
													    scaled_model_input.shape[2]       ,						dim=2  )  # batch_size, num_embeddings, embedding_dim

													if do_classifier_free_guidance is not None:
																		__magic_name__							,    __magic_name__							:	Any    							=							noise_pred.chunk(2  )
																		__magic_name__							:	int    							=							noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

													__magic_name__							:	Tuple    							=							self.scheduler.step(
													    lowerCamelCase_       ,						timestep=lowerCamelCase_       ,						sample=lowerCamelCase_       ,						).prev_sample

								if output_type == "latent":
													return ShapEPipelineOutput(images=lowerCamelCase_  )

								__magic_name__							:	List[str]    							=							[]
								for i, latent in enumerate(lowerCamelCase_  ):
													print()
													__magic_name__							:	str    							=							self.renderer.decode(
													    latent[None, :]       ,						lowerCamelCase_       ,						size=lowerCamelCase_       ,						ray_batch_size=4096       ,						n_coarse_samples=64       ,						n_fine_samples=128       ,						)

													images.append(lowerCamelCase_  )

								__magic_name__							:	str    							=							torch.stack(lowerCamelCase_  )

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

								__magic_name__							:	Optional[int]    							=							images.cpu().numpy()

								if output_type == "pil":
													__magic_name__							:	Union[str, Any]    							=							[self.numpy_to_pil(lowerCamelCase_  ) for image in images]

								# Offload last model to CPU
								if hasattr(self       ,						'''final_offload_hook'''  ) and self.final_offload_hook is not None:
													self.final_offload_hook.offload()

								if not return_dict:
													return (images,)

								return ShapEPipelineOutput(images=lowerCamelCase_  )









# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works

from ...utils import deprecate
from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline  # noqa: F401


deprecate(
    '''stable diffusion controlnet''',
    '''0.22.0''',
    '''Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.''',
    standard_warn=False,
    stacklevel=3,
)



