



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 	lowerCamelCase__	(       _A):



 """simple docstring"""

 a__					: Union[PIL.Image.Image, np.ndarray]


class 	lowerCamelCase__	(       _A):



 """simple docstring"""

 def __init__(    self					:					int			,						__lowerCAmelCase					:					PriorTransformer			,						__lowerCAmelCase					:					CLIPVisionModel			,						__lowerCAmelCase					:					CLIPImageProcessor			,						__lowerCAmelCase					:					HeunDiscreteScheduler			,						__lowerCAmelCase					:					ShapERenderer			,						)   ->	List[str]:
    super().__init__()

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

 def     snake_case_      (    self					:					Optional[int]			,						__lowerCAmelCase					:					Optional[Any]			,						__lowerCAmelCase					:					List[Any]			,						__lowerCAmelCase					:					Optional[int]			,						__lowerCAmelCase					:					List[str]			,						__lowerCAmelCase					:					str			,						__lowerCAmelCase					:					Tuple      )   ->	int:
    if latents is None:
       _A      =       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}'''      )
       _A      =       latents.to(__lowerCAmelCase      )

    _A      =       latents * scheduler.init_noise_sigma
    return latents

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

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

    _A      =       [self.image_encoder, self.prior]
    for cpu_offloaded_model in models:
       if cpu_offloaded_model is not None:
          cpu_offload(__lowerCAmelCase			,						__lowerCAmelCase      )

 @property
 def     snake_case_      (    self					:					int      )   ->	List[Any]:
    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     snake_case_      (    self					:					List[str]			,						__lowerCAmelCase					:					str			,						__lowerCAmelCase					:					Optional[Any]			,						__lowerCAmelCase					:					List[Any]			,						__lowerCAmelCase					:					Dict			,						)   ->	Optional[int]:
    if isinstance(__lowerCAmelCase			,						__lowerCAmelCase      ) and isinstance(image[0]			,						torch.Tensor      ):
       _A      =       torch.cat(__lowerCAmelCase			,						axis=0      ) if image[0].ndim == 4 else torch.stack(__lowerCAmelCase			,						axis=0      )

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

    _A      =       image.to(dtype=self.image_encoder.dtype			,						device=__lowerCAmelCase      )

    _A      =       self.image_encoder(__lowerCAmelCase      )['''last_hidden_state''']
    _A      =       image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

    _A      =       image_embeds.repeat_interleave(__lowerCAmelCase			,						dim=0      )

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

    return image_embeds

 @torch.no_grad()
 @replace_example_docstring(__lowerCAmelCase      )
 def __call__(    self					:					str			,						__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			,						)   ->	Tuple:

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

    _A      =       self._execution_device

    _A      =       batch_size * num_images_per_prompt

    _A      =       guidance_scale > 1.0
    _A      =       self._encode_image(__lowerCAmelCase			,						__lowerCAmelCase			,						__lowerCAmelCase			,						__lowerCAmelCase      )

    # prior

    self.scheduler.set_timesteps(__lowerCAmelCase			,						device=__lowerCAmelCase      )
    _A      =       self.scheduler.timesteps

    _A      =       self.prior.config.num_embeddings
    _A      =       self.prior.config.embedding_dim

    _A      =       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
    _A      =       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
       _A      =       torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents
       _A      =       self.scheduler.scale_model_input(__lowerCAmelCase			,						__lowerCAmelCase      )

       _A      =       self.prior(
           __lowerCAmelCase			,						timestep=__lowerCAmelCase			,						proj_embedding=__lowerCAmelCase			,						).predicted_image_embedding

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

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

       _A      =       self.scheduler.step(
           __lowerCAmelCase			,						timestep=__lowerCAmelCase			,						sample=__lowerCAmelCase			,						).prev_sample

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

    _A      =       []
    for i, latent in enumerate(__lowerCAmelCase      ):
       print()
       _A      =       self.renderer.decode(
           latent[None, :]			,						__lowerCAmelCase			,						size=__lowerCAmelCase			,						ray_batch_size=40_96			,						n_coarse_samples=64			,						n_fine_samples=1_28			,						)

       images.append(__lowerCAmelCase      )

    _A      =       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}'''      )

    _A      =       images.cpu().numpy()

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











import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()


class     _a							(	UpperCAmelCase__    ,							UpperCAmelCase__    ,							unittest.TestCase     ):






  """simple docstring"""





  A_						       = StableDiffusionSAGPipeline
  A_						       = TEXT_TO_IMAGE_PARAMS
  A_						       = TEXT_TO_IMAGE_BATCH_PARAMS
  A_						       = TEXT_TO_IMAGE_IMAGE_PARAMS
  A_						       = TEXT_TO_IMAGE_IMAGE_PARAMS
  A_						       = False




  def  _UpperCAmelCase  (  self			)      ->			Optional[Any]:
     torch.manual_seed(0			)
     UpperCamelCase_						=  UNetaDConditionModel(
         block_out_channels=(32, 64)		,		layers_per_block=2		,		sample_size=32		,		in_channels=4		,		out_channels=4		,		down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')		,		up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')		,		cross_attention_dim=32		,		)
     UpperCamelCase_						=  DDIMScheduler(
         beta_start=0.0_0_0_8_5		,		beta_end=0.0_1_2		,		beta_schedule='scaled_linear'		,		clip_sample=_UpperCAmelCase		,		set_alpha_to_one=_UpperCAmelCase		,		)
     torch.manual_seed(0			)
     UpperCamelCase_						=  AutoencoderKL(
         block_out_channels=[32, 64]		,		in_channels=3		,		out_channels=3		,		down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']		,		up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']		,		latent_channels=4		,		)
     torch.manual_seed(0			)
     UpperCamelCase_						=  CLIPTextConfig(
         bos_token_id=0		,		eos_token_id=2		,		hidden_size=32		,		intermediate_size=37		,		layer_norm_eps=1e-05		,		num_attention_heads=4		,		num_hidden_layers=5		,		pad_token_id=1		,		vocab_size=1000		,		)
     UpperCamelCase_						=  CLIPTextModel(_UpperCAmelCase			)
     UpperCamelCase_						=  CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'			)

     UpperCamelCase_						=  {
         'unet': unet,
         'scheduler': scheduler,
         'vae': vae,
         'text_encoder': text_encoder,
         'tokenizer': tokenizer,
         'safety_checker': None,
         'feature_extractor': None,
     }
     return components




  def  _UpperCAmelCase  (  self		,		_UpperCAmelCase		,		_UpperCAmelCase=0			)      ->			List[Any]:
     if str(_UpperCAmelCase			).startswith('mps'			):
        UpperCamelCase_						=  torch.manual_seed(_UpperCAmelCase			)
     else:
        UpperCamelCase_						=  torch.Generator(device=_UpperCAmelCase			).manual_seed(_UpperCAmelCase			)
     UpperCamelCase_						=  {
         'prompt': '.',
         'generator': generator,
         'num_inference_steps': 2,
         'guidance_scale': 1.0,
         'sag_scale': 1.0,
         'output_type': 'numpy',
     }
     return inputs




  def  _UpperCAmelCase  (  self			)      ->			Tuple:
     super().test_inference_batch_single_identical(expected_max_diff=3e-3			)




@slow
@require_torch_gpu
class     _a							(	unittest.TestCase     ):






  """simple docstring"""





  def  _UpperCAmelCase  (  self			)      ->			Tuple:
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()




  def  _UpperCAmelCase  (  self			)      ->			str:
     UpperCamelCase_						=  StableDiffusionSAGPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'			)
     UpperCamelCase_						=  sag_pipe.to(_UpperCAmelCase			)
     sag_pipe.set_progress_bar_config(disable=_UpperCAmelCase			)

     UpperCamelCase_						=  '.'
     UpperCamelCase_						=  torch.manual_seed(0			)
     UpperCamelCase_						=  sag_pipe(
         [prompt]		,		generator=_UpperCAmelCase		,		guidance_scale=7.5		,		sag_scale=1.0		,		num_inference_steps=20		,		output_type='np'			)

     UpperCamelCase_						=  output.images

     UpperCamelCase_						=  image[0, -3:, -3:, -1]

     assert image.shape == (1, 512, 512, 3)
     UpperCamelCase_						=  np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9]			)

     assert np.abs(image_slice.flatten() - expected_slice			).max() < 5e-2




  def  _UpperCAmelCase  (  self			)      ->			List[Any]:
     UpperCamelCase_						=  StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'			)
     UpperCamelCase_						=  sag_pipe.to(_UpperCAmelCase			)
     sag_pipe.set_progress_bar_config(disable=_UpperCAmelCase			)

     UpperCamelCase_						=  '.'
     UpperCamelCase_						=  torch.manual_seed(0			)
     UpperCamelCase_						=  sag_pipe(
         [prompt]		,		generator=_UpperCAmelCase		,		guidance_scale=7.5		,		sag_scale=1.0		,		num_inference_steps=20		,		output_type='np'			)

     UpperCamelCase_						=  output.images

     UpperCamelCase_						=  image[0, -3:, -3:, -1]

     assert image.shape == (1, 512, 512, 3)
     UpperCamelCase_						=  np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1]			)

     assert np.abs(image_slice.flatten() - expected_slice			).max() < 5e-2




  def  _UpperCAmelCase  (  self			)      ->			Dict:
     UpperCamelCase_						=  StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'			)
     UpperCamelCase_						=  sag_pipe.to(_UpperCAmelCase			)
     sag_pipe.set_progress_bar_config(disable=_UpperCAmelCase			)

     UpperCamelCase_						=  '.'
     UpperCamelCase_						=  torch.manual_seed(0			)
     UpperCamelCase_						=  sag_pipe(
         [prompt]		,		width=768		,		height=512		,		generator=_UpperCAmelCase		,		guidance_scale=7.5		,		sag_scale=1.0		,		num_inference_steps=20		,		output_type='np'		,		)

     UpperCamelCase_						=  output.images

     assert image.shape == (1, 512, 768, 3)





