
import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


__magic_name__  :  List[str]     			=   logging.get_logger(__name__)  # pylint: disable=invalid-name

__magic_name__  :  Optional[int]     			=   '\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = "a shark"\n\n        >>> images = pipe(\n        ...     prompt,\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], "shark_3d.gif")\n        ```\n'


@dataclass
class 							lowerCamelCase       (		A__					):



  """simple docstring"""





  lowerCAmelCase_								=		42



class 							lowerCamelCase       (		A__					):



  """simple docstring"""





  def __init__(					self						,    __UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase						,    ):
      super().__init__()

      self.register_modules(
          prior=__UpperCamelCase						,    text_encoder=__UpperCamelCase						,    tokenizer=__UpperCamelCase						,    scheduler=__UpperCamelCase						,    renderer=__UpperCamelCase						,    )

  def 					lowercase_						(					self						,    __UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase					):

      if latents is None:
          A_								=					randn_tensor(__UpperCamelCase						,    generator=__UpperCamelCase						,    device=__UpperCamelCase						,    dtype=__UpperCamelCase					)
      else:
          if latents.shape != shape:
              raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'					)
          A_								=					latents.to(__UpperCamelCase					)

      A_								=					latents * scheduler.init_noise_sigma
      return latents

  def 					lowercase_						(					self						,    __UpperCamelCase=0					):

      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.text_encoder, self.prior]
      for cpu_offloaded_model in models:
          if cpu_offloaded_model is not None:
              cpu_offload(__UpperCamelCase						,    __UpperCamelCase					)

  def 					lowercase_						(					self						,    __UpperCamelCase=0					):

      if is_accelerate_available() and is_accelerate_version(">="						,    "0.17.0.dev0"					):
          from accelerate import cpu_offload_with_hook
      else:
          raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."					)

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

      if self.device.type != "cpu":
          self.to("cpu"						,    silence_dtype_warnings=__UpperCamelCase					)
          torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

      A_								=					None
      for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
          A_								=					cpu_offload_with_hook(__UpperCamelCase						,    __UpperCamelCase						,    prev_module_hook=__UpperCamelCase					)

      if self.safety_checker is not None:
          A_								=					cpu_offload_with_hook(self.safety_checker						,    __UpperCamelCase						,    prev_module_hook=__UpperCamelCase					)

      # We'll offload the last model manually.
      A_								=					hook

  @property
  def 					lowercase_						(					self					):

      if self.device != torch.device("meta"					) or not hasattr(self.text_encoder						,    "_hf_hook"					):
          return self.device
      for module in self.text_encoder.modules():
          if (
              hasattr(__UpperCamelCase						,    "_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						,    __UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase						,    ):
      len(__UpperCamelCase					) if isinstance(__UpperCamelCase						,    __UpperCamelCase					) else 1

      # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
      A_								=					0
      # get prompt text embeddings
      A_								=					self.tokenizer(
          __UpperCamelCase						,    padding="max_length"						,    max_length=self.tokenizer.model_max_length						,    truncation=__UpperCamelCase						,    return_tensors="pt"						,    )
      A_								=					text_inputs.input_ids
      A_								=					self.tokenizer(__UpperCamelCase						,    padding="longest"						,    return_tensors="pt"					).input_ids

      if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__UpperCamelCase						,    __UpperCamelCase					):
          A_								=					self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]					)
          logger.warning(
              "The following part of your input was truncated because CLIP can only handle sequences up to"
              f' {self.tokenizer.model_max_length} tokens: {removed_text}'					)

      A_								=					self.text_encoder(text_input_ids.to(__UpperCamelCase					)					)
      A_								=					text_encoder_output.text_embeds

      A_								=					prompt_embeds.repeat_interleave(__UpperCamelCase						,    dim=0					)
      # in Shap-E it normalize the prompt_embeds and then later rescale it
      A_								=					prompt_embeds / torch.linalg.norm(__UpperCamelCase						,    dim=-1						,    keepdim=__UpperCamelCase					)

      if do_classifier_free_guidance:
          A_								=					torch.zeros_like(__UpperCamelCase					)

          # 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_prompt_embeds, prompt_embeds]					)

      # Rescale the features to have unit variance
      A_								=					math.sqrt(prompt_embeds.shape[1]					) * prompt_embeds

      return prompt_embeds

  @torch.no_grad()
  @replace_example_docstring(__UpperCamelCase					)
  def __call__(					self						,    __UpperCamelCase						,    __UpperCamelCase = 1						,    __UpperCamelCase = 25						,    __UpperCamelCase = None						,    __UpperCamelCase = None						,    __UpperCamelCase = 4.0						,    __UpperCamelCase = 64						,    __UpperCamelCase = "pil"						,    __UpperCamelCase = True						,    ):

      if isinstance(__UpperCamelCase						,    __UpperCamelCase					):
          A_								=					1
      elif isinstance(__UpperCamelCase						,    __UpperCamelCase					):
          A_								=					len(__UpperCamelCase					)
      else:
          raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(__UpperCamelCase					)}'					)

      A_								=					self._execution_device

      A_								=					batch_size * num_images_per_prompt

      A_								=					guidance_scale > 1.0
      A_								=					self._encode_prompt(__UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase					)

      # prior

      self.scheduler.set_timesteps(__UpperCamelCase						,    device=__UpperCamelCase					)
      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)						,    prompt_embeds.dtype						,    __UpperCamelCase						,    __UpperCamelCase						,    __UpperCamelCase						,    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]						,    __UpperCamelCase						,    __UpperCamelCase					)

      for i, t in enumerate(self.progress_bar(__UpperCamelCase					)					):
          # 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(__UpperCamelCase						,    __UpperCamelCase					)

          A_								=					self.prior(
              __UpperCamelCase						,    timestep=__UpperCamelCase						,    proj_embedding=__UpperCamelCase						,    ).predicted_image_embedding

          # remove the variance
          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_								=					noise_pred.chunk(2					)
              A_								=					noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

          A_								=					self.scheduler.step(
              __UpperCamelCase						,    timestep=__UpperCamelCase						,    sample=__UpperCamelCase						,    ).prev_sample

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

      A_								=					[]
      for i, latent in enumerate(__UpperCamelCase					):
          A_								=					self.renderer.decode(
              latent[None, :]						,    __UpperCamelCase						,    size=__UpperCamelCase						,    ray_batch_size=4096						,    n_coarse_samples=64						,    n_fine_samples=128						,    )
          images.append(__UpperCamelCase					)

      A_								=					torch.stack(__UpperCamelCase					)

      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(__UpperCamelCase					) 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=__UpperCamelCase					)







from typing import Any, Dict, List, Union

import numpy as np

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
    from PIL import Image

    from ..image_utils import load_image

if is_torch_available():
    from ..models.auto.modeling_auto import (
        MODEL_FOR_IMAGE_SEGMENTATION_MAPPING,
        MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING,
        MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING,
        MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING,
    )


_lowerCAmelCase        =       logging.get_logger(__name__)


_lowerCAmelCase        =       Dict[str, Any]
_lowerCAmelCase        =       List[Prediction]






@add_end_docstrings(A__				)
class     __UpperCAmelCase(    A__				):






 """simple docstring"""




 def __init__(    self ,       *__magic_name__ ,       **__magic_name__      ):

        """simple docstring"""

        super().__init__(*__magic_name__ ,       **__magic_name__      )

        if self.framework == "tf":
               raise ValueError(f"""The {self.__class__} is only available in PyTorch."""      )

        requires_backends(self ,       '''vision'''      )
        self.check_model_type(
            dict(
                MODEL_FOR_IMAGE_SEGMENTATION_MAPPING.items()
                + MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING.items()
                + MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING.items()
                + MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING.items()      )      )
 def  UpperCAmelCase   (    self ,       **__magic_name__      ):

        """simple docstring"""

        A_							:       str	      =				{}
        A_							:       List[Any]	      =				{}
        if "subtask" in kwargs:
               A_							:       Optional[int]	      =				kwargs['''subtask''']
               A_							:       Dict	      =				kwargs['''subtask''']
        if "threshold" in kwargs:
               A_							:       Tuple	      =				kwargs['''threshold''']
        if "mask_threshold" in kwargs:
               A_							:       int	      =				kwargs['''mask_threshold''']
        if "overlap_mask_area_threshold" in kwargs:
               A_							:       Optional[Any]	      =				kwargs['''overlap_mask_area_threshold''']

        return preprocess_kwargs, {}, postprocess_kwargs
 def __call__(    self ,       __magic_name__ ,       **__magic_name__      ):

        """simple docstring"""

        return super().__call__(__magic_name__ ,       **__magic_name__      )
 def  UpperCAmelCase   (    self ,       __magic_name__ ,       __magic_name__=None      ):

        """simple docstring"""

        A_							:       Optional[int]	      =				load_image(__magic_name__      )
        A_							:       int	      =				[(image.height, image.width)]
        if self.model.config.__class__.__name__ == "OneFormerConfig":
               if subtask is None:
                      A_							:       int	      =				{}
               else:
                      A_							:       str	      =				{'''task_inputs''': [subtask]}
               A_							:       List[Any]	      =				self.image_processor(images=[image] ,       return_tensors='''pt''' ,       **__magic_name__      )
               A_							:       int	      =				self.tokenizer(
                   inputs['''task_inputs'''] ,       padding='''max_length''' ,       max_length=self.model.config.task_seq_len ,       return_tensors=self.framework ,       )['''input_ids''']
        else:
               A_							:       Any	      =				self.image_processor(images=[image] ,       return_tensors='''pt'''      )
        A_							:       Optional[int]	      =				target_size
        return inputs
 def  UpperCAmelCase   (    self ,       __magic_name__      ):

        """simple docstring"""

        A_							:       Dict	      =				model_inputs.pop('''target_size'''      )
        A_							:       Union[str, Any]	      =				self.model(**__magic_name__      )
        A_							:       Any	      =				target_size
        return model_outputs
 def  UpperCAmelCase   (    self ,       __magic_name__ ,       __magic_name__=None ,       __magic_name__=0.9 ,       __magic_name__=0.5 ,       __magic_name__=0.5      ):

        """simple docstring"""

        A_							:       Tuple	      =				None
        if subtask in {"panoptic", None} and hasattr(self.image_processor ,       '''post_process_panoptic_segmentation'''      ):
               A_							:       Dict	      =				self.image_processor.post_process_panoptic_segmentation
        elif subtask in {"instance", None} and hasattr(self.image_processor ,       '''post_process_instance_segmentation'''      ):
               A_							:       Tuple	      =				self.image_processor.post_process_instance_segmentation

        if fn is not None:
               A_							:       Dict	      =				fn(
                   __magic_name__ ,       threshold=__magic_name__ ,       mask_threshold=__magic_name__ ,       overlap_mask_area_threshold=__magic_name__ ,       target_sizes=model_outputs['''target_size'''] ,       )[0]

               A_							:       Optional[Any]	      =				[]
               A_							:       Optional[int]	      =				outputs['''segmentation''']

               for segment in outputs["segments_info"]:
                      A_							:       Optional[int]	      =				(segmentation == segment['''id''']) * 255
                      A_							:       int	      =				Image.fromarray(mask.numpy().astype(np.uinta      ) ,       mode='''L'''      )
                      A_							:       Union[str, Any]	      =				self.model.config.idalabel[segment['''label_id''']]
                      A_							:       Optional[int]	      =				segment['''score''']
                      annotation.append({'''score''': score, '''label''': label, '''mask''': mask}      )

        elif subtask in {"semantic", None} and hasattr(self.image_processor ,       '''post_process_semantic_segmentation'''      ):
               A_							:       int	      =				self.image_processor.post_process_semantic_segmentation(
                   __magic_name__ ,       target_sizes=model_outputs['''target_size''']      )[0]

               A_							:       Tuple	      =				[]
               A_							:       Any	      =				outputs.numpy()
               A_							:       Optional[Any]	      =				np.unique(__magic_name__      )

               for label in labels:
                      A_							:       Any	      =				(segmentation == label) * 255
                      A_							:       str	      =				Image.fromarray(mask.astype(np.uinta      ) ,       mode='''L'''      )
                      A_							:       List[str]	      =				self.model.config.idalabel[label]
                      annotation.append({'''score''': None, '''label''': label, '''mask''': mask}      )
        else:
               raise ValueError(f"""Subtask {subtask} is not supported for model {type(self.model      )}"""      )
        return annotation


