



"""simple docstring"""
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


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

_UpperCAmelCase     =							"""
    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 					a	(  UpperCAmelCase__       ):
  UpperCamelCase	:				str     						=					4_2







class 					a	(  UpperCAmelCase__       ):



  def __init__(						self :					List[Any]       ,		lowerCAmelCase :					int       ,		lowerCAmelCase :					int       ,		lowerCAmelCase :					Tuple       ,		lowerCAmelCase :					List[str]       ,		lowerCAmelCase :					Optional[Any]       ,		)     ->					Optional[int]:


     '''simple docstring'''




     super().__init__()

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



  def 	lowerCamelCase__       (						self :					Union[str, Any]       ,		lowerCAmelCase :					int       ,		lowerCAmelCase :					Tuple       ,		lowerCAmelCase :					Tuple       ,		lowerCAmelCase :					Optional[Any]       ,		lowerCAmelCase :					Any       ,		lowerCAmelCase :					int		)     ->					Tuple:


     '''simple docstring'''




     if latents is None:
        SCREAMING_SNAKE_CASE_: Any     			=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}'''		)
        SCREAMING_SNAKE_CASE_: Any     			=latents.to(lowerCAmelCase		)

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



  def 	lowerCamelCase__       (						self :					Union[str, Any]       ,		lowerCAmelCase :					Dict=0		)     ->					Optional[Any]:


     '''simple docstring'''




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

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

     SCREAMING_SNAKE_CASE_: List[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 	lowerCamelCase__       (						self :					Any		)     ->					List[str]:


     '''simple docstring'''




     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 	lowerCamelCase__       (						self :					Dict       ,		lowerCAmelCase :					Optional[Any]       ,		lowerCAmelCase :					Optional[int]       ,		lowerCAmelCase :					str       ,		lowerCAmelCase :					List[Any]       ,		)     ->					Union[str, Any]:


     '''simple docstring'''




     if isinstance(lowerCAmelCase       ,		lowerCAmelCase		) and isinstance(image[0]       ,		torch.Tensor		):
        SCREAMING_SNAKE_CASE_: Any     			=torch.cat(lowerCAmelCase       ,		axis=0		) if image[0].ndim == 4 else torch.stack(lowerCAmelCase       ,		axis=0		)

     if not isinstance(lowerCAmelCase       ,		torch.Tensor		):
        SCREAMING_SNAKE_CASE_: List[str]     			=self.image_processor(lowerCAmelCase       ,		return_tensors="""pt"""		).pixel_values[0].unsqueeze(0		)

     SCREAMING_SNAKE_CASE_: Tuple     			=image.to(dtype=self.image_encoder.dtype       ,		device=lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: List[Any]     			=self.image_encoder(lowerCAmelCase		)["""last_hidden_state"""]
     SCREAMING_SNAKE_CASE_: Dict     			=image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

     SCREAMING_SNAKE_CASE_: Tuple     			=image_embeds.repeat_interleave(lowerCAmelCase       ,		dim=0		)

     if do_classifier_free_guidance:
        SCREAMING_SNAKE_CASE_: str     			=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
        SCREAMING_SNAKE_CASE_: Tuple     			=torch.cat([negative_image_embeds, image_embeds]		)

     return image_embeds





  @torch.no_grad()
  @replace_example_docstring(lowerCAmelCase		)
  def __call__(						self :					Tuple       ,		lowerCAmelCase :					Any       ,		lowerCAmelCase :					Tuple = 1       ,		lowerCAmelCase :					List[str] = 25       ,		lowerCAmelCase :					Optional[int] = None       ,		lowerCAmelCase :					Optional[Any] = None       ,		lowerCAmelCase :					Dict = 4.0       ,		lowerCAmelCase :					str = 64       ,		lowerCAmelCase :					Optional[Any] = "pil"       ,		lowerCAmelCase :					int = True       ,		)     ->					Any:


     '''simple docstring'''




     if isinstance(lowerCAmelCase       ,		PIL.Image.Image		):
        SCREAMING_SNAKE_CASE_: List[Any]     			=1
     elif isinstance(lowerCAmelCase       ,		torch.Tensor		):
        SCREAMING_SNAKE_CASE_: List[Any]     			=image.shape[0]
     elif isinstance(lowerCAmelCase       ,		lowerCAmelCase		) and isinstance(image[0]       ,		(torch.Tensor, PIL.Image.Image)		):
        SCREAMING_SNAKE_CASE_: Optional[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		)}'''		)

     SCREAMING_SNAKE_CASE_: Dict     			=self._execution_device

     SCREAMING_SNAKE_CASE_: Dict     			=batch_size * num_images_per_prompt

     SCREAMING_SNAKE_CASE_: Optional[int]     			=guidance_scale > 1.0
     SCREAMING_SNAKE_CASE_: Dict     			=self._encode_image(lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase		)

     # prior

     self.scheduler.set_timesteps(lowerCAmelCase       ,		device=lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: int     			=self.scheduler.timesteps

     SCREAMING_SNAKE_CASE_: Tuple     			=self.prior.config.num_embeddings
     SCREAMING_SNAKE_CASE_: List[Any]     			=self.prior.config.embedding_dim

     SCREAMING_SNAKE_CASE_: List[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
     SCREAMING_SNAKE_CASE_: Dict     			=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
        SCREAMING_SNAKE_CASE_: Optional[int]     			=torch.cat([latents] * 2		) if do_classifier_free_guidance else latents
        SCREAMING_SNAKE_CASE_: List[Any]     			=self.scheduler.scale_model_input(lowerCAmelCase       ,		lowerCAmelCase		)

        SCREAMING_SNAKE_CASE_: int     			=self.prior(
            lowerCAmelCase       ,		timestep=lowerCAmelCase       ,		proj_embedding=lowerCAmelCase       ,		).predicted_image_embedding

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

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

        SCREAMING_SNAKE_CASE_: str     			=self.scheduler.step(
            lowerCAmelCase       ,		timestep=lowerCAmelCase       ,		sample=lowerCAmelCase       ,		).prev_sample

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

     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=[]
     for i, latent in enumerate(lowerCAmelCase		):
        print()
        SCREAMING_SNAKE_CASE_: Dict     			=self.renderer.decode(
            latent[None, :]       ,		lowerCAmelCase       ,		size=lowerCAmelCase       ,		ray_batch_size=4096       ,		n_coarse_samples=64       ,		n_fine_samples=128       ,		)

        images.append(lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=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}'''		)

     SCREAMING_SNAKE_CASE_: Optional[Any]     			=images.cpu().numpy()

     if output_type == "pil":
        SCREAMING_SNAKE_CASE_: Optional[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		)








"""simple docstring"""
import gc
import unittest

from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
   import jax
   import jax.numpy as jnp
   from flax.jax_utils import replicate
   from flax.training.common_utils import shard
@slow
@require_flax
class 					a	(  unittest.TestCase       ):



  def 	lowerCamelCase__       (						self :					Dict		)     ->					str:


     '''simple docstring'''




     super().tearDown()
     gc.collect()



  def 	lowerCamelCase__       (						self :					Optional[Any]		)     ->					int:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_			,		SCREAMING_SNAKE_CASE_: Dict     			=FlaxStableDiffusionPipeline.from_pretrained(
         """stabilityai/stable-diffusion-2"""       ,		revision="""bf16"""       ,		dtype=jnp.bfloataa       ,		)

     SCREAMING_SNAKE_CASE_: Union[str, Any]     			="""A painting of a squirrel eating a burger"""
     SCREAMING_SNAKE_CASE_: Any     			=jax.device_count()
     SCREAMING_SNAKE_CASE_: Dict     			=num_samples * [prompt]
     SCREAMING_SNAKE_CASE_: List[Any]     			=sd_pipe.prepare_inputs(lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=replicate(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=shard(lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Dict     			=jax.random.PRNGKey(0		)
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=jax.random.split(lowerCAmelCase       ,		jax.device_count()		)

     SCREAMING_SNAKE_CASE_: Tuple     			=sd_pipe(lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		num_inference_steps=25       ,		jit=lowerCAmelCase		)[0]
     assert images.shape == (jax.device_count(), 1, 768, 768, 3)

     SCREAMING_SNAKE_CASE_: Dict     			=images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]		)
     SCREAMING_SNAKE_CASE_: Dict     			=images[0, 253:256, 253:256, -1]

     SCREAMING_SNAKE_CASE_: Optional[int]     			=jnp.asarray(jax.device_get(image_slice.flatten()		)		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=jnp.array([0.4_2_3_8, 0.4_4_1_4, 0.4_3_9_5, 0.4_4_5_3, 0.4_6_2_9, 0.4_5_9_0, 0.4_5_3_1, 0.4_5_5_0_8, 0.4_5_1_2]		)
     print(f'''output_slice: {output_slice}'''		)
     assert jnp.abs(output_slice - expected_slice		).max() < 1E-2





  def 	lowerCamelCase__       (						self :					List[str]		)     ->					Dict:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: int     			="""stabilityai/stable-diffusion-2"""
     SCREAMING_SNAKE_CASE_			,		SCREAMING_SNAKE_CASE_: Optional[int]     			=FlaxDPMSolverMultistepScheduler.from_pretrained(lowerCAmelCase       ,		subfolder="""scheduler"""		)
     SCREAMING_SNAKE_CASE_			,		SCREAMING_SNAKE_CASE_: Optional[int]     			=FlaxStableDiffusionPipeline.from_pretrained(
         lowerCAmelCase       ,		scheduler=lowerCAmelCase       ,		revision="""bf16"""       ,		dtype=jnp.bfloataa       ,		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=scheduler_params

     SCREAMING_SNAKE_CASE_: Tuple     			="""A painting of a squirrel eating a burger"""
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=jax.device_count()
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=num_samples * [prompt]
     SCREAMING_SNAKE_CASE_: List[Any]     			=sd_pipe.prepare_inputs(lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Tuple     			=replicate(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=shard(lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Any     			=jax.random.PRNGKey(0		)
     SCREAMING_SNAKE_CASE_: Any     			=jax.random.split(lowerCAmelCase       ,		jax.device_count()		)

     SCREAMING_SNAKE_CASE_: Tuple     			=sd_pipe(lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		num_inference_steps=25       ,		jit=lowerCAmelCase		)[0]
     assert images.shape == (jax.device_count(), 1, 768, 768, 3)

     SCREAMING_SNAKE_CASE_: str     			=images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]		)
     SCREAMING_SNAKE_CASE_: Any     			=images[0, 253:256, 253:256, -1]

     SCREAMING_SNAKE_CASE_: Optional[Any]     			=jnp.asarray(jax.device_get(image_slice.flatten()		)		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=jnp.array([0.4_3_3_6, 0.4_2_9_6_9, 0.4_4_5_3, 0.4_1_9_9, 0.4_2_9_7, 0.4_5_3_1, 0.4_4_3_4, 0.4_4_3_4, 0.4_2_9_7]		)
     print(f'''output_slice: {output_slice}'''		)
     assert jnp.abs(output_slice - expected_slice		).max() < 1E-2



