




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

_lowerCAmelCase						:   int		=   "\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      (				lowerCAmelCase		):
      UpperCAmelCase_        =		42



class 			_UpperCamelCase      (				lowerCAmelCase		):
      def __init__(			self   :List[str] ,      lowerCamelCase   :PriorTransformer ,      lowerCamelCase   :CLIPVisionModel ,      lowerCamelCase   :CLIPImageProcessor ,      lowerCamelCase   :HeunDiscreteScheduler ,      lowerCamelCase   :ShapERenderer ,      )     ->			str:
       super().__init__()

       self.register_modules(
           prior=lowerCamelCase ,      image_encoder=lowerCamelCase ,      image_processor=lowerCamelCase ,      scheduler=lowerCamelCase ,      renderer=lowerCamelCase ,      )
      def 	UpperCAmelCase_						(			self   :Dict ,      lowerCamelCase   :int ,      lowerCamelCase   :Any ,      lowerCamelCase   :int ,      lowerCamelCase   :Union[str, Any] ,      lowerCamelCase   :Optional[int] ,      lowerCamelCase   :int      )     ->			int:
       if latents is None:
        UpperCAmelCase__							 =						randn_tensor(lowerCamelCase ,      generator=lowerCamelCase ,      device=lowerCamelCase ,      dtype=lowerCamelCase      )
       else:
        if latents.shape != shape:
         raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''      )
        UpperCAmelCase__							 =						latents.to(lowerCamelCase      )

       UpperCAmelCase__							 =						latents * scheduler.init_noise_sigma
       return latents
      def 	UpperCAmelCase_						(			self   :Tuple ,      lowerCamelCase   :Any=0      )     ->			int:
       if is_accelerate_available():
        from accelerate import cpu_offload
       else:
        raise ImportError("Please install accelerate via `pip install accelerate`"      )

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

       UpperCAmelCase__							 =						[self.image_encoder, self.prior]
       for cpu_offloaded_model in models:
        if cpu_offloaded_model is not None:
         cpu_offload(lowerCamelCase ,      lowerCamelCase      )
      @property
      def 	UpperCAmelCase_						(			self   :Optional[Any]      )     ->			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(lowerCamelCase ,      "_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   :List[str] ,      lowerCamelCase   :int ,      lowerCamelCase   :Dict ,      lowerCamelCase   :Tuple ,      lowerCamelCase   :str ,      )     ->			Dict:
       if isinstance(lowerCamelCase ,      lowerCamelCase      ) and isinstance(image[0] ,      torch.Tensor      ):
        UpperCAmelCase__							 =						torch.cat(lowerCamelCase ,      axis=0      ) if image[0].ndim == 4 else torch.stack(lowerCamelCase ,      axis=0      )

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

       UpperCAmelCase__							 =						image.to(dtype=self.image_encoder.dtype ,      device=lowerCamelCase      )

       UpperCAmelCase__							 =						self.image_encoder(lowerCamelCase      )["last_hidden_state"]
       UpperCAmelCase__							 =						image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

       UpperCAmelCase__							 =						image_embeds.repeat_interleave(lowerCamelCase ,      dim=0      )

       if do_classifier_free_guidance:
        UpperCAmelCase__							 =						torch.zeros_like(lowerCamelCase      )

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

       return image_embeds







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

       if isinstance(lowerCamelCase ,      PIL.Image.Image      ):
        UpperCAmelCase__							 =						1
       elif isinstance(lowerCamelCase ,      torch.Tensor      ):
        UpperCAmelCase__							 =						image.shape[0]
       elif isinstance(lowerCamelCase ,      lowerCamelCase      ) and isinstance(image[0] ,      (torch.Tensor, PIL.Image.Image)      ):
        UpperCAmelCase__							 =						len(lowerCamelCase      )
       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(lowerCamelCase      )}'''      )

       UpperCAmelCase__							 =						self._execution_device

       UpperCAmelCase__							 =						batch_size * num_images_per_prompt

       UpperCAmelCase__							 =						guidance_scale > 1.0
       UpperCAmelCase__							 =						self._encode_image(lowerCamelCase ,      lowerCamelCase ,      lowerCamelCase ,      lowerCamelCase      )

       # prior

       self.scheduler.set_timesteps(lowerCamelCase ,      device=lowerCamelCase      )
       UpperCAmelCase__							 =						self.scheduler.timesteps

       UpperCAmelCase__							 =						self.prior.config.num_embeddings
       UpperCAmelCase__							 =						self.prior.config.embedding_dim

       UpperCAmelCase__							 =						self.prepare_latents(
           (batch_size, num_embeddings * embedding_dim) ,      image_embeds.dtype ,      lowerCamelCase ,      lowerCamelCase ,      lowerCamelCase ,      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
       UpperCAmelCase__							 =						latents.reshape(latents.shape[0] ,      lowerCamelCase ,      lowerCamelCase      )

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

        UpperCAmelCase__							 =						self.prior(
            lowerCamelCase ,      timestep=lowerCamelCase ,      proj_embedding=lowerCamelCase ,      ).predicted_image_embedding

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

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

        UpperCAmelCase__							 =						self.scheduler.step(
            lowerCamelCase ,      timestep=lowerCamelCase ,      sample=lowerCamelCase ,      ).prev_sample

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

       UpperCAmelCase__							 =						[]
       for i, latent in enumerate(lowerCamelCase      ):
        print()
        UpperCAmelCase__							 =						self.renderer.decode(
            latent[None, :] ,      lowerCamelCase ,      size=lowerCamelCase ,      ray_batch_size=4096 ,      n_coarse_samples=64 ,      n_fine_samples=128 ,      )

        images.append(lowerCamelCase      )

       UpperCAmelCase__							 =						torch.stack(lowerCamelCase      )

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

       UpperCAmelCase__							 =						images.cpu().numpy()

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











from ....configuration_utils import PretrainedConfig
from ....utils import logging


_lowerCAmelCase						:   Union[str, Any]		=   logging.get_logger(__name__)

_lowerCAmelCase						:   Tuple		=   {
    "CarlCochet/trajectory-transformer-halfcheetah-medium-v2": (
        "https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json"
    ),
    # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer
}
class 			_UpperCamelCase      (				lowerCAmelCase		):
      UpperCAmelCase_        =		"""trajectory_transformer"""
      UpperCAmelCase_        =		["""past_key_values"""]
      UpperCAmelCase_        =		{
          """hidden_size""": """n_embd""",
          """num_attention_heads""": """n_head""",
          """num_hidden_layers""": """n_layer""",
      }
      def __init__(			self   :Union[str, Any] ,      lowerCamelCase   :Optional[int]=100 ,      lowerCamelCase   :Optional[int]=5 ,      lowerCamelCase   :Optional[Any]=1 ,      lowerCamelCase   :Any=1 ,      lowerCamelCase   :int=249 ,      lowerCamelCase   :Optional[Any]=6 ,      lowerCamelCase   :Optional[Any]=17 ,      lowerCamelCase   :Optional[int]=25 ,      lowerCamelCase   :Union[str, Any]=4 ,      lowerCamelCase   :Union[str, Any]=4 ,      lowerCamelCase   :Optional[int]=128 ,      lowerCamelCase   :List[Any]=0.1 ,      lowerCamelCase   :List[str]=0.1 ,      lowerCamelCase   :Tuple=0.1 ,      lowerCamelCase   :Dict=0.00_06 ,      lowerCamelCase   :Dict=512 ,      lowerCamelCase   :Optional[Any]=0.02 ,      lowerCamelCase   :Any=1e-12 ,      lowerCamelCase   :Optional[Any]=1 ,      lowerCamelCase   :List[Any]=True ,      lowerCamelCase   :int=1 ,      lowerCamelCase   :Dict=5_0256 ,      lowerCamelCase   :Union[str, Any]=5_0256 ,      **lowerCamelCase   :int ,      )     ->			Optional[Any]:
       UpperCAmelCase__							 =						vocab_size
       UpperCAmelCase__							 =						action_weight
       UpperCAmelCase__							 =						reward_weight
       UpperCAmelCase__							 =						value_weight
       UpperCAmelCase__							 =						max_position_embeddings
       UpperCAmelCase__							 =						block_size
       UpperCAmelCase__							 =						action_dim
       UpperCAmelCase__							 =						observation_dim
       UpperCAmelCase__							 =						transition_dim
       UpperCAmelCase__							 =						learning_rate
       UpperCAmelCase__							 =						n_layer
       UpperCAmelCase__							 =						n_head
       UpperCAmelCase__							 =						n_embd
       UpperCAmelCase__							 =						embd_pdrop
       UpperCAmelCase__							 =						attn_pdrop
       UpperCAmelCase__							 =						resid_pdrop
       UpperCAmelCase__							 =						initializer_range
       UpperCAmelCase__							 =						layer_norm_eps
       UpperCAmelCase__							 =						kaiming_initializer_range
       UpperCAmelCase__							 =						use_cache
       super().__init__(pad_token_id=lowerCamelCase ,      bos_token_id=lowerCamelCase ,      eos_token_id=lowerCamelCase ,      **lowerCamelCase      )





