

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


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

SCREAMING_SNAKE_CASE_    :		Tuple							     =  '\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     a  (				UpperCAmelCase__ ):



    """simple docstring"""



    UpperCAmelCase         =    42



class     a  (				UpperCAmelCase__ ):



    """simple docstring"""



    def __init__(   self:       Dict			,  UpperCamelCase:       Union[str, Any]			,  UpperCamelCase:       Optional[Any]			,  UpperCamelCase:       Any			,  UpperCamelCase:       Optional[int]			,  UpperCamelCase:       Any			,  ):






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






         """simple docstring"""


         if latents is None:
              A__								=     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}"""				)
              A__								=     latents.to(snake_case_				)

         A__								=     latents * scheduler.init_noise_sigma
         return latents

    def  UpperCamelCase		(   self:       Optional[Any]			,  UpperCamelCase:       List[str]=0				):






         """simple docstring"""


         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(snake_case_			,  snake_case_				)

    @property
    def  UpperCamelCase		(   self:       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(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  UpperCamelCase		(   self:       Dict			,  UpperCamelCase:       List[Any]			,  UpperCamelCase:       int			,  UpperCamelCase:       Union[str, Any]			,  UpperCamelCase:       Union[str, Any]			,  ):






         """simple docstring"""


         if isinstance(snake_case_			,  snake_case_				) and isinstance(image[0]			,  torch.Tensor				):
              A__								=     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				):
              A__								=     self.image_processor(snake_case_			,  return_tensors="""pt"""				).pixel_values[0].unsqueeze(0				)

         A__								=     image.to(dtype=self.image_encoder.dtype			,  device=snake_case_				)

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

         A__								=     image_embeds.repeat_interleave(snake_case_			,  dim=0				)

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

         return image_embeds





    @torch.no_grad()
    @replace_example_docstring(snake_case_				)
    def __call__(   self:       Optional[int]			,  UpperCamelCase:       Union[str, Any]			,  UpperCamelCase:       Dict = 1			,  UpperCamelCase:       List[str] = 25			,  UpperCamelCase:       Tuple = None			,  UpperCamelCase:       int = None			,  UpperCamelCase:       Optional[Any] = 4.0			,  UpperCamelCase:       Union[str, Any] = 64			,  UpperCamelCase:       Dict = "pil"			,  UpperCamelCase:       List[str] = True			,  ):






         """simple docstring"""


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

         A__								=     self._execution_device

         A__								=     batch_size * num_images_per_prompt

         A__								=     guidance_scale > 1.0
         A__								=     self._encode_image(snake_case_			,  snake_case_			,  snake_case_			,  snake_case_				)

         # prior

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

              A__								=     self.prior(
                  snake_case_			,  timestep=snake_case_			,  proj_embedding=snake_case_			,  ).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(
                  snake_case_			,  timestep=snake_case_			,  sample=snake_case_			,  ).prev_sample

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

         A__								=     []
         for i, latent in enumerate(snake_case_				):
              print()
              A__								=     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_				)

         A__								=     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}"""				)

         A__								=     images.cpu().numpy()

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













"""simple docstring"""




from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase_     :						str						=					logging.get_logger(__name__)

lowerCamelCase_     :						Any						=					{
    'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json',
    'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json',
    'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json',
    'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json',
    'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json',
    'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json',
    'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json',
    'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json',
    'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json',
}

class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_      : Tuple	    =   """xmod"""

      def __init__(     self					,      snake_case_=3_0_5_2_2					,      snake_case_=7_6_8					,      snake_case_=1_2					,      snake_case_=1_2					,      snake_case_=3_0_7_2					,      snake_case_="gelu"					,      snake_case_=0.1					,      snake_case_=0.1					,      snake_case_=5_1_2					,      snake_case_=2					,      snake_case_=0.02					,      snake_case_=1E-12					,      snake_case_=1					,      snake_case_=0					,      snake_case_=2					,      snake_case_="absolute"					,      snake_case_=True					,      snake_case_=None					,      snake_case_=False					,      snake_case_=2					,      snake_case_=False					,      snake_case_=True					,      snake_case_=True					,      snake_case_=("en_XX",)					,      snake_case_=None					,      **snake_case_					,      ):

        """simple docstring"""

        super().__init__(pad_token_id=snake_case_					,      bos_token_id=snake_case_					,      eos_token_id=snake_case_					,      **snake_case_  )

        A_  :       Union[str, Any]										=  vocab_size
        A_  :       Any										=  hidden_size
        A_  :       List[str]										=  num_hidden_layers
        A_  :       Tuple										=  num_attention_heads
        A_  :       int										=  hidden_act
        A_  :       Any										=  intermediate_size
        A_  :       Any										=  hidden_dropout_prob
        A_  :       Dict										=  attention_probs_dropout_prob
        A_  :       Union[str, Any]										=  max_position_embeddings
        A_  :       List[Any]										=  type_vocab_size
        A_  :       List[str]										=  initializer_range
        A_  :       Any										=  layer_norm_eps
        A_  :       Optional[Any]										=  position_embedding_type
        A_  :       int										=  use_cache
        A_  :       Dict										=  classifier_dropout
        A_  :       int										=  pre_norm
        A_  :       Optional[Any]										=  adapter_reduction_factor
        A_  :       List[Any]										=  adapter_layer_norm
        A_  :       int										=  adapter_reuse_layer_norm
        A_  :       Dict										=  ln_before_adapter
        A_  :       List[str]										=  list(snake_case_  )
        A_  :       Union[str, Any]										=  default_language


class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''

      @property
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        if self.task == "multiple-choice":
          A_  :       Dict										=  {0: 'batch', 1: 'choice', 2: 'sequence'}
        else:
          A_  :       int										=  {0: 'batch', 1: 'sequence'}
        return OrderedDict(
            [
                ('input_ids', dynamic_axis),
                ('attention_mask', dynamic_axis),
            ]  )