

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


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

_lowerCamelCase    :       Optional[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       					=					4_2






class  __UpperCAmelCase					(	lowerCamelCase__						):



   def __init__(							self							:					Union[str, Any],		__A							:					PriorTransformer,		__A							:					CLIPVisionModel,		__A							:					CLIPImageProcessor,		__A							:					HeunDiscreteScheduler,		__A							:					ShapERenderer,		):
     super().__init__()

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



   def 	__magic_name__   (							self							:					Optional[int],		__A							:					Optional[Any],		__A							:					Any,		__A							:					Union[str, Any],		__A							:					List[Any],		__A							:					Any,		__A							:					Union[str, Any]						):
     if latents is None:
       UpperCAmelCase	:							Tuple						=			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	:							List[str]						=			latents.to(__A						)

     UpperCAmelCase	:							Union[str, Any]						=			latents * scheduler.init_noise_sigma
     return latents



   def 	__magic_name__   (							self							:					Union[str, Any],		__A							:					Optional[int]=0						):
     if is_accelerate_available():
       from accelerate import cpu_offload
     else:
       raise ImportError('''Please install accelerate via `pip install accelerate`'''						)

     UpperCAmelCase	:							int						=			torch.device(F'''cuda:{gpu_id}'''						)

     UpperCAmelCase	:							int						=			[self.image_encoder, self.prior]
     for cpu_offloaded_model in models:
       if cpu_offloaded_model is not None:
         cpu_offload(__A,		__A						)



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

     if not isinstance(__A,		torch.Tensor						):
       UpperCAmelCase	:							int						=			self.image_processor(__A,		return_tensors='''pt'''						).pixel_values[0].unsqueeze(0						)

     UpperCAmelCase	:							Dict						=			image.to(dtype=self.image_encoder.dtype,		device=__A						)

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

     UpperCAmelCase	:							Union[str, Any]						=			image_embeds.repeat_interleave(__A,		dim=0						)

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

     return image_embeds





   @torch.no_grad()
   @replace_example_docstring(__A						)
   def __call__(							self							:					List[Any],		__A							:					Union[PIL.Image.Image, List[PIL.Image.Image]],		__A							:					int = 1,		__A							:					int = 2_5,		__A							:					Optional[Union[torch.Generator, List[torch.Generator]]] = None,		__A							:					Optional[torch.FloatTensor] = None,		__A							:					float = 4.0,		__A							:					int = 6_4,		__A							:					Optional[str] = "pil",		__A							:					bool = True,		):

     if isinstance(__A,		PIL.Image.Image						):
       UpperCAmelCase	:							Tuple						=			1
     elif isinstance(__A,		torch.Tensor						):
       UpperCAmelCase	:							Tuple						=			image.shape[0]
     elif isinstance(__A,		__A						) and isinstance(image[0],		(torch.Tensor, PIL.Image.Image)						):
       UpperCAmelCase	:							Dict						=			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	:							Tuple						=			self._execution_device

     UpperCAmelCase	:							int						=			batch_size * num_images_per_prompt

     UpperCAmelCase	:							str						=			guidance_scale > 1.0
     UpperCAmelCase	:							List[Any]						=			self._encode_image(__A,		__A,		__A,		__A						)

     # prior

     self.scheduler.set_timesteps(__A,		device=__A						)
     UpperCAmelCase	:							Dict						=			self.scheduler.timesteps

     UpperCAmelCase	:							Union[str, Any]						=			self.prior.config.num_embeddings
     UpperCAmelCase	:							Optional[int]						=			self.prior.config.embedding_dim

     UpperCAmelCase	:							Any						=			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	:							List[Any]						=			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	:							List[str]						=			torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
       UpperCAmelCase	:							Optional[Any]						=			self.scheduler.scale_model_input(__A,		__A						)

       UpperCAmelCase	:							Any						=			self.prior(
           __A,		timestep=__A,		proj_embedding=__A,		).predicted_image_embedding

       # remove the variance
       UpperCAmelCase	:							Tuple						=			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	:							List[str]						=			noise_pred.chunk(2						)
         UpperCAmelCase	:							int						=			noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

       UpperCAmelCase	:							int						=			self.scheduler.step(
           __A,		timestep=__A,		sample=__A,		).prev_sample

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

     UpperCAmelCase	:							Union[str, Any]						=			[]
     for i, latent in enumerate(__A						):
       print()
       UpperCAmelCase	:							Any						=			self.renderer.decode(
           latent[None, :],		__A,		size=__A,		ray_batch_size=4_0_9_6,		n_coarse_samples=6_4,		n_fine_samples=1_2_8,		)

       images.append(__A						)

     UpperCAmelCase	:							Optional[int]						=			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	:							str						=			images.cpu().numpy()

     if output_type == "pil":
       UpperCAmelCase	:							str						=			[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 unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
     import torch

if is_vision_available():
     from PIL import Image

     from transformers import ChineseCLIPImageProcessor





class  __UpperCAmelCase					(	unittest.TestCase						):



   def __init__(							self							:					List[Any],		__A							:					str,		__A							:					List[str]=7,		__A							:					List[str]=3,		__A							:					Optional[int]=1_8,		__A							:					List[Any]=3_0,		__A							:					Tuple=4_0_0,		__A							:					Tuple=True,		__A							:					List[Any]=None,		__A							:					str=True,		__A							:					int=None,		__A							:					Optional[Any]=True,		__A							:					List[Any]=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3],		__A							:					List[str]=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1],		__A							:					Tuple=True,		):
     UpperCAmelCase	:							int						=			size if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
     UpperCAmelCase	:							Optional[Any]						=			crop_size if crop_size is not None else {'''height''': 1_8, '''width''': 1_8}
     UpperCAmelCase	:							int						=			parent
     UpperCAmelCase	:							Union[str, Any]						=			batch_size
     UpperCAmelCase	:							List[Any]						=			num_channels
     UpperCAmelCase	:							Dict						=			image_size
     UpperCAmelCase	:							List[str]						=			min_resolution
     UpperCAmelCase	:							Optional[Any]						=			max_resolution
     UpperCAmelCase	:							Union[str, Any]						=			do_resize
     UpperCAmelCase	:							Dict						=			size
     UpperCAmelCase	:							Any						=			do_center_crop
     UpperCAmelCase	:							Union[str, Any]						=			crop_size
     UpperCAmelCase	:							List[str]						=			do_normalize
     UpperCAmelCase	:							Optional[Any]						=			image_mean
     UpperCAmelCase	:							Optional[Any]						=			image_std
     UpperCAmelCase	:							List[Any]						=			do_convert_rgb



   def 	__magic_name__   (							self							:					int						):
     return {
         "do_resize": self.do_resize,
         "size": self.size,
         "do_center_crop": self.do_center_crop,
         "crop_size": self.crop_size,
         "do_normalize": self.do_normalize,
         "image_mean": self.image_mean,
         "image_std": self.image_std,
         "do_convert_rgb": self.do_convert_rgb,
     }





   def 	__magic_name__   (							self							:					Optional[Any],		__A							:					Any=False,		__A							:					str=False,		__A							:					List[Any]=False						):
     assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

     if equal_resolution:
       UpperCAmelCase	:							Dict						=			[]
       for i in range(self.batch_size						):
         image_inputs.append(
             np.random.randint(
                 2_5_5,		size=(self.num_channels, self.max_resolution, self.max_resolution),		dtype=np.uinta						)						)
     else:
       UpperCAmelCase	:							Tuple						=			[]
       for i in range(self.batch_size						):
         UpperCAmelCase			,						UpperCAmelCase	:							Tuple						=			np.random.choice(np.arange(self.min_resolution,		self.max_resolution						),		2						)
         image_inputs.append(np.random.randint(2_5_5,		size=(self.num_channels, width, height),		dtype=np.uinta						)						)

     if not numpify and not torchify:
       # PIL expects the channel dimension as last dimension
       UpperCAmelCase	:							Optional[int]						=			[Image.fromarray(np.moveaxis(__A,		0,		-1						)						) for x in image_inputs]

     if torchify:
       UpperCAmelCase	:							str						=			[torch.from_numpy(__A						) for x in image_inputs]

     return image_inputs






@require_torch
@require_vision
class  __UpperCAmelCase					(	lowerCamelCase__      ,  unittest.TestCase						):
   UpperCamelCase       					=					ChineseCLIPImageProcessor if is_vision_available() else None



   def 	__magic_name__   (							self							:					Dict						):
     UpperCAmelCase	:							Optional[Any]						=			ChineseCLIPImageProcessingTester(self,		do_center_crop=__A						)



   @property
   def 	__magic_name__   (							self							:					Tuple						):
     return self.image_processor_tester.prepare_image_processor_dict()



   def 	__magic_name__   (							self							:					Any						):
     UpperCAmelCase	:							List[Any]						=			self.image_processing_class(**self.image_processor_dict						)
     self.assertTrue(hasattr(__A,		'''do_resize'''						)						)
     self.assertTrue(hasattr(__A,		'''size'''						)						)
     self.assertTrue(hasattr(__A,		'''do_center_crop'''						)						)
     self.assertTrue(hasattr(__A,		'''center_crop'''						)						)
     self.assertTrue(hasattr(__A,		'''do_normalize'''						)						)
     self.assertTrue(hasattr(__A,		'''image_mean'''						)						)
     self.assertTrue(hasattr(__A,		'''image_std'''						)						)
     self.assertTrue(hasattr(__A,		'''do_convert_rgb'''						)						)



   def 	__magic_name__   (							self							:					Optional[Any]						):
     UpperCAmelCase	:							Union[str, Any]						=			self.image_processing_class.from_dict(self.image_processor_dict						)
     self.assertEqual(image_processor.size,		{'''height''': 2_2_4, '''width''': 2_2_4}						)
     self.assertEqual(image_processor.crop_size,		{'''height''': 1_8, '''width''': 1_8}						)

     UpperCAmelCase	:							int						=			self.image_processing_class.from_dict(self.image_processor_dict,		size=4_2,		crop_size=8_4						)
     self.assertEqual(image_processor.size,		{'''shortest_edge''': 4_2}						)
     self.assertEqual(image_processor.crop_size,		{'''height''': 8_4, '''width''': 8_4}						)



   def 	__magic_name__   (							self							:					Union[str, Any]						):
     pass



   def 	__magic_name__   (							self							:					Tuple						):
     # Initialize image_processing
     UpperCAmelCase	:							Dict						=			self.image_processing_class(**self.image_processor_dict						)
     # create random PIL images
     UpperCAmelCase	:							Optional[int]						=			self.image_processor_tester.prepare_inputs(equal_resolution=__A						)
     for image in image_inputs:
       self.assertIsInstance(__A,		Image.Image						)

     # Test not batched input
     UpperCAmelCase	:							str						=			image_processing(image_inputs[0],		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_images.shape,		(
             1,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         ),		)

     # Test batched
     UpperCAmelCase	:							Any						=			image_processing(__A,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_images.shape,		(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         ),		)



   def 	__magic_name__   (							self							:					Optional[Any]						):
     # Initialize image_processing
     UpperCAmelCase	:							List[str]						=			self.image_processing_class(**self.image_processor_dict						)
     # create random numpy tensors
     UpperCAmelCase	:							List[Any]						=			self.image_processor_tester.prepare_inputs(equal_resolution=__A,		numpify=__A						)
     for image in image_inputs:
       self.assertIsInstance(__A,		np.ndarray						)

     # Test not batched input
     UpperCAmelCase	:							List[str]						=			image_processing(image_inputs[0],		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_images.shape,		(
             1,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         ),		)

     # Test batched
     UpperCAmelCase	:							Dict						=			image_processing(__A,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_images.shape,		(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         ),		)





   def 	__magic_name__   (							self							:					Any						):
     # Initialize image_processing
     UpperCAmelCase	:							str						=			self.image_processing_class(**self.image_processor_dict						)
     # create random PyTorch tensors
     UpperCAmelCase	:							Optional[Any]						=			self.image_processor_tester.prepare_inputs(equal_resolution=__A,		torchify=__A						)
     for image in image_inputs:
       self.assertIsInstance(__A,		torch.Tensor						)

     # Test not batched input
     UpperCAmelCase	:							str						=			image_processing(image_inputs[0],		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_images.shape,		(
             1,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         ),		)

     # Test batched
     UpperCAmelCase	:							List[str]						=			image_processing(__A,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_images.shape,		(
             self.image_processor_tester.batch_size,
             self.image_processor_tester.num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         ),		)






@require_torch
@require_vision
class  __UpperCAmelCase					(	lowerCamelCase__      ,  unittest.TestCase						):
   UpperCamelCase       					=					ChineseCLIPImageProcessor if is_vision_available() else None



   def 	__magic_name__   (							self							:					Optional[Any]						):
     UpperCAmelCase	:							str						=			ChineseCLIPImageProcessingTester(self,		num_channels=4,		do_center_crop=__A						)
     UpperCAmelCase	:							Dict						=			3



   @property
   def 	__magic_name__   (							self							:					List[Any]						):
     return self.image_processor_tester.prepare_image_processor_dict()



   def 	__magic_name__   (							self							:					Dict						):
     UpperCAmelCase	:							List[Any]						=			self.image_processing_class(**self.image_processor_dict						)
     self.assertTrue(hasattr(__A,		'''do_resize'''						)						)
     self.assertTrue(hasattr(__A,		'''size'''						)						)
     self.assertTrue(hasattr(__A,		'''do_center_crop'''						)						)
     self.assertTrue(hasattr(__A,		'''center_crop'''						)						)
     self.assertTrue(hasattr(__A,		'''do_normalize'''						)						)
     self.assertTrue(hasattr(__A,		'''image_mean'''						)						)
     self.assertTrue(hasattr(__A,		'''image_std'''						)						)
     self.assertTrue(hasattr(__A,		'''do_convert_rgb'''						)						)



   def 	__magic_name__   (							self							:					List[Any]						):
     pass





   def 	__magic_name__   (							self							:					Tuple						):
     # Initialize image_processing
     UpperCAmelCase	:							Optional[Any]						=			self.image_processing_class(**self.image_processor_dict						)
     # create random PIL images
     UpperCAmelCase	:							Dict						=			self.image_processor_tester.prepare_inputs(equal_resolution=__A						)
     for image in image_inputs:
       self.assertIsInstance(__A,		Image.Image						)

     # Test not batched input
     UpperCAmelCase	:							Tuple						=			image_processing(image_inputs[0],		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_images.shape,		(
             1,
             self.expected_encoded_image_num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         ),		)

     # Test batched
     UpperCAmelCase	:							Tuple						=			image_processing(__A,		return_tensors='''pt'''						).pixel_values
     self.assertEqual(
         encoded_images.shape,		(
             self.image_processor_tester.batch_size,
             self.expected_encoded_image_num_channels,
             self.image_processor_tester.crop_size['''height'''],
             self.image_processor_tester.crop_size['''width'''],
         ),		)





