





'''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


lowerCAmelCase					:     Union[str, Any]												=logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCAmelCase					:     Union[str, Any]												='''
    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_   (				_lowerCAmelCase							):
     __A      =			42







class       a_   (				_lowerCAmelCase							):





     def __init__( self		:					Tuple	,      lowercase		:					PriorTransformer	,      lowercase		:					CLIPVisionModel	,      lowercase		:					CLIPImageProcessor	,      lowercase		:					HeunDiscreteScheduler	,      lowercase		:					ShapERenderer	,      ):





        """simple docstring"""




        super().__init__()

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





     def 							lowercase__      ( self		:					int	,      lowercase		:					Any	,      lowercase		:					Union[str, Any]	,      lowercase		:					Optional[Any]	,      lowercase		:					Any	,      lowercase		:					Any	,      lowercase		:					Dict						):





        """simple docstring"""




        if latents is None:
           lowercase_			:Any    			= randn_tensor(lowercase	,      generator=lowercase	,      device=lowercase	,      dtype=lowercase						)
        else:
           if latents.shape != shape:
              raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}'						)
           lowercase_			:Dict    			= latents.to(lowercase						)

        lowercase_			:str    			= latents * scheduler.init_noise_sigma
        return latents





     def 							lowercase__      ( self		:					List[str]	,      lowercase		:					int=0						):





        """simple docstring"""




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

        lowercase_			:Dict    			= torch.device(F'cuda:{gpu_id}'						)

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





     @property
     def 							lowercase__      ( self		:					List[Any]						):





        """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(lowercase	,      "_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 							lowercase__      ( self		:					List[Any]	,      lowercase		:					Any	,      lowercase		:					int	,      lowercase		:					Optional[Any]	,      lowercase		:					Optional[int]	,      ):





        """simple docstring"""




        if isinstance(lowercase	,      lowercase						) and isinstance(image[0]	,      torch.Tensor						):
           lowercase_			:int    			= torch.cat(lowercase	,      axis=0						) if image[0].ndim == 4 else torch.stack(lowercase	,      axis=0						)

        if not isinstance(lowercase	,      torch.Tensor						):
           lowercase_			:Union[str, Any]    			= self.image_processor(lowercase	,      return_tensors="pt"						).pixel_values[0].unsqueeze(0						)

        lowercase_			:Dict    			= image.to(dtype=self.image_encoder.dtype	,      device=lowercase						)

        lowercase_			:Optional[Any]    			= self.image_encoder(lowercase						)["last_hidden_state"]
        lowercase_			:Optional[int]    			= image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

        lowercase_			:Tuple    			= image_embeds.repeat_interleave(lowercase	,      dim=0						)

        if do_classifier_free_guidance:
           lowercase_			:Tuple    			= torch.zeros_like(lowercase						)

           # 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
           lowercase_			:Any    			= torch.cat([negative_image_embeds, image_embeds]						)

        return image_embeds







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





        """simple docstring"""




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

        lowercase_			:List[str]    			= self._execution_device

        lowercase_			:Optional[Any]    			= batch_size * num_images_per_prompt

        lowercase_			:str    			= guidance_scale > 1.0
        lowercase_			:List[Any]    			= self._encode_image(lowercase	,      lowercase	,      lowercase	,      lowercase						)

        # prior

        self.scheduler.set_timesteps(lowercase	,      device=lowercase						)
        lowercase_			:Dict    			= self.scheduler.timesteps

        lowercase_			:Tuple    			= self.prior.config.num_embeddings
        lowercase_			:Dict    			= self.prior.config.embedding_dim

        lowercase_			:Union[str, Any]    			= self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim)	,      image_embeds.dtype	,      lowercase	,      lowercase	,      lowercase	,      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
        lowercase_			:List[Any]    			= latents.reshape(latents.shape[0]	,      lowercase	,      lowercase						)

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

           lowercase_			:Union[str, Any]    			= self.prior(
               lowercase	,      timestep=lowercase	,      proj_embedding=lowercase	,      ).predicted_image_embedding

           # remove the variance
           lowercase_			,							lowercase_			:Union[str, 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:
              lowercase_			,							lowercase_			:Optional[int]    			= noise_pred.chunk(2						)
              lowercase_			:Tuple    			= noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

           lowercase_			:int    			= self.scheduler.step(
               lowercase	,      timestep=lowercase	,      sample=lowercase	,      ).prev_sample

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

        lowercase_			:Dict    			= []
        for i, latent in enumerate(lowercase						):
           print()
           lowercase_			:Tuple    			= self.renderer.decode(
               latent[None, :]	,      lowercase	,      size=lowercase	,      ray_batch_size=4_096	,      n_coarse_samples=64	,      n_fine_samples=128	,      )

           images.append(lowercase						)

        lowercase_			:str    			= torch.stack(lowercase						)

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

        lowercase_			:Dict    			= images.cpu().numpy()

        if output_type == "pil":
           lowercase_			:int    			= [self.numpy_to_pil(lowercase						) 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=lowercase						)









'''simple docstring'''


import unittest

from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate
def 							UpperCAmelCase_  (						__lowerCamelCase					:					List[Any] ):
   return x + 2


class       a_   (				unittest.TestCase							):





     def 							lowercase__      ( self		:					Optional[Any]						):





        """simple docstring"""




        lowercase_			:Optional[int]    			= "x = 3"
        lowercase_			:Any    			= {}
        lowercase_			:Any    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        assert result == 3
        self.assertDictEqual(lowercase	,      {"x": 3}						)

        lowercase_			:Dict    			= "x = y"
        lowercase_			:Dict    			= {"y": 5}
        lowercase_			:str    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        # evaluate returns the value of the last assignment.
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 5, "y": 5}						)





     def 							lowercase__      ( self		:					List[Any]						):





        """simple docstring"""




        lowercase_			:Dict    			= "y = add_two(x)"
        lowercase_			:Optional[Any]    			= {"x": 3}
        lowercase_			:int    			= evaluate(lowercase	,      {"add_two": add_two}	,      state=lowercase						)
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 3, "y": 5}						)

        # Won't work without the tool
        with CaptureStdout() as out:
           lowercase_			:List[Any]    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        assert result is None
        assert "tried to execute add_two" in out.out





     def 							lowercase__      ( self		:					int						):





        """simple docstring"""




        lowercase_			:Optional[int]    			= "x = 3"
        lowercase_			:Any    			= {}
        lowercase_			:Any    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        assert result == 3
        self.assertDictEqual(lowercase	,      {"x": 3}						)





     def 							lowercase__      ( self		:					Any						):





        """simple docstring"""




        lowercase_			:Optional[Any]    			= "test_dict = {'x': x, 'y': add_two(x)}"
        lowercase_			:List[str]    			= {"x": 3}
        lowercase_			:Any    			= evaluate(lowercase	,      {"add_two": add_two}	,      state=lowercase						)
        self.assertDictEqual(lowercase	,      {"x": 3, "y": 5}						)
        self.assertDictEqual(lowercase	,      {"x": 3, "test_dict": {"x": 3, "y": 5}}						)





     def 							lowercase__      ( self		:					Optional[Any]						):





        """simple docstring"""




        lowercase_			:Optional[int]    			= "x = 3\ny = 5"
        lowercase_			:Union[str, Any]    			= {}
        lowercase_			:Optional[int]    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        # evaluate returns the value of the last assignment.
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 3, "y": 5}						)





     def 							lowercase__      ( self		:					List[Any]						):





        """simple docstring"""




        lowercase_			:List[str]    			= "text = f'This is x: {x}.'"
        lowercase_			:int    			= {"x": 3}
        lowercase_			:int    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        # evaluate returns the value of the last assignment.
        assert result == "This is x: 3."
        self.assertDictEqual(lowercase	,      {"x": 3, "text": "This is x: 3."}						)





     def 							lowercase__      ( self		:					Optional[int]						):





        """simple docstring"""




        lowercase_			:List[Any]    			= "if x <= 3:\n    y = 2\nelse:\n    y = 5"
        lowercase_			:List[str]    			= {"x": 3}
        lowercase_			:Union[str, Any]    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        # evaluate returns the value of the last assignment.
        assert result == 2
        self.assertDictEqual(lowercase	,      {"x": 3, "y": 2}						)

        lowercase_			:List[str]    			= {"x": 8}
        lowercase_			:Tuple    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        # evaluate returns the value of the last assignment.
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 8, "y": 5}						)





     def 							lowercase__      ( self		:					Dict						):





        """simple docstring"""




        lowercase_			:Any    			= "test_list = [x, add_two(x)]"
        lowercase_			:Optional[int]    			= {"x": 3}
        lowercase_			:List[str]    			= evaluate(lowercase	,      {"add_two": add_two}	,      state=lowercase						)
        self.assertListEqual(lowercase	,      [3, 5]						)
        self.assertDictEqual(lowercase	,      {"x": 3, "test_list": [3, 5]}						)





     def 							lowercase__      ( self		:					List[Any]						):





        """simple docstring"""




        lowercase_			:str    			= "y = x"
        lowercase_			:Any    			= {"x": 3}
        lowercase_			:Tuple    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        assert result == 3
        self.assertDictEqual(lowercase	,      {"x": 3, "y": 3}						)





     def 							lowercase__      ( self		:					Any						):





        """simple docstring"""




        lowercase_			:List[Any]    			= "test_list = [x, add_two(x)]\ntest_list[1]"
        lowercase_			:Dict    			= {"x": 3}
        lowercase_			:Any    			= evaluate(lowercase	,      {"add_two": add_two}	,      state=lowercase						)
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 3, "test_list": [3, 5]}						)

        lowercase_			:Union[str, Any]    			= "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']"
        lowercase_			:List[Any]    			= {"x": 3}
        lowercase_			:List[Any]    			= evaluate(lowercase	,      {"add_two": add_two}	,      state=lowercase						)
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 3, "test_dict": {"x": 3, "y": 5}}						)







     def 							lowercase__      ( self		:					Any						):





        """simple docstring"""




        lowercase_			:Dict    			= "x = 0\nfor i in range(3):\n    x = i"
        lowercase_			:Any    			= {}
        lowercase_			:Tuple    			= evaluate(lowercase	,      {"range": range}	,      state=lowercase						)
        assert result == 2
        self.assertDictEqual(lowercase	,      {"x": 2, "i": 2}						)


