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


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

_A						=			'\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 	_lowercase       (    __UpperCAmelCase		):
	lowercase_				=     42






class 	_lowercase       (    __UpperCAmelCase		):




	def __init__(			self		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_		,			)		->							Optional[int]:
			super().__init__()

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




	def       _UpperCamelCase   (			self		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_ )		->							Optional[int]:
			if latents is None:
					lowerCamelCase					:      Any          =   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}""" )
					lowerCamelCase					:      str          =   latents.to(UpperCAmelCase_ )

			lowerCamelCase					:      str          =   latents * scheduler.init_noise_sigma
			return latents




	def       _UpperCamelCase   (			self		,			UpperCAmelCase_=0 )		->							Optional[int]:
			if is_accelerate_available():
					from accelerate import cpu_offload
			else:
					raise ImportError('Please install accelerate via `pip install accelerate`' )

			lowerCamelCase					:      List[Any]          =   torch.device(F"""cuda:{gpu_id}""" )

			lowerCamelCase					:      Any          =   [self.image_encoder, self.prior]
			for cpu_offloaded_model in models:
					if cpu_offloaded_model is not None:
							cpu_offload(UpperCAmelCase_		,			UpperCAmelCase_ )




	@property
	def       _UpperCamelCase   (			self )		->							Dict:
			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(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       _UpperCamelCase   (			self		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_		,			)		->							List[Any]:
			if isinstance(UpperCAmelCase_		,			UpperCAmelCase_ ) and isinstance(image[0]		,			torch.Tensor ):
					lowerCamelCase					:      Union[str, Any]          =   torch.cat(UpperCAmelCase_		,			axis=0 ) if image[0].ndim == 4 else torch.stack(UpperCAmelCase_		,			axis=0 )

			if not isinstance(UpperCAmelCase_		,			torch.Tensor ):
					lowerCamelCase					:      Optional[Any]          =   self.image_processor(UpperCAmelCase_		,			return_tensors='pt' ).pixel_values[0].unsqueeze(0 )

			lowerCamelCase					:      Optional[int]          =   image.to(dtype=self.image_encoder.dtype		,			device=UpperCAmelCase_ )

			lowerCamelCase					:      Optional[int]          =   self.image_encoder(UpperCAmelCase_ )['last_hidden_state']
			lowerCamelCase					:      Optional[int]          =   image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

			lowerCamelCase					:      List[Any]          =   image_embeds.repeat_interleave(UpperCAmelCase_		,			dim=0 )

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

			return image_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		,			)		->							Optional[int]:

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

			lowerCamelCase					:      Optional[Any]          =   self._execution_device

			lowerCamelCase					:      str          =   batch_size * num_images_per_prompt

			lowerCamelCase					:      Tuple          =   guidance_scale > 1.0
			lowerCamelCase					:      List[str]          =   self._encode_image(UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_		,			UpperCAmelCase_ )

			# prior

			self.scheduler.set_timesteps(UpperCAmelCase_		,			device=UpperCAmelCase_ )
			lowerCamelCase					:      List[str]          =   self.scheduler.timesteps

			lowerCamelCase					:      Optional[int]          =   self.prior.config.num_embeddings
			lowerCamelCase					:      Dict          =   self.prior.config.embedding_dim

			lowerCamelCase					:      Union[str, Any]          =   self.prepare_latents(
			    (batch_size, num_embeddings * embedding_dim)		,			image_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
			lowerCamelCase					:      Union[str, Any]          =   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
					lowerCamelCase					:      str          =   torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
					lowerCamelCase					:      List[str]          =   self.scheduler.scale_model_input(UpperCAmelCase_		,			UpperCAmelCase_ )

					lowerCamelCase					:      Tuple          =   self.prior(
					    UpperCAmelCase_		,			timestep=UpperCAmelCase_		,			proj_embedding=UpperCAmelCase_		,			).predicted_image_embedding

					# remove the variance
					lowerCamelCase     ,   lowerCamelCase					:      Union[str, Any]          =   noise_pred.split(
					    scaled_model_input.shape[2]		,			dim=2 )  # batch_size, num_embeddings, embedding_dim

					if do_classifier_free_guidance is not None:
							lowerCamelCase     ,   lowerCamelCase					:      Optional[Any]          =   noise_pred.chunk(2 )
							lowerCamelCase					:      List[Any]          =   noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

					lowerCamelCase					:      str          =   self.scheduler.step(
					    UpperCAmelCase_		,			timestep=UpperCAmelCase_		,			sample=UpperCAmelCase_		,			).prev_sample

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

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

					images.append(UpperCAmelCase_ )

			lowerCamelCase					:      Tuple          =   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}""" )

			lowerCamelCase					:      List[Any]          =   images.cpu().numpy()

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








"""simple docstring"""

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


_A						=			pytest.mark.integration






@require_faiss
class 	_lowercase       (    __UpperCAmelCase		):




	def       _UpperCamelCase   (			self )		->							Union[str, Any]:
			lowerCamelCase					:      Any          =   Dataset.from_dict({'filename': ['my_name-train' + '_' + str(UpperCAmelCase_ ) for x in np.arange(30 ).tolist()]} )
			return dset




	def       _UpperCamelCase   (			self )		->							List[Any]:
			import faiss

			lowerCamelCase					:      Dataset          =   self._create_dummy_dataset()
			lowerCamelCase					:      Optional[int]          =   dset.map(
			    lambda UpperCAmelCase_		,			UpperCAmelCase_ : {"vecs": i * np.ones(5		,			dtype=np.floataa )}		,			with_indices=UpperCAmelCase_		,			keep_in_memory=UpperCAmelCase_ )
			lowerCamelCase					:      Dict          =   dset.add_faiss_index('vecs'		,			batch_size=100		,			metric_type=faiss.METRIC_INNER_PRODUCT )
			lowerCamelCase     ,   lowerCamelCase					:      List[str]          =   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 )		->							Tuple:
			import faiss

			lowerCamelCase					:      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		,			)
			lowerCamelCase     ,   lowerCamelCase					:      str          =   dset.get_nearest_examples('vecs'		,			np.ones(5		,			dtype=np.floataa ) )
			self.assertEqual(examples['filename'][0]		,			'my_name-train_29' )




	def       _UpperCamelCase   (			self )		->							int:
			import faiss

			lowerCamelCase					:      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=UpperCAmelCase_ ) as tmp_file:
					dset.save_faiss_index('vecs'		,			tmp_file.name )
					dset.load_faiss_index('vecs2'		,			tmp_file.name )
			os.unlink(tmp_file.name )

			lowerCamelCase     ,   lowerCamelCase					:      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 )		->							Any:
			lowerCamelCase					:      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(UpperCAmelCase_		,			partial(dset.get_nearest_examples		,			'vecs2'		,			np.ones(5		,			dtype=np.floataa ) ) )




	def       _UpperCamelCase   (			self )		->							Union[str, Any]:
			from elasticsearch import Elasticsearch

			lowerCamelCase					:      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:
					lowerCamelCase					:      Tuple          =   {'acknowledged': True}
					mocked_bulk.return_value([(True, None)] * 30 )
					lowerCamelCase					:      int          =   {'hits': {'hits': [{'_score': 1, '_id': 29}]}}
					lowerCamelCase					:      Optional[Any]          =   Elasticsearch()

					dset.add_elasticsearch_index('filename'		,			es_client=UpperCAmelCase_ )
					lowerCamelCase     ,   lowerCamelCase					:      str          =   dset.get_nearest_examples('filename'		,			'my_name-train_29' )
					self.assertEqual(examples['filename'][0]		,			'my_name-train_29' )






@require_faiss
class 	_lowercase       (    __UpperCAmelCase		):




	def       _UpperCamelCase   (			self )		->							Union[str, Any]:
			import faiss

			lowerCamelCase					:      str          =   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
			lowerCamelCase					:      Optional[int]          =   np.zeros(5		,			dtype=np.floataa )
			lowerCamelCase					:      List[str]          =   1
			lowerCamelCase     ,   lowerCamelCase					:      int          =   index.search(UpperCAmelCase_ )
			self.assertRaises(UpperCAmelCase_		,			index.search		,			query.reshape(-1		,			1 ) )
			self.assertGreater(scores[0]		,			0 )
			self.assertEqual(indices[0]		,			1 )

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




	def       _UpperCamelCase   (			self )		->							Dict:
			import faiss

			lowerCamelCase					:      List[Any]          =   FaissIndex(string_factory='Flat' )
			index.add_vectors(np.eye(5		,			dtype=np.floataa ) )
			self.assertIsInstance(index.faiss_index		,			faiss.IndexFlat )
			lowerCamelCase					:      int          =   FaissIndex(string_factory='LSH' )
			index.add_vectors(np.eye(5		,			dtype=np.floataa ) )
			self.assertIsInstance(index.faiss_index		,			faiss.IndexLSH )
			with self.assertRaises(UpperCAmelCase_ ):
					lowerCamelCase					:      str          =   FaissIndex(string_factory='Flat'		,			custom_index=faiss.IndexFlat(5 ) )




	def       _UpperCamelCase   (			self )		->							Any:
			import faiss

			lowerCamelCase					:      Any          =   faiss.IndexFlat(5 )
			lowerCamelCase					:      Any          =   FaissIndex(custom_index=UpperCAmelCase_ )
			index.add_vectors(np.eye(5		,			dtype=np.floataa ) )
			self.assertIsInstance(index.faiss_index		,			faiss.IndexFlat )




	def       _UpperCamelCase   (			self )		->							Any:
			import faiss

			lowerCamelCase					:      Any          =   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=UpperCAmelCase_ ) as tmp_file:
					index.save(tmp_file.name )
					lowerCamelCase					:      List[str]          =   FaissIndex.load(tmp_file.name )
			os.unlink(tmp_file.name )

			lowerCamelCase					:      Dict          =   np.zeros(5		,			dtype=np.floataa )
			lowerCamelCase					:      Optional[Any]          =   1
			lowerCamelCase     ,   lowerCamelCase					:      str          =   index.search(UpperCAmelCase_ )
			self.assertGreater(scores[0]		,			0 )
			self.assertEqual(indices[0]		,			1 )


@require_faiss
def 		UpperCAmelCase (		a_      ):





		'''simple docstring'''


		import faiss

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

		lowerCamelCase					:      Union[str, Any]          =   'index.faiss'
		lowerCamelCase					:      List[Any]          =   F"""mock://{index_name}"""
		index.save(a_,						storage_options=mockfs.storage_options      )
		lowerCamelCase					:      Optional[int]          =   FaissIndex.load(a_,						storage_options=mockfs.storage_options      )

		lowerCamelCase					:      str          =   np.zeros(5,						dtype=np.floataa      )
		lowerCamelCase					:      str          =   1
		lowerCamelCase     ,   lowerCamelCase					:      int          =   index.search(a_      )
		assert scores[0] > 0
		assert indices[0] == 1






@require_elasticsearch
class 	_lowercase       (    __UpperCAmelCase		):




	def       _UpperCamelCase   (			self )		->							int:
			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:
					lowerCamelCase					:      Union[str, Any]          =   Elasticsearch()
					lowerCamelCase					:      Optional[Any]          =   {'acknowledged': True}
					lowerCamelCase					:      str          =   ElasticSearchIndex(es_client=UpperCAmelCase_ )
					mocked_bulk.return_value([(True, None)] * 3 )
					index.add_documents(['foo', 'bar', 'foobar'] )

					# single query
					lowerCamelCase					:      Tuple          =   'foo'
					lowerCamelCase					:      List[str]          =   {'hits': {'hits': [{'_score': 1, '_id': 0}]}}
					lowerCamelCase     ,   lowerCamelCase					:      Any          =   index.search(UpperCAmelCase_ )
					self.assertEqual(scores[0]		,			1 )
					self.assertEqual(indices[0]		,			0 )

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

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

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






