
'''simple docstring'''






from copy import deepcopy
from typing import Optional, Union

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_tf_available, is_torch_available


if is_torch_available():
 import torch

if is_tf_available():
 import tensorflow as tf

class  UpperCAmelCase__						(       A ):
    lowerCAmelCase_				    =		['image_processor']
    lowerCAmelCase_				    =		'SamImageProcessor'



    def __init__(	self      :       Any,__A      :       Optional[int]     ):
          super().__init__(__A     )
          _lowerCamelCase				:   Union[str, Any]								=   self.image_processor
          _lowerCamelCase				:   Optional[int]								=   -1_0
          _lowerCamelCase				:   List[str]								=   self.image_processor.size["longest_edge"]



    def __call__(	self      :       Any,__A      :       Tuple=None,__A      :       Any=None,__A      :       Optional[Any]=None,__A      :       Dict=None,__A      :       Optional[Union[str, TensorType]] = None,**__A      :       str,):
          _lowerCamelCase				:   str								=   self.image_processor(
              __A,return_tensors=__A,**__A,)

          # pop arguments that are not used in the foward but used nevertheless
          _lowerCamelCase				:   List[Any]								=   encoding_image_processor["original_sizes"]

          if hasattr(__A,"numpy"     ):  # Checks if Torch or TF tensor
                _lowerCamelCase				:   Dict								=   original_sizes.numpy()

          _lowerCamelCase				:   Union[str, Any]								=   self._check_and_preprocess_points(
              input_points=__A,input_labels=__A,input_boxes=__A,)

          _lowerCamelCase				:   Union[str, Any]								=   self._normalize_and_convert(
              __A,__A,input_points=__A,input_labels=__A,input_boxes=__A,return_tensors=__A,)

          return encoding_image_processor



    def   lowerCamelCase_  (	self      :       List[str],__A      :       List[str],__A      :       Union[str, Any],__A      :       List[str]=None,__A      :       int=None,__A      :       Any=None,__A      :       int="pt",):
          if input_points is not None:
                if len(__A     ) != len(__A     ):
                      _lowerCamelCase				:   Tuple								=   [
                          self._normalize_coordinates(self.target_size,__A,original_sizes[0]     ) for point in input_points
                      ]
                else:
                      _lowerCamelCase				:   Dict								=   [
                          self._normalize_coordinates(self.target_size,__A,__A     )
                          for point, original_size in zip(__A,__A     )
                      ]
                # check that all arrays have the same shape
                if not all(point.shape == input_points[0].shape for point in input_points     ):
                      if input_labels is not None:
                            _lowerCamelCase				:   Dict								=   self._pad_points_and_labels(__A,__A     )

                _lowerCamelCase				:   Optional[int]								=   np.array(__A     )

          if input_labels is not None:
                _lowerCamelCase				:   List[Any]								=   np.array(__A     )

          if input_boxes is not None:
                if len(__A     ) != len(__A     ):
                      _lowerCamelCase				:   Optional[Any]								=   [
                          self._normalize_coordinates(self.target_size,__A,original_sizes[0],is_bounding_box=__A     )
                          for box in input_boxes
                      ]
                else:
                      _lowerCamelCase				:   List[str]								=   [
                          self._normalize_coordinates(self.target_size,__A,__A,is_bounding_box=__A     )
                          for box, original_size in zip(__A,__A     )
                      ]
                _lowerCamelCase				:   Dict								=   np.array(__A     )

          if input_boxes is not None:
                if return_tensors == "pt":
                      _lowerCamelCase				:   str								=   torch.from_numpy(__A     )
                      # boxes batch size of 1 by default
                      _lowerCamelCase				:   int								=   input_boxes.unsqueeze(1     ) if len(input_boxes.shape     ) != 3 else input_boxes
                elif return_tensors == "tf":
                      _lowerCamelCase				:   str								=   tf.convert_to_tensor(__A     )
                      # boxes batch size of 1 by default
                      _lowerCamelCase				:   Optional[Any]								=   tf.expand_dims(__A,1     ) if len(input_boxes.shape     ) != 3 else input_boxes
                encoding_image_processor.update({"input_boxes": input_boxes}     )
          if input_points is not None:
                if return_tensors == "pt":
                      _lowerCamelCase				:   Dict								=   torch.from_numpy(__A     )
                      # point batch size of 1 by default
                      _lowerCamelCase				:   int								=   input_points.unsqueeze(1     ) if len(input_points.shape     ) != 4 else input_points
                elif return_tensors == "tf":
                      _lowerCamelCase				:   Any								=   tf.convert_to_tensor(__A     )
                      # point batch size of 1 by default
                      _lowerCamelCase				:   Any								=   tf.expand_dims(__A,1     ) if len(input_points.shape     ) != 4 else input_points
                encoding_image_processor.update({"input_points": input_points}     )
          if input_labels is not None:
                if return_tensors == "pt":
                      _lowerCamelCase				:   Optional[int]								=   torch.from_numpy(__A     )
                      # point batch size of 1 by default
                      _lowerCamelCase				:   List[str]								=   input_labels.unsqueeze(1     ) if len(input_labels.shape     ) != 3 else input_labels
                elif return_tensors == "tf":
                      _lowerCamelCase				:   Dict								=   tf.convert_to_tensor(__A     )
                      # point batch size of 1 by default
                      _lowerCamelCase				:   Tuple								=   tf.expand_dims(__A,1     ) if len(input_labels.shape     ) != 3 else input_labels
                encoding_image_processor.update({"input_labels": input_labels}     )

          return encoding_image_processor



    def   lowerCamelCase_  (	self      :       List[str],__A      :       Dict,__A      :       str     ):
          _lowerCamelCase				:   Optional[Any]								=   max([point.shape[0] for point in input_points]     )
          _lowerCamelCase				:   Dict								=   []
          for i, point in enumerate(__A     ):
                if point.shape[0] != expected_nb_points:
                      _lowerCamelCase				:   Tuple								=   np.concatenate(
                          [point, np.zeros((expected_nb_points - point.shape[0], 2)     ) + self.point_pad_value],axis=0     )
                      _lowerCamelCase				:   Dict								=   np.append(input_labels[i],[self.point_pad_value]     )
                processed_input_points.append(__A     )
          _lowerCamelCase				:   Tuple								=   processed_input_points
          return input_points, input_labels



    def   lowerCamelCase_  (	self      :       int,__A      :       int,__A      :       np.ndarray,__A      :       Union[str, Any],__A      :       Optional[int]=False     ):
          _lowerCamelCase				:   List[str]								=   original_size
          _lowerCamelCase				:   Union[str, Any]								=   self.image_processor._get_preprocess_shape(__A,longest_edge=__A     )
          _lowerCamelCase				:   str								=   deepcopy(__A     ).astype(__A     )

          if is_bounding_box:
                _lowerCamelCase				:   Dict								=   coords.reshape(-1,2,2     )

          _lowerCamelCase				:   int								=   coords[..., 0] * (new_w / old_w)
          _lowerCamelCase				:   Dict								=   coords[..., 1] * (new_h / old_h)

          if is_bounding_box:
                _lowerCamelCase				:   List[Any]								=   coords.reshape(-1,4     )

          return coords



    def   lowerCamelCase_  (	self      :       List[str],__A      :       str=None,__A      :       Tuple=None,__A      :       List[Any]=None,):
          if input_points is not None:
                if hasattr(__A,"numpy"     ):  # Checks for TF or Torch tensor
                      _lowerCamelCase				:   Optional[int]								=   input_points.numpy().tolist()

                if not isinstance(__A,__A     ) or not isinstance(input_points[0],__A     ):
                      raise ValueError("Input points must be a list of list of floating points."     )
                _lowerCamelCase				:   str								=   [np.array(__A     ) for input_point in input_points]
          else:
                _lowerCamelCase				:   List[str]								=   None

          if input_labels is not None:
                if hasattr(__A,"numpy"     ):
                      _lowerCamelCase				:   Any								=   input_labels.numpy().tolist()

                if not isinstance(__A,__A     ) or not isinstance(input_labels[0],__A     ):
                      raise ValueError("Input labels must be a list of list integers."     )
                _lowerCamelCase				:   str								=   [np.array(__A     ) for label in input_labels]
          else:
                _lowerCamelCase				:   int								=   None

          if input_boxes is not None:
                if hasattr(__A,"numpy"     ):
                      _lowerCamelCase				:   str								=   input_boxes.numpy().tolist()

                if (
                    not isinstance(__A,__A     )
                    or not isinstance(input_boxes[0],__A     )
                    or not isinstance(input_boxes[0][0],__A     )
                ):
                      raise ValueError("Input boxes must be a list of list of list of floating points."     )
                _lowerCamelCase				:   str								=   [np.array(__A     ).astype(np.floataa     ) for box in input_boxes]
          else:
                _lowerCamelCase				:   str								=   None

          return input_points, input_labels, input_boxes



    @property
    def   lowerCamelCase_  (	self      :       Optional[int]     ):
          _lowerCamelCase				:   List[Any]								=   self.image_processor.model_input_names
          return list(dict.fromkeys(__A     )     )



    def   lowerCamelCase_  (	self      :       List[str],*__A      :       int,**__A      :       Union[str, Any]     ):
          return self.image_processor.post_process_masks(*__A,**__A     )

'''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_       :   str   =       logging.get_logger(__name__)  # pylint: disable=invalid-name

UpperCAmelCase_       :   str   =       '\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e-img2img"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n        >>> image = load_image(image_url).convert("RGB")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n        ```\n'

@dataclass
class  UpperCAmelCase__						(       A ):
    lowerCAmelCase_				    =		42


class  UpperCAmelCase__						(       A ):



    def __init__(	self      :       str,__A      :       PriorTransformer,__A      :       CLIPVisionModel,__A      :       CLIPImageProcessor,__A      :       HeunDiscreteScheduler,__A      :       ShapERenderer,):
          super().__init__()

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



    def   lowerCamelCase_  (	self      :       Optional[int],__A      :       str,__A      :       Tuple,__A      :       Any,__A      :       Optional[int],__A      :       Tuple,__A      :       Union[str, Any]     ):
          if latents is None:
                _lowerCamelCase				:   int								=   randn_tensor(__A,generator=__A,device=__A,dtype=__A     )
          else:
                if latents.shape != shape:
                      raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'     )
                _lowerCamelCase				:   Union[str, Any]								=   latents.to(__A     )

          _lowerCamelCase				:   Tuple								=   latents * scheduler.init_noise_sigma
          return latents



    def   lowerCamelCase_  (	self      :       List[str],__A      :       List[Any]=0     ):
          if is_accelerate_available():
                from accelerate import cpu_offload
          else:
                raise ImportError("Please install accelerate via `pip install accelerate`"     )

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

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



    @property
    def   lowerCamelCase_  (	self      :       Optional[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(__A,"_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      :       Tuple,__A      :       int,__A      :       Any,__A      :       str,__A      :       int,):
          if isinstance(__A,__A     ) and isinstance(image[0],torch.Tensor     ):
                _lowerCamelCase				:   Dict								=   torch.cat(__A,axis=0     ) if image[0].ndim == 4 else torch.stack(__A,axis=0     )

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

          _lowerCamelCase				:   Any								=   image.to(dtype=self.image_encoder.dtype,device=__A     )

          _lowerCamelCase				:   List[str]								=   self.image_encoder(__A     )["last_hidden_state"]
          _lowerCamelCase				:   Optional[Any]								=   image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

          _lowerCamelCase				:   Any								=   image_embeds.repeat_interleave(__A,dim=0     )

          if do_classifier_free_guidance:
                _lowerCamelCase				:   int								=   torch.zeros_like(__A     )

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

          return image_embeds



    @torch.no_grad()
    @replace_example_docstring(__A     )
    def __call__(	self      :       Tuple,__A      :       Union[PIL.Image.Image, List[PIL.Image.Image]],__A      :       int = 1,__A      :       int = 2_5,__A      :       Optional[Union[torch.Generator, List[torch.Generator]]] = None,__A      :       Optional[torch.FloatTensor] = None,__A      :       float = 4.0,__A      :       int = 6_4,__A      :       Optional[str] = "pil",__A      :       bool = True,):

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

          _lowerCamelCase				:   Optional[int]								=   self._execution_device

          _lowerCamelCase				:   int								=   batch_size * num_images_per_prompt

          _lowerCamelCase				:   Union[str, Any]								=   guidance_scale > 1.0
          _lowerCamelCase				:   Tuple								=   self._encode_image(__A,__A,__A,__A     )

          # prior

          self.scheduler.set_timesteps(__A,device=__A     )
          _lowerCamelCase				:   List[Any]								=   self.scheduler.timesteps

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

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

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

                _lowerCamelCase				:   List[str]								=   self.prior(
                    __A,timestep=__A,proj_embedding=__A,).predicted_image_embedding

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

                _lowerCamelCase				:   Any								=   self.scheduler.step(
                    __A,timestep=__A,sample=__A,).prev_sample

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

          _lowerCamelCase				:   Any								=   []
          for i, latent in enumerate(__A     ):
                print()
                _lowerCamelCase				:   int								=   self.renderer.decode(
                    latent[None, :],__A,size=__A,ray_batch_size=4_0_9_6,n_coarse_samples=6_4,n_fine_samples=1_2_8,)

                images.append(__A     )

          _lowerCamelCase				:   List[Any]								=   torch.stack(__A     )

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

          _lowerCamelCase				:   Union[str, Any]								=   images.cpu().numpy()

          if output_type == "pil":
                _lowerCamelCase				:   List[str]								=   [self.numpy_to_pil(__A     ) 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=__A     )