
"""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__          =	'\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			(					lowercase      ):
      UpperCamelCase							:   Dict           =     4_2





class 				a			(					lowercase      ):



      def __init__(   self     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	):
          super().__init__()

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



      def  __snake_case							(   self     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_      ):






          if latents is None:
              UpperCAmelCase__	:      Union[str, 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}'''      )
              UpperCAmelCase__	:      Optional[Any]     							=					latents.to(UpperCamelCase_      )

          UpperCAmelCase__	:      Tuple     							=					latents * scheduler.init_noise_sigma
          return latents



      def  __snake_case							(   self     ,	UpperCamelCase_=0      ):






          if is_accelerate_available():
              from accelerate import cpu_offload
          else:
              raise ImportError('Please install accelerate via `pip install accelerate`'      )

          UpperCAmelCase__	:      Union[str, Any]     							=					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  __snake_case							(   self      ):






          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  __snake_case							(   self     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	):






          if isinstance(UpperCamelCase_     ,	UpperCamelCase_      ) and isinstance(image[0]     ,	torch.Tensor      ):
              UpperCAmelCase__	:      Optional[Any]     							=					torch.cat(UpperCamelCase_     ,	axis=0      ) if image[0].ndim == 4 else torch.stack(UpperCamelCase_     ,	axis=0      )

          if not isinstance(UpperCamelCase_     ,	torch.Tensor      ):
              UpperCAmelCase__	:      Tuple     							=					self.image_processor(UpperCamelCase_     ,	return_tensors='pt'      ).pixel_values[0].unsqueeze(0      )

          UpperCAmelCase__	:      Union[str, Any]     							=					image.to(dtype=self.image_encoder.dtype     ,	device=UpperCamelCase_      )

          UpperCAmelCase__	:      str     							=					self.image_encoder(UpperCamelCase_      )['last_hidden_state']
          UpperCAmelCase__	:      List[str]     							=					image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

          UpperCAmelCase__	:      Union[str, Any]     							=					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__	:      List[Any]     							=					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     ,	):






          if isinstance(UpperCamelCase_     ,	PIL.Image.Image      ):
              UpperCAmelCase__	:      List[str]     							=					1
          elif isinstance(UpperCamelCase_     ,	torch.Tensor      ):
              UpperCAmelCase__	:      Any     							=					image.shape[0]
          elif isinstance(UpperCamelCase_     ,	UpperCamelCase_      ) and isinstance(image[0]     ,	(torch.Tensor, PIL.Image.Image)      ):
              UpperCAmelCase__	:      Dict     							=					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__	:      Optional[int]     							=					self._execution_device

          UpperCAmelCase__	:      Tuple     							=					batch_size * num_images_per_prompt

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

          # prior

          self.scheduler.set_timesteps(UpperCamelCase_     ,	device=UpperCamelCase_      )
          UpperCAmelCase__	:      Tuple     							=					self.scheduler.timesteps

          UpperCAmelCase__	:      Dict     							=					self.prior.config.num_embeddings
          UpperCAmelCase__	:      Optional[int]     							=					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__	:      Optional[int]     							=					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__	:      Dict     							=					torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents
              UpperCAmelCase__	:      Union[str, Any]     							=					self.scheduler.scale_model_input(UpperCamelCase_     ,	UpperCamelCase_      )

              UpperCAmelCase__	:      Optional[Any]     							=					self.prior(
                  UpperCamelCase_     ,	timestep=UpperCamelCase_     ,	proj_embedding=UpperCamelCase_     ,	).predicted_image_embedding

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

              UpperCAmelCase__	:      int     							=					self.scheduler.step(
                  UpperCamelCase_     ,	timestep=UpperCamelCase_     ,	sample=UpperCamelCase_     ,	).prev_sample

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

          UpperCAmelCase__	:      Optional[int]     							=					[]
          for i, latent in enumerate(UpperCamelCase_      ):
              print()
              UpperCAmelCase__	:      int     							=					self.renderer.decode(
                  latent[None, :]     ,	UpperCamelCase_     ,	size=UpperCamelCase_     ,	ray_batch_size=4_096     ,	n_coarse_samples=64     ,	n_fine_samples=128     ,	)

              images.append(UpperCamelCase_      )

          UpperCAmelCase__	:      List[str]     							=					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__	:      Union[str, Any]     							=					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 torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


lowercase_   							=  logging.get_logger(__name__)
def 	a (     A__      :  Optional[int] ,  A__      :  Union[str, Any]	)       -> int:





      """simple docstring"""



      _lowercase      			=nn.functional.normalize(A__	)
      _lowercase      			=nn.functional.normalize(A__	)
      return torch.mm(A__ ,  normalized_text_embeds.t()	)







class 					__lowerCAmelCase	(   SCREAMING_SNAKE_CASE				):
  _a		     =    CLIPConfig

  _a		     =    ["""CLIPEncoderLayer"""]




  def __init__(							self				,  lowerCAmelCase   )    ->					Union[str, Any]:
        '''simple docstring'''






        super().__init__(lowerCAmelCase   )

        _lowercase      			=CLIPVisionModel(config.vision_config   )
        _lowercase      			=nn.Linear(config.vision_config.hidden_size				,  config.projection_dim				,  bias=lowerCAmelCase   )

        _lowercase      			=nn.Parameter(torch.ones(17				,  config.projection_dim   )				,  requires_grad=lowerCAmelCase   )
        _lowercase      			=nn.Parameter(torch.ones(3				,  config.projection_dim   )				,  requires_grad=lowerCAmelCase   )

        _lowercase      			=nn.Parameter(torch.ones(17   )				,  requires_grad=lowerCAmelCase   )
        _lowercase      			=nn.Parameter(torch.ones(3   )				,  requires_grad=lowerCAmelCase   )




  @torch.no_grad()
  def     A__	(							self				,  lowerCAmelCase				,  lowerCAmelCase   )    ->					Optional[int]:
        '''simple docstring'''






        _lowercase      			=self.vision_model(lowerCAmelCase   )[1]  # pooled_output
        _lowercase      			=self.visual_projection(lowerCAmelCase   )

        # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
        _lowercase      			=cosine_distance(lowerCAmelCase				,  self.special_care_embeds   ).cpu().float().numpy()
        _lowercase      			=cosine_distance(lowerCAmelCase				,  self.concept_embeds   ).cpu().float().numpy()

        _lowercase      			=[]
        _lowercase      			=image_embeds.shape[0]
        for i in range(lowerCAmelCase   ):
              _lowercase      			={'special_scores': {}, 'special_care': [], 'concept_scores': {}, 'bad_concepts': []}

              # increase this value to create a stronger `nfsw` filter
              # at the cost of increasing the possibility of filtering benign images
              _lowercase      			=0.0

              for concept_idx in range(len(special_cos_dist[0]   )   ):
                    _lowercase      			=special_cos_dist[i][concept_idx]
                    _lowercase      			=self.special_care_embeds_weights[concept_idx].item()
                    _lowercase      			=round(concept_cos - concept_threshold + adjustment				,  3   )
                    if result_img["special_scores"][concept_idx] > 0:
                          result_img["special_care"].append({concept_idx, result_img['special_scores'][concept_idx]}   )
                          _lowercase      			=0.01

              for concept_idx in range(len(cos_dist[0]   )   ):
                    _lowercase      			=cos_dist[i][concept_idx]
                    _lowercase      			=self.concept_embeds_weights[concept_idx].item()
                    _lowercase      			=round(concept_cos - concept_threshold + adjustment				,  3   )
                    if result_img["concept_scores"][concept_idx] > 0:
                          result_img["bad_concepts"].append(lowerCAmelCase   )

              result.append(lowerCAmelCase   )

        _lowercase      			=[len(res['bad_concepts']   ) > 0 for res in result]

        return images, has_nsfw_concepts




  @torch.no_grad()
  def     A__	(							self				,  lowerCAmelCase				,  lowerCAmelCase   )    ->					Tuple:
        '''simple docstring'''






        _lowercase      			=self.vision_model(lowerCAmelCase   )[1]  # pooled_output
        _lowercase      			=self.visual_projection(lowerCAmelCase   )

        _lowercase      			=cosine_distance(lowerCAmelCase				,  self.special_care_embeds   )
        _lowercase      			=cosine_distance(lowerCAmelCase				,  self.concept_embeds   )

        # increase this value to create a stronger `nsfw` filter
        # at the cost of increasing the possibility of filtering benign images
        _lowercase      			=0.0

        _lowercase      			=special_cos_dist - self.special_care_embeds_weights + adjustment
        # special_scores = special_scores.round(decimals=3)
        _lowercase      			=torch.any(special_scores > 0				,  dim=1   )
        _lowercase      			=special_care * 0.01
        _lowercase      			=special_adjustment.unsqueeze(1   ).expand(-1				,  cos_dist.shape[1]   )

        _lowercase      			=(cos_dist - self.concept_embeds_weights) + special_adjustment
        # concept_scores = concept_scores.round(decimals=3)
        _lowercase      			=torch.any(concept_scores > 0				,  dim=1   )

        return images, has_nsfw_concepts


