





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


__lowercase  :   str						      =logging.get_logger(__name__)  # pylint: disable=invalid-name

__lowercase  :   Tuple						      ="""
    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      A       (	__lowercase						):
      _snake_case							     =42

class      A       (	__lowercase						):



      def __init__(	self:						Optional[int]		,  _lowerCAmelCase:						PriorTransformer		,  _lowerCAmelCase:						CLIPVisionModel		,  _lowerCAmelCase:						CLIPImageProcessor		,  _lowerCAmelCase:						HeunDiscreteScheduler		,  _lowerCAmelCase:						ShapERenderer		,  )						->    Any:
         '''simple docstring'''

         super().__init__()

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



      def 	lowerCAmelCase__    (	self:						Union[str, Any]		,  _lowerCAmelCase:						Any		,  _lowerCAmelCase:						Any		,  _lowerCAmelCase:						Any		,  _lowerCAmelCase:						int		,  _lowerCAmelCase:						int		,  _lowerCAmelCase:						Optional[Any]       )						->    List[Any]:
         '''simple docstring'''

         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 	lowerCAmelCase__    (	self:						List[Any]		,  _lowerCAmelCase:						Optional[Any]=0       )						->    Optional[int]:
         '''simple docstring'''

         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 	lowerCAmelCase__    (	self:						Optional[Any]       )						->    Tuple:
         '''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(_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 	lowerCAmelCase__    (	self:						int		,  _lowerCAmelCase:						str		,  _lowerCAmelCase:						Optional[int]		,  _lowerCAmelCase:						str		,  _lowerCAmelCase:						str		,  )						->    Any:
         '''simple docstring'''

         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		,  )						->    List[str]:
         '''simple docstring'''

         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       )











import json
import os
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from requests.exceptions import HTTPError

from transformers.utils import (
    CONFIG_NAME,
    FLAX_WEIGHTS_NAME,
    TF2_WEIGHTS_NAME,
    TRANSFORMERS_CACHE,
    WEIGHTS_NAME,
    cached_file,
    get_file_from_repo,
    has_file,
)


__lowercase  :   Any						      ="""hf-internal-testing/tiny-random-bert"""
__lowercase  :   List[str]						      =os.path.join(TRANSFORMERS_CACHE, """models--hf-internal-testing--tiny-random-bert""")
__lowercase  :   Dict						      ="""9b8c223d42b2188cb49d29af482996f9d0f3e5a6"""

class      A       (	unittest.TestCase						):



      def 	lowerCAmelCase__    (	self:						List[str]       )						->    str:
         '''simple docstring'''

         UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  _lowerCAmelCase       )
         # Should have downloaded the file in here
         self.assertTrue(os.path.isdir(_lowerCAmelCase       )       )
         # Cache should contain at least those three subfolders:
         for subfolder in ["blobs", "refs", "snapshots"]:
            self.assertTrue(os.path.isdir(os.path.join(_lowerCAmelCase		,  _lowerCAmelCase       )       )       )
         with open(os.path.join(_lowerCAmelCase		,  "refs"		,  "main"       )       ) as f:
            UpperCAmelCase_											=f.read()
         self.assertEqual(_lowerCAmelCase		,  os.path.join(_lowerCAmelCase		,  "snapshots"		,  _lowerCAmelCase		,  _lowerCAmelCase       )       )
         self.assertTrue(os.path.isfile(_lowerCAmelCase       )       )

         # File is cached at the same place the second time.
         UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  _lowerCAmelCase       )
         self.assertEqual(_lowerCAmelCase		,  _lowerCAmelCase       )

         # Using a specific revision to test the full commit hash.
         UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  _lowerCAmelCase		,  revision="9b8c223"       )
         self.assertEqual(_lowerCAmelCase		,  os.path.join(_lowerCAmelCase		,  "snapshots"		,  _lowerCAmelCase		,  _lowerCAmelCase       )       )



      def 	lowerCAmelCase__    (	self:						Any       )						->    Optional[Any]:
         '''simple docstring'''

         with self.assertRaisesRegex(_lowerCAmelCase		,  "is not a valid model identifier"       ):
            UpperCAmelCase_											=cached_file("tiny-random-bert"		,  _lowerCAmelCase       )

         with self.assertRaisesRegex(_lowerCAmelCase		,  "is not a valid git identifier"       ):
            UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  _lowerCAmelCase		,  revision="aaaa"       )

         with self.assertRaisesRegex(_lowerCAmelCase		,  "does not appear to have a file named"       ):
            UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  "conf"       )



      def 	lowerCAmelCase__    (	self:						Tuple       )						->    Optional[Any]:
         '''simple docstring'''

         with self.assertRaisesRegex(_lowerCAmelCase		,  "does not appear to have a file named"       ):
            UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  "conf"       )

         with open(os.path.join(_lowerCAmelCase		,  "refs"		,  "main"       )       ) as f:
            UpperCAmelCase_											=f.read()
         self.assertTrue(os.path.isfile(os.path.join(_lowerCAmelCase		,  ".no_exist"		,  _lowerCAmelCase		,  "conf"       )       )       )

         UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  "conf"		,  _raise_exceptions_for_missing_entries=_lowerCAmelCase       )
         self.assertIsNone(_lowerCAmelCase       )

         UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  "conf"		,  local_files_only=_lowerCAmelCase		,  _raise_exceptions_for_missing_entries=_lowerCAmelCase       )
         self.assertIsNone(_lowerCAmelCase       )

         UpperCAmelCase_											=mock.Mock()
         UpperCAmelCase_											=500
         UpperCAmelCase_											={}
         UpperCAmelCase_											=HTTPError
         UpperCAmelCase_											={}

         # Under the mock environment we get a 500 error when trying to reach the tokenizer.
         with mock.patch("requests.Session.request"		,  return_value=_lowerCAmelCase       ) as mock_head:
            UpperCAmelCase_											=cached_file(_lowerCAmelCase		,  "conf"		,  _raise_exceptions_for_connection_errors=_lowerCAmelCase       )
            self.assertIsNone(_lowerCAmelCase       )
            # This check we did call the fake head request
            mock_head.assert_called()



      def 	lowerCAmelCase__    (	self:						Any       )						->    Tuple:
         '''simple docstring'''

         self.assertTrue(has_file("hf-internal-testing/tiny-bert-pt-only"		,  _lowerCAmelCase       )       )
         self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"		,  _lowerCAmelCase       )       )
         self.assertFalse(has_file("hf-internal-testing/tiny-bert-pt-only"		,  _lowerCAmelCase       )       )



      def 	lowerCAmelCase__    (	self:						Any       )						->    Dict:
         '''simple docstring'''

         self.assertIsNone(get_file_from_repo("bert-base-cased"		,  "ahah.txt"       )       )

         # The function raises if the repository does not exist.
         with self.assertRaisesRegex(_lowerCAmelCase		,  "is not a valid model identifier"       ):
            get_file_from_repo("bert-base-case"		,  _lowerCAmelCase       )

         # The function raises if the revision does not exist.
         with self.assertRaisesRegex(_lowerCAmelCase		,  "is not a valid git identifier"       ):
            get_file_from_repo("bert-base-cased"		,  _lowerCAmelCase		,  revision="ahaha"       )

         UpperCAmelCase_											=get_file_from_repo("bert-base-cased"		,  _lowerCAmelCase       )
         # The name is the cached name which is not very easy to test, so instead we load the content.
         UpperCAmelCase_											=json.loads(open(_lowerCAmelCase		,  "r"       ).read()       )
         self.assertEqual(config["hidden_size"]		,  768       )






      def 	lowerCAmelCase__    (	self:						Optional[int]       )						->    Dict:
         '''simple docstring'''

         with tempfile.TemporaryDirectory() as tmp_dir:
            UpperCAmelCase_											=Path(_lowerCAmelCase       ) / "a.txt"
            filename.touch()
            self.assertEqual(get_file_from_repo(_lowerCAmelCase		,  "a.txt"       )		,  str(_lowerCAmelCase       )       )

            self.assertIsNone(get_file_from_repo(_lowerCAmelCase		,  "b.txt"       )       )




