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


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

UpperCAmelCase__     						=  """
    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 (						__snake_case      ):
    _snake_case   :     Union[PIL.Image.Image, np.ndarray]



class 				a (						__snake_case      ):


    def __init__(    self		:     Tuple      , __lowerCAmelCase		:     Union[str, Any]      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     Optional[Any]      , ):
      super().__init__()

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


    def    lowerCAmelCase_     (    self		:     Optional[Any]      , __lowerCAmelCase		:     Dict      , __lowerCAmelCase		:     Dict      , __lowerCAmelCase		:     int      , __lowerCAmelCase		:     Union[str, Any]      , __lowerCAmelCase		:     Optional[Any]      , __lowerCAmelCase		:     Optional[Any]    ):




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

      _UpperCAmelCase         =					latents * scheduler.init_noise_sigma
      return latents


    def    lowerCAmelCase_     (    self		:     Optional[Any]      , __lowerCAmelCase		:     str=0    ):




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


    @property
    def    lowerCAmelCase_     (    self		:     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(A_      , """_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		:     int      , __lowerCAmelCase		:     List[str]      , __lowerCAmelCase		:     str      , __lowerCAmelCase		:     Union[str, Any]      , ):




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

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

      _UpperCAmelCase         =					image.to(dtype=self.image_encoder.dtype      , device=A_    )

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

      _UpperCAmelCase         =					image_embeds.repeat_interleave(A_      , dim=0    )

      if do_classifier_free_guidance:
        _UpperCAmelCase         =					torch.zeros_like(A_    )

        # 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(A_    )
    def __call__(    self		:     Optional[Any]      , __lowerCAmelCase		:     Optional[int]      , __lowerCAmelCase		:     str = 1      , __lowerCAmelCase		:     str = 25      , __lowerCAmelCase		:     Dict = None      , __lowerCAmelCase		:     List[str] = None      , __lowerCAmelCase		:     Tuple = 4.0      , __lowerCAmelCase		:     Any = 64      , __lowerCAmelCase		:     Optional[Any] = "pil"      , __lowerCAmelCase		:     Union[str, Any] = True      , ):




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

      _UpperCAmelCase         =					self._execution_device

      _UpperCAmelCase         =					batch_size * num_images_per_prompt

      _UpperCAmelCase         =					guidance_scale > 1.0
      _UpperCAmelCase         =					self._encode_image(A_      , A_      , A_      , A_    )

      # prior

      self.scheduler.set_timesteps(A_      , device=A_    )
      _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      , A_      , A_      , A_      , 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]      , A_      , A_    )

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

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

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

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

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

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

        images.append(A_    )

      _UpperCAmelCase         =					torch.stack(A_    )

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







import os
import tempfile
from functools import partial
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pytest

from datasets.arrow_dataset import Dataset
from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex

from .utils import require_elasticsearch, require_faiss


__lowerCamelCase       :     Union[str, Any]   =     pytest.mark.integration



@require_faiss
class 					A__   (       __snake_case			):





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Union[str, Any]       	=   Dataset.from_dict({"filename": ["my_name-train" + "_" + str(A_   ) for x in np.arange(30   ).tolist()]}   )
       return dset





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       import faiss

       UpperCamelCase	:					Dataset       	=   self._create_dummy_dataset()
       UpperCamelCase	:					List[Any]       	=   dset.map(
           lambda A_       ,							A_   : {"vecs": i * np.ones(5       ,							dtype=np.floataa   )}       ,							with_indices=A_       ,							keep_in_memory=A_   )
       UpperCamelCase	:					List[str]       	=   dset.add_faiss_index("vecs"       ,							batch_size=100       ,							metric_type=faiss.METRIC_INNER_PRODUCT   )
       UpperCamelCase	,    UpperCamelCase	:					Tuple       	=   dset.get_nearest_examples("vecs"       ,							np.ones(5       ,							dtype=np.floataa   )   )
       self.assertEqual(examples["filename"][0]       ,							"my_name-train_29"   )
       dset.drop_index("vecs"   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       import faiss

       UpperCamelCase	:					Dataset       	=   self._create_dummy_dataset()
       dset.add_faiss_index_from_external_arrays(
           external_arrays=np.ones((30, 5)   ) * np.arange(30   ).reshape(-1       ,							1   )       ,							index_name="vecs"       ,							batch_size=100       ,							metric_type=faiss.METRIC_INNER_PRODUCT       ,							)
       UpperCamelCase	,    UpperCamelCase	:					int       	=   dset.get_nearest_examples("vecs"       ,							np.ones(5       ,							dtype=np.floataa   )   )
       self.assertEqual(examples["filename"][0]       ,							"my_name-train_29"   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       import faiss

       UpperCamelCase	:					Dataset       	=   self._create_dummy_dataset()
       dset.add_faiss_index_from_external_arrays(
           external_arrays=np.ones((30, 5)   ) * np.arange(30   ).reshape(-1       ,							1   )       ,							index_name="vecs"       ,							metric_type=faiss.METRIC_INNER_PRODUCT       ,							)

       # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
       # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
       # see https://bugs.python.org/issue14243 and
       # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
       with tempfile.NamedTemporaryFile(delete=A_   ) as tmp_file:
        dset.save_faiss_index("vecs"       ,							tmp_file.name   )
        dset.load_faiss_index("vecs2"       ,							tmp_file.name   )
       os.unlink(tmp_file.name   )

       UpperCamelCase	,    UpperCamelCase	:					List[str]       	=   dset.get_nearest_examples("vecs2"       ,							np.ones(5       ,							dtype=np.floataa   )   )
       self.assertEqual(examples["filename"][0]       ,							"my_name-train_29"   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       UpperCamelCase	:					Dataset       	=   self._create_dummy_dataset()
       dset.add_faiss_index_from_external_arrays(
           external_arrays=np.ones((30, 5)   ) * np.arange(30   ).reshape(-1       ,							1   )       ,							index_name="vecs"   )
       dset.drop_index("vecs"   )
       self.assertRaises(A_       ,							partial(dset.get_nearest_examples       ,							"vecs2"       ,							np.ones(5       ,							dtype=np.floataa   )   )   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       from elasticsearch import Elasticsearch

       UpperCamelCase	:					Dataset       	=   self._create_dummy_dataset()
       with patch("elasticsearch.Elasticsearch.search"   ) as mocked_search, patch(
           "elasticsearch.client.IndicesClient.create"   ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk"   ) as mocked_bulk:
        UpperCamelCase	:					List[str]       	=   {"acknowledged": True}
        mocked_bulk.return_value([(True, None)] * 30   )
        UpperCamelCase	:					List[Any]       	=   {"hits": {"hits": [{"_score": 1, "_id": 29}]}}
        UpperCamelCase	:					Optional[Any]       	=   Elasticsearch()

        dset.add_elasticsearch_index("filename"       ,							es_client=A_   )
        UpperCamelCase	,    UpperCamelCase	:					List[str]       	=   dset.get_nearest_examples("filename"       ,							"my_name-train_29"   )
        self.assertEqual(examples["filename"][0]       ,							"my_name-train_29"   )



@require_faiss
class 					A__   (       __snake_case			):





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       import faiss

       UpperCamelCase	:					Optional[int]       	=   FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT   )

       # add vectors
       index.add_vectors(np.eye(5       ,							dtype=np.floataa   )   )
       self.assertIsNotNone(index.faiss_index   )
       self.assertEqual(index.faiss_index.ntotal       ,							5   )
       index.add_vectors(np.zeros((5, 5)       ,							dtype=np.floataa   )   )
       self.assertEqual(index.faiss_index.ntotal       ,							10   )

       # single query
       UpperCamelCase	:					Any       	=   np.zeros(5       ,							dtype=np.floataa   )
       UpperCamelCase	:					Optional[Any]       	=   1
       UpperCamelCase	,    UpperCamelCase	:					Optional[Any]       	=   index.search(A_   )
       self.assertRaises(A_       ,							index.search       ,							query.reshape(-1       ,							1   )   )
       self.assertGreater(scores[0]       ,							0   )
       self.assertEqual(indices[0]       ,							1   )

       # batched queries
       UpperCamelCase	:					Optional[int]       	=   np.eye(5       ,							dtype=np.floataa   )[::-1]
       UpperCamelCase	,    UpperCamelCase	:					Tuple       	=   index.search_batch(A_   )
       self.assertRaises(A_       ,							index.search_batch       ,							queries[0]   )
       UpperCamelCase	:					Optional[int]       	=   [scores[0] for scores in total_scores]
       UpperCamelCase	:					Tuple       	=   [indices[0] for indices in total_indices]
       self.assertGreater(np.min(A_   )       ,							0   )
       self.assertListEqual([4, 3, 2, 1, 0]       ,							A_   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       import faiss

       UpperCamelCase	:					List[str]       	=   FaissIndex(string_factory="Flat"   )
       index.add_vectors(np.eye(5       ,							dtype=np.floataa   )   )
       self.assertIsInstance(index.faiss_index       ,							faiss.IndexFlat   )
       UpperCamelCase	:					List[str]       	=   FaissIndex(string_factory="LSH"   )
       index.add_vectors(np.eye(5       ,							dtype=np.floataa   )   )
       self.assertIsInstance(index.faiss_index       ,							faiss.IndexLSH   )
       with self.assertRaises(A_   ):
        UpperCamelCase	:					List[str]       	=   FaissIndex(string_factory="Flat"       ,							custom_index=faiss.IndexFlat(5   )   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       import faiss

       UpperCamelCase	:					Dict       	=   faiss.IndexFlat(5   )
       UpperCamelCase	:					Union[str, Any]       	=   FaissIndex(custom_index=A_   )
       index.add_vectors(np.eye(5       ,							dtype=np.floataa   )   )
       self.assertIsInstance(index.faiss_index       ,							faiss.IndexFlat   )





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       import faiss

       UpperCamelCase	:					str       	=   FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT   )
       index.add_vectors(np.eye(5       ,							dtype=np.floataa   )   )

       # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
       # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
       # see https://bugs.python.org/issue14243 and
       # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
       with tempfile.NamedTemporaryFile(delete=A_   ) as tmp_file:
        index.save(tmp_file.name   )
        UpperCamelCase	:					int       	=   FaissIndex.load(tmp_file.name   )
       os.unlink(tmp_file.name   )

       UpperCamelCase	:					str       	=   np.zeros(5       ,							dtype=np.floataa   )
       UpperCamelCase	:					int       	=   1
       UpperCamelCase	,    UpperCamelCase	:					Dict       	=   index.search(A_   )
       self.assertGreater(scores[0]       ,							0   )
       self.assertEqual(indices[0]       ,							1   )



@require_faiss
def 		A_				(     _lowerCAmelCase     )						-> Optional[int]:
 import faiss

 UpperCamelCase	:					Union[str, Any]       	=   FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT     )
 index.add_vectors(np.eye(5							,   dtype=np.floataa     )     )

 UpperCamelCase	:					List[Any]       	=   "index.faiss"
 UpperCamelCase	:					List[str]       	=   F"""mock://{index_name}"""
 index.save(_lowerCAmelCase							,   storage_options=mockfs.storage_options     )
 UpperCamelCase	:					List[str]       	=   FaissIndex.load(_lowerCAmelCase							,   storage_options=mockfs.storage_options     )

 UpperCamelCase	:					List[str]       	=   np.zeros(5							,   dtype=np.floataa     )
 UpperCamelCase	:					Optional[int]       	=   1
 UpperCamelCase	,    UpperCamelCase	:					List[str]       	=   index.search(_lowerCAmelCase     )
 assert scores[0] > 0
 assert indices[0] == 1



@require_elasticsearch
class 					A__   (       __snake_case			):





      def        __UpperCamelCase( self   ):
       '''simple docstring'''




       from elasticsearch import Elasticsearch

       with patch("elasticsearch.Elasticsearch.search"   ) as mocked_search, patch(
           "elasticsearch.client.IndicesClient.create"   ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk"   ) as mocked_bulk:
        UpperCamelCase	:					List[str]       	=   Elasticsearch()
        UpperCamelCase	:					Union[str, Any]       	=   {"acknowledged": True}
        UpperCamelCase	:					Union[str, Any]       	=   ElasticSearchIndex(es_client=A_   )
        mocked_bulk.return_value([(True, None)] * 3   )
        index.add_documents(["foo", "bar", "foobar"]   )

        # single query
        UpperCamelCase	:					str       	=   "foo"
        UpperCamelCase	:					Dict       	=   {"hits": {"hits": [{"_score": 1, "_id": 0}]}}
        UpperCamelCase	,    UpperCamelCase	:					Tuple       	=   index.search(A_   )
        self.assertEqual(scores[0]       ,							1   )
        self.assertEqual(indices[0]       ,							0   )

        # single query with timeout
        UpperCamelCase	:					Dict       	=   "foo"
        UpperCamelCase	:					Optional[Any]       	=   {"hits": {"hits": [{"_score": 1, "_id": 0}]}}
        UpperCamelCase	,    UpperCamelCase	:					str       	=   index.search(A_       ,							request_timeout=30   )
        self.assertEqual(scores[0]       ,							1   )
        self.assertEqual(indices[0]       ,							0   )

        # batched queries
        UpperCamelCase	:					Dict       	=   ["foo", "bar", "foobar"]
        UpperCamelCase	:					List[Any]       	=   {"hits": {"hits": [{"_score": 1, "_id": 1}]}}
        UpperCamelCase	,    UpperCamelCase	:					Optional[int]       	=   index.search_batch(A_   )
        UpperCamelCase	:					str       	=   [scores[0] for scores in total_scores]
        UpperCamelCase	:					Optional[Any]       	=   [indices[0] for indices in total_indices]
        self.assertGreater(np.min(A_   )       ,							0   )
        self.assertListEqual([1, 1, 1]       ,							A_   )

        # batched queries with timeout
        UpperCamelCase	:					int       	=   ["foo", "bar", "foobar"]
        UpperCamelCase	:					List[Any]       	=   {"hits": {"hits": [{"_score": 1, "_id": 1}]}}
        UpperCamelCase	,    UpperCamelCase	:					Union[str, Any]       	=   index.search_batch(A_       ,							request_timeout=30   )
        UpperCamelCase	:					Union[str, Any]       	=   [scores[0] for scores in total_scores]
        UpperCamelCase	:					Dict       	=   [indices[0] for indices in total_indices]
        self.assertGreater(np.min(A_   )       ,							0   )
        self.assertListEqual([1, 1, 1]       ,							A_   )
