'''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     A__							(       _snake_case   ):





   """simple docstring"""





   UpperCamelCase_       :						Union[PIL.Image.Image, np.ndarray]





class     A__							(       _snake_case   ):





   """simple docstring"""





   def __init__( self     :		Optional[int]						,     lowerCAmelCase__     :		Optional[int]						,     lowerCAmelCase__     :		List[str]						,     lowerCAmelCase__     :		Union[str, Any]						,     lowerCAmelCase__     :		Tuple						,     lowerCAmelCase__     :		List[Any]						,     )       ->    Any:







      """simple docstring"""




      super().__init__()

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




   def 			_lowerCAmelCase		( self     :		Union[str, Any]						,     lowerCAmelCase__     :		Tuple						,     lowerCAmelCase__     :		Any						,     lowerCAmelCase__     :		Optional[Any]						,     lowerCAmelCase__     :		Tuple						,     lowerCAmelCase__     :		Dict						,     lowerCAmelCase__     :		Optional[Any]			)       ->    List[Any]:







      """simple docstring"""




      if latents is None:
         _UpperCAmelCase							:	str							=   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}"""			)
         _UpperCAmelCase							:	Tuple							=   latents.to(_UpperCamelCase			)

      _UpperCAmelCase							:	Tuple							=   latents * scheduler.init_noise_sigma
      return latents




   def 			_lowerCAmelCase		( self     :		Union[str, Any]						,     lowerCAmelCase__     :		Optional[Any]=0			)       ->    Union[str, Any]:







      """simple docstring"""




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




   @property
   def 			_lowerCAmelCase		( self     :		str			)       ->    int:







      """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(_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 			_lowerCAmelCase		( self     :		Union[str, Any]						,     lowerCAmelCase__     :		List[Any]						,     lowerCAmelCase__     :		int						,     lowerCAmelCase__     :		List[Any]						,     lowerCAmelCase__     :		str						,     )       ->    str:







      """simple docstring"""




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

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

      _UpperCAmelCase							:	Tuple							=   image.to(dtype=self.image_encoder.dtype						,     device=_UpperCamelCase			)

      _UpperCAmelCase							:	Optional[Any]							=   self.image_encoder(_UpperCamelCase			)['last_hidden_state']
      _UpperCAmelCase							:	Union[str, Any]							=   image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

      _UpperCAmelCase							:	List[str]							=   image_embeds.repeat_interleave(_UpperCamelCase						,     dim=0			)

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

      return image_embeds




   @torch.no_grad()
   @replace_example_docstring(_UpperCamelCase			)
   def __call__( self     :		Dict						,     lowerCAmelCase__     :		Union[str, Any]						,     lowerCAmelCase__     :		str = 1						,     lowerCAmelCase__     :		Optional[int] = 2_5						,     lowerCAmelCase__     :		int = None						,     lowerCAmelCase__     :		Optional[int] = None						,     lowerCAmelCase__     :		Dict = 4.0						,     lowerCAmelCase__     :		str = 6_4						,     lowerCAmelCase__     :		Dict = "pil"						,     lowerCAmelCase__     :		Optional[Any] = True						,     )       ->    Union[str, Any]:







      """simple docstring"""




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

      _UpperCAmelCase							:	Tuple							=   self._execution_device

      _UpperCAmelCase							:	str							=   batch_size * num_images_per_prompt

      _UpperCAmelCase							:	str							=   guidance_scale > 1.0
      _UpperCAmelCase							:	str							=   self._encode_image(_UpperCamelCase						,     _UpperCamelCase						,     _UpperCamelCase						,     _UpperCamelCase			)

      # prior

      self.scheduler.set_timesteps(_UpperCamelCase						,     device=_UpperCamelCase			)
      _UpperCAmelCase							:	int							=   self.scheduler.timesteps

      _UpperCAmelCase							:	int							=   self.prior.config.num_embeddings
      _UpperCAmelCase							:	Any							=   self.prior.config.embedding_dim

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

         _UpperCAmelCase							:	int							=   self.prior(
             _UpperCamelCase						,     timestep=_UpperCamelCase						,     proj_embedding=_UpperCamelCase						,     ).predicted_image_embedding

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

         _UpperCAmelCase							:	List[str]							=   self.scheduler.step(
             _UpperCamelCase						,     timestep=_UpperCamelCase						,     sample=_UpperCamelCase						,     ).prev_sample

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

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

         images.append(_UpperCamelCase			)

      _UpperCAmelCase							:	Optional[int]							=   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}"""			)

      _UpperCAmelCase							:	Dict							=   images.cpu().numpy()

      if output_type == "pil":
         _UpperCAmelCase							:	List[str]							=   [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			)







import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin



@skip_mps
class   lowerCamelCase      (_snake_case ,  _snake_case ,  unittest.TestCase			):







		'''simple docstring'''



		_snake_case    :    Union[str, Any]       						=  IFImgaImgSuperResolutionPipeline
		_snake_case    :    Union[str, Any]       						=  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''}
		_snake_case    :    List[Any]       						=  TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''}			)
		_snake_case    :    List[str]       						=  PipelineTesterMixin.required_optional_params - {'''latents'''}



		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							return self._get_superresolution_dummy_components()



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase=0   )	->							Any:
							if str(_UpperCamelCase   ).startswith('mps'   ):
												UpperCAmelCase_    :      List[Any]            =						torch.manual_seed(_UpperCamelCase   )
							else:
												UpperCAmelCase_    :      int            =						torch.Generator(device=_UpperCamelCase   ).manual_seed(_UpperCamelCase   )

							UpperCAmelCase_    :      List[Any]            =						floats_tensor((1, 3, 3_2, 3_2)				,		rng=random.Random(_UpperCamelCase   )   ).to(_UpperCamelCase   )
							UpperCAmelCase_    :      Dict            =						floats_tensor((1, 3, 1_6, 1_6)				,		rng=random.Random(_UpperCamelCase   )   ).to(_UpperCamelCase   )

							UpperCAmelCase_    :      Tuple            =						{
							    'prompt': 'A painting of a squirrel eating a burger',
							    'image': image,
							    'original_image': original_image,
							    'generator': generator,
							    'num_inference_steps': 2,
							    'output_type': 'numpy',
							}

							return inputs



		@unittest.skipIf(
		    torch_device != 'cuda' or not is_xformers_available()				,		reason='XFormers attention is only available with CUDA and `xformers` installed'				,		)
		def 					__UpperCAmelCase			(							self   )	->							Any:
							self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3   )



		def 					__UpperCAmelCase			(							self   )	->							Dict:
							self._test_save_load_optional_components()



		@unittest.skipIf(torch_device != 'cuda'				,		reason='float16 requires CUDA'   )
		def 					__UpperCAmelCase			(							self   )	->							str:
							# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
							super().test_save_load_floataa(expected_max_diff=1E-1   )



		def 					__UpperCAmelCase			(							self   )	->							List[Any]:
							self._test_attention_slicing_forward_pass(expected_max_diff=1E-2   )



		def 					__UpperCAmelCase			(							self   )	->							Union[str, Any]:
							self._test_save_load_local()



		def 					__UpperCAmelCase			(							self   )	->							Dict:
							self._test_inference_batch_single_identical(
							    expected_max_diff=1E-2				,		)






