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

__lowerCamelCase							=       """
    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   UpperCAmelCase		(						A_ ):
   A__					:		Union[PIL.Image.Image, np.ndarray]






class   UpperCAmelCase		(						A_ ):



   def __init__(self		:					Any    ,						snake_case__		:					PriorTransformer    ,						snake_case__		:					CLIPVisionModel    ,						snake_case__		:					CLIPImageProcessor    ,						snake_case__		:					HeunDiscreteScheduler    ,						snake_case__		:					ShapERenderer    ,						)		->	Optional[int]:


          '''simple docstring'''


          super().__init__()

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



   def 				_SCREAMING_SNAKE_CASE   (self		:					str    ,						snake_case__		:					str    ,						snake_case__		:					Dict    ,						snake_case__		:					str    ,						snake_case__		:					Dict    ,						snake_case__		:					int    ,						snake_case__		:					Optional[int] )		->	Tuple:


          '''simple docstring'''


          if latents is None:
                 snake_case       :   Tuple							=      randn_tensor(snake_case__    ,						generator=snake_case__    ,						device=snake_case__    ,						dtype=snake_case__ )
          else:
                 if latents.shape != shape:
                        raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}""" )
                 snake_case       :   List[Any]							=      latents.to(snake_case__ )

          snake_case       :   List[Any]							=      latents * scheduler.init_noise_sigma
          return latents



   def 				_SCREAMING_SNAKE_CASE   (self		:					Optional[Any]    ,						snake_case__		:					Union[str, Any]=0 )		->	Tuple:


          '''simple docstring'''


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

          snake_case       :   Tuple							=      torch.device(f"""cuda:{gpu_id}""" )

          snake_case       :   List[str]							=      [self.image_encoder, self.prior]
          for cpu_offloaded_model in models:
                 if cpu_offloaded_model is not None:
                        cpu_offload(snake_case__    ,						snake_case__ )



   @property
   def 				_SCREAMING_SNAKE_CASE   (self		:					List[Any] )		->	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(snake_case__    ,						"_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 				_SCREAMING_SNAKE_CASE   (self		:					List[Any]    ,						snake_case__		:					int    ,						snake_case__		:					Dict    ,						snake_case__		:					Any    ,						snake_case__		:					Optional[int]    ,						)		->	Optional[Any]:


          '''simple docstring'''


          if isinstance(snake_case__    ,						snake_case__ ) and isinstance(image[0]    ,						torch.Tensor ):
                 snake_case       :   str							=      torch.cat(snake_case__    ,						axis=0 ) if image[0].ndim == 4 else torch.stack(snake_case__    ,						axis=0 )

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

          snake_case       :   int							=      image.to(dtype=self.image_encoder.dtype    ,						device=snake_case__ )

          snake_case       :   Tuple							=      self.image_encoder(snake_case__ )["last_hidden_state"]
          snake_case       :   List[str]							=      image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

          snake_case       :   List[str]							=      image_embeds.repeat_interleave(snake_case__    ,						dim=0 )

          if do_classifier_free_guidance:
                 snake_case       :   int							=      torch.zeros_like(snake_case__ )

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

          return image_embeds



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


          '''simple docstring'''


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

          snake_case       :   List[Any]							=      self._execution_device

          snake_case       :   int							=      batch_size * num_images_per_prompt

          snake_case       :   Optional[Any]							=      guidance_scale > 1.0
          snake_case       :   str							=      self._encode_image(snake_case__    ,						snake_case__    ,						snake_case__    ,						snake_case__ )

          # prior

          self.scheduler.set_timesteps(snake_case__    ,						device=snake_case__ )
          snake_case       :   List[str]							=      self.scheduler.timesteps

          snake_case       :   Dict							=      self.prior.config.num_embeddings
          snake_case       :   int							=      self.prior.config.embedding_dim

          snake_case       :   Dict							=      self.prepare_latents(
              (batch_size, num_embeddings * embedding_dim)    ,						image_embeds.dtype    ,						snake_case__    ,						snake_case__    ,						snake_case__    ,						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
          snake_case       :   Optional[Any]							=      latents.reshape(latents.shape[0]    ,						snake_case__    ,						snake_case__ )

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

                 snake_case       :   Dict							=      self.prior(
                     snake_case__    ,						timestep=snake_case__    ,						proj_embedding=snake_case__    ,						).predicted_image_embedding

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

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

                 snake_case       :   Union[str, Any]							=      self.scheduler.step(
                     snake_case__    ,						timestep=snake_case__    ,						sample=snake_case__    ,						).prev_sample

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

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

                 images.append(snake_case__ )

          snake_case       :   Any							=      torch.stack(snake_case__ )

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

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

          if output_type == "pil":
                 snake_case       :   Union[str, Any]							=      [self.numpy_to_pil(snake_case__ ) 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=snake_case__ )







import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
   from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
   from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING


def 			UpperCamelCase					(    __lowerCamelCase     : List[Any]    ):
       return 1.0 / (1.0 + np.exp(-_outputs    ))


def 			UpperCamelCase					(    __lowerCamelCase     : int    ):
       snake_case       :   Tuple							=      np.max(_outputs				,					axis=-1				,					keepdims=__lowerCamelCase    )
       snake_case       :   int							=      np.exp(_outputs - maxes    )
       return shifted_exp / shifted_exp.sum(axis=-1				,					keepdims=__lowerCamelCase    )






class   UpperCAmelCase		(						A_ ):
   A__					:		Any						     =     "sigmoid"
   A__					:		str						     =     "softmax"
   A__					:		int						     =     "none"






@add_end_docstrings(
    A_       ,r"\n        return_all_scores (`bool`, *optional*, defaults to `False`):\n            Whether to return all prediction scores or just the one of the predicted class.\n        function_to_apply (`str`, *optional*, defaults to `\"default\"`):\n            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n              has several labels, will apply the softmax function on the output.\n            - `\"sigmoid\"`: Applies the sigmoid function on the output.\n            - `\"softmax\"`: Applies the softmax function on the output.\n            - `\"none\"`: Does not apply any function on the output.\n    "       ,)
class   UpperCAmelCase		(						A_ ):
   A__					:		int						     =     False
   A__					:		Union[str, Any]						     =     ClassificationFunction.NONE



   def __init__(self		:					List[str]    ,						**snake_case__		:					int )		->	str:


          '''simple docstring'''


          super().__init__(**snake_case__ )

          self.check_model_type(
              TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
              if self.framework == "tf"
              else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING )



   def 				_SCREAMING_SNAKE_CASE   (self		:					List[Any]    ,						snake_case__		:					List[str]=None    ,						snake_case__		:					Optional[Any]=None    ,						snake_case__		:					Union[str, Any]=""    ,						**snake_case__		:					List[str] )		->	Union[str, Any]:


          '''simple docstring'''


          snake_case       :   Dict							=      tokenizer_kwargs

          snake_case       :   List[Any]							=      {}
          if hasattr(self.model.config    ,						"return_all_scores" ) and return_all_scores is None:
                 snake_case       :   Optional[int]							=      self.model.config.return_all_scores

          if isinstance(snake_case__    ,						snake_case__ ) or top_k is None:
                 snake_case       :   List[Any]							=      top_k
                 snake_case       :   str							=      False
          elif return_all_scores is not None:
                 warnings.warn(
                     "`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of"
                     " `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`."    ,						snake_case__    ,						)
                 if return_all_scores:
                        snake_case       :   List[str]							=      None
                 else:
                        snake_case       :   Optional[int]							=      1

          if isinstance(snake_case__    ,						snake_case__ ):
                 snake_case       :   Dict							=      ClassificationFunction[function_to_apply.upper()]

          if function_to_apply is not None:
                 snake_case       :   Optional[int]							=      function_to_apply
          return preprocess_params, {}, postprocess_params



   def __call__(self		:					Dict    ,						*snake_case__		:					List[str]    ,						**snake_case__		:					int )		->	Optional[int]:


          '''simple docstring'''


          snake_case       :   Optional[int]							=      super().__call__(*snake_case__    ,						**snake_case__ )
          # TODO try and retrieve it in a nicer way from _sanitize_parameters.
          snake_case       :   Tuple							=      "top_k" not in kwargs
          if isinstance(args[0]    ,						snake_case__ ) and _legacy:
                 # This pipeline is odd, and return a list when single item is run
                 return [result]
          else:
                 return result



   def 				_SCREAMING_SNAKE_CASE   (self		:					Dict    ,						snake_case__		:					Tuple    ,						**snake_case__		:					Union[str, Any] )		->	Dict[str, GenericTensor]:


          '''simple docstring'''


          snake_case       :   int							=      self.framework
          if isinstance(snake_case__    ,						snake_case__ ):
                 return self.tokenizer(**snake_case__    ,						return_tensors=snake_case__    ,						**snake_case__ )
          elif isinstance(snake_case__    ,						snake_case__ ) and len(snake_case__ ) == 1 and isinstance(inputs[0]    ,						snake_case__ ) and len(inputs[0] ) == 2:
                 # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
                 return self.tokenizer(
                     text=inputs[0][0]    ,						text_pair=inputs[0][1]    ,						return_tensors=snake_case__    ,						**snake_case__ )
          elif isinstance(snake_case__    ,						snake_case__ ):
                 # This is likely an invalid usage of the pipeline attempting to pass text pairs.
                 raise ValueError(
                     "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a"
                     " dictionary `{\"text\": \"My text\", \"text_pair\": \"My pair\"}` in order to send a text pair." )
          return self.tokenizer(snake_case__    ,						return_tensors=snake_case__    ,						**snake_case__ )



   def 				_SCREAMING_SNAKE_CASE   (self		:					int    ,						snake_case__		:					Union[str, Any] )		->	int:


          '''simple docstring'''


          return self.model(**snake_case__ )



   def 				_SCREAMING_SNAKE_CASE   (self		:					List[str]    ,						snake_case__		:					Optional[Any]    ,						snake_case__		:					List[str]=None    ,						snake_case__		:					Dict=1    ,						snake_case__		:					Tuple=True )		->	str:


          '''simple docstring'''


          if function_to_apply is None:
                 if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                        snake_case       :   Tuple							=      ClassificationFunction.SIGMOID
                 elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                        snake_case       :   Tuple							=      ClassificationFunction.SOFTMAX
                 elif hasattr(self.model.config    ,						"function_to_apply" ) and function_to_apply is None:
                        snake_case       :   Tuple							=      self.model.config.function_to_apply
                 else:
                        snake_case       :   int							=      ClassificationFunction.NONE

          snake_case       :   Any							=      model_outputs["logits"][0]
          snake_case       :   List[str]							=      outputs.numpy()

          if function_to_apply == ClassificationFunction.SIGMOID:
                 snake_case       :   Optional[Any]							=      sigmoid(snake_case__ )
          elif function_to_apply == ClassificationFunction.SOFTMAX:
                 snake_case       :   Union[str, Any]							=      softmax(snake_case__ )
          elif function_to_apply == ClassificationFunction.NONE:
                 snake_case       :   Optional[Any]							=      outputs
          else:
                 raise ValueError(f"""Unrecognized `function_to_apply` argument: {function_to_apply}""" )

          if top_k == 1 and _legacy:
                 return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

          snake_case       :   Optional[int]							=      [
              {"label": self.model.config.idalabel[i], "score": score.item()} for i, score in enumerate(snake_case__ )
          ]
          if not _legacy:
                 dict_scores.sort(key=lambda snake_case__ : x["score"]    ,						reverse=snake_case__ )
                 if top_k is not None:
                        snake_case       :   Optional[int]							=      dict_scores[:top_k]
          return dict_scores





