




import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

UpperCAmelCase__						:       Tuple							=    '\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = \"a shark\"\n\n        >>> images = pipe(\n        ...     prompt,\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], \"shark_3d.gif\")\n        ```\n'

@dataclass
class      UpperCAmelCase						(			UpperCamelCase__    ):
   __SCREAMING_SNAKE_CASE		:							str							=					42

class      UpperCAmelCase						(			UpperCamelCase__    ):






   def __init__(	self   :       Optional[int]						,					UpperCamelCase_   :       List[Any]						,					UpperCamelCase_   :       Optional[Any]						,					UpperCamelCase_   :       List[str]						,					UpperCamelCase_   :       Dict						,					UpperCamelCase_   :       str						,					)->			int:
     super().__init__()

     self.register_modules(
         prior=snake_case_						,					text_encoder=snake_case_						,					tokenizer=snake_case_						,					scheduler=snake_case_						,					renderer=snake_case_						,					)






   def  _a						(	self   :       Tuple						,					UpperCamelCase_   :       List[str]						,					UpperCamelCase_   :       List[Any]						,					UpperCamelCase_   :       str						,					UpperCamelCase_   :       List[str]						,					UpperCamelCase_   :       str						,					UpperCamelCase_   :       Union[str, Any]     )->			List[str]:
     if latents is None:
       _lowercase: Optional[Any]						     =    randn_tensor(snake_case_						,					generator=snake_case_						,					device=snake_case_						,					dtype=snake_case_     )
     else:
       if latents.shape != shape:
         raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'     )
       _lowercase: Any						     =    latents.to(snake_case_     )

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






   def  _a						(	self   :       Optional[Any]						,					UpperCamelCase_   :       Dict=0     )->			str:
     if is_accelerate_available():
       from accelerate import cpu_offload
     else:
       raise ImportError('Please install accelerate via `pip install accelerate`'     )

     _lowercase: int						     =    torch.device(f'cuda:{gpu_id}'     )

     _lowercase: str						     =    [self.text_encoder, self.prior]
     for cpu_offloaded_model in models:
       if cpu_offloaded_model is not None:
         cpu_offload(snake_case_						,					snake_case_     )






   def  _a						(	self   :       Tuple						,					UpperCamelCase_   :       Tuple=0     )->			Any:
     if is_accelerate_available() and is_accelerate_version('>='						,					'0.17.0.dev0'     ):
       from accelerate import cpu_offload_with_hook
     else:
       raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'     )

     _lowercase: List[Any]						     =    torch.device(f'cuda:{gpu_id}'     )

     if self.device.type != "cpu":
       self.to('cpu'						,					silence_dtype_warnings=snake_case_     )
       torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

     _lowercase: Any						     =    None
     for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
       _lowercase: List[Any]						     =    cpu_offload_with_hook(snake_case_						,					snake_case_						,					prev_module_hook=snake_case_     )

     if self.safety_checker is not None:
       _lowercase: Union[str, Any]						     =    cpu_offload_with_hook(self.safety_checker						,					snake_case_						,					prev_module_hook=snake_case_     )

     # We'll offload the last model manually.
     _lowercase: Optional[Any]						     =    hook






   @property
   def  _a						(	self   :       List[Any]     )->			Optional[int]:
     if self.device != torch.device('meta'     ) or not hasattr(self.text_encoder						,					'_hf_hook'     ):
       return self.device
     for module in self.text_encoder.modules():
       if (
           hasattr(snake_case_						,					'_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  _a						(	self   :       List[Any]						,					UpperCamelCase_   :       Any						,					UpperCamelCase_   :       Dict						,					UpperCamelCase_   :       str						,					UpperCamelCase_   :       Optional[Any]						,					)->			List[Any]:
     len(snake_case_     ) if isinstance(snake_case_						,					snake_case_     ) else 1

     # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
     _lowercase: List[str]						     =    0
     # get prompt text embeddings
     _lowercase: Dict						     =    self.tokenizer(
         snake_case_						,					padding='max_length'						,					max_length=self.tokenizer.model_max_length						,					truncation=snake_case_						,					return_tensors='pt'						,					)
     _lowercase: List[Any]						     =    text_inputs.input_ids
     _lowercase: Optional[int]						     =    self.tokenizer(snake_case_						,					padding='longest'						,					return_tensors='pt'     ).input_ids

     if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(snake_case_						,					snake_case_     ):
       _lowercase: Optional[Any]						     =    self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]     )
       logger.warning(
           'The following part of your input was truncated because CLIP can only handle sequences up to'
           f' {self.tokenizer.model_max_length} tokens: {removed_text}'     )

     _lowercase: Optional[Any]						     =    self.text_encoder(text_input_ids.to(snake_case_     )     )
     _lowercase: int						     =    text_encoder_output.text_embeds

     _lowercase: List[str]						     =    prompt_embeds.repeat_interleave(snake_case_						,					dim=0     )
     # in Shap-E it normalize the prompt_embeds and then later rescale it
     _lowercase: Dict						     =    prompt_embeds / torch.linalg.norm(snake_case_						,					dim=-1						,					keepdim=snake_case_     )

     if do_classifier_free_guidance:
       _lowercase: Optional[int]						     =    torch.zeros_like(snake_case_     )

       # 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
       _lowercase: List[Any]						     =    torch.cat([negative_prompt_embeds, prompt_embeds]     )

     # Rescale the features to have unit variance
     _lowercase: Dict						     =    math.sqrt(prompt_embeds.shape[1]     ) * prompt_embeds

     return prompt_embeds






   @torch.no_grad()
   @replace_example_docstring(snake_case_     )
   def __call__(	self   :       str						,					UpperCamelCase_   :       Dict						,					UpperCamelCase_   :       Union[str, Any] = 1						,					UpperCamelCase_   :       Optional[Any] = 25						,					UpperCamelCase_   :       int = None						,					UpperCamelCase_   :       Union[str, Any] = None						,					UpperCamelCase_   :       Union[str, Any] = 4.0						,					UpperCamelCase_   :       int = 64						,					UpperCamelCase_   :       Dict = "pil"						,					UpperCamelCase_   :       Dict = True						,					)->			Dict:

     if isinstance(snake_case_						,					snake_case_     ):
       _lowercase: int						     =    1
     elif isinstance(snake_case_						,					snake_case_     ):
       _lowercase: List[str]						     =    len(snake_case_     )
     else:
       raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(snake_case_     )}'     )

     _lowercase: Optional[int]						     =    self._execution_device

     _lowercase: Tuple						     =    batch_size * num_images_per_prompt

     _lowercase: Optional[int]						     =    guidance_scale > 1.0
     _lowercase: Tuple						     =    self._encode_prompt(snake_case_						,					snake_case_						,					snake_case_						,					snake_case_     )

     # prior

     self.scheduler.set_timesteps(snake_case_						,					device=snake_case_     )
     _lowercase: Any						     =    self.scheduler.timesteps

     _lowercase: Union[str, Any]						     =    self.prior.config.num_embeddings
     _lowercase: List[Any]						     =    self.prior.config.embedding_dim

     _lowercase: Any						     =    self.prepare_latents(
         (batch_size, num_embeddings * embedding_dim)						,					prompt_embeds.dtype						,					snake_case_						,					snake_case_						,					snake_case_						,					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
     _lowercase: List[str]						     =    latents.reshape(latents.shape[0]						,					snake_case_						,					snake_case_     )

     for i, t in enumerate(self.progress_bar(snake_case_     )     ):
       # expand the latents if we are doing classifier free guidance
       _lowercase: Optional[Any]						     =    torch.cat([latents] * 2     ) if do_classifier_free_guidance else latents
       _lowercase: Optional[int]						     =    self.scheduler.scale_model_input(snake_case_						,					snake_case_     )

       _lowercase: Optional[Any]						     =    self.prior(
           snake_case_						,					timestep=snake_case_						,					proj_embedding=snake_case_						,					).predicted_image_embedding

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

       _lowercase: int						     =    self.scheduler.step(
           snake_case_						,					timestep=snake_case_						,					sample=snake_case_						,					).prev_sample

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

     _lowercase: List[str]						     =    []
     for i, latent in enumerate(snake_case_     ):
       _lowercase: Tuple						     =    self.renderer.decode(
           latent[None, :]						,					snake_case_						,					size=snake_case_						,					ray_batch_size=40_96						,					n_coarse_samples=64						,					n_fine_samples=1_28						,					)
       images.append(snake_case_     )

     _lowercase: List[str]						     =    torch.stack(snake_case_     )

     if output_type not in ["np", "pil"]:
       raise ValueError(f'Only the output types `pil` and `np` are supported not output_type={output_type}'     )

     _lowercase: List[str]						     =    images.cpu().numpy()

     if output_type == "pil":
       _lowercase: Dict						     =    [self.numpy_to_pil(snake_case_     ) 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=snake_case_     )






from cva import destroyAllWindows, imread, imshow, waitKey


def 		_lowerCamelCase				(					UpperCamelCase					,     UpperCamelCase							)			->		List[str]:





  """simple docstring"""





  _lowercase     ,					_lowercase: Tuple						     =    img.shape[0], img.shape[1]

  def to_grayscale(UpperCamelCase					,     UpperCamelCase					,     UpperCamelCase							):
    return 0.2_126 * red + 0.587 * green + 0.114 * blue

  def normalize(UpperCamelCase							):
    return min(UpperCamelCase					,     255							)

  for i in range(UpperCamelCase							):
    for j in range(UpperCamelCase							):
      _lowercase: Any						     =    int(to_grayscale(*img[i][j]							)							)
      _lowercase: str						     =    [
          normalize(UpperCamelCase							),
          normalize(greyscale + factor							),
          normalize(greyscale + 2 * factor							),
      ]

  return img


if __name__ == "__main__":
   # read original image
   UpperCAmelCase__						:       Optional[Any]							=    {
       percentage: imread('image_data/lena.jpg', 1) for percentage in (10, 20, 30, 40)
   }

   for percentage, img in images.items():
      make_sepia(img, percentage)

   for percentage, img in images.items():
      imshow(f'''Original image with sepia (factor: {percentage})''', img)

   waitKey(0)
   destroyAllWindows()
