


import types
from typing import List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer
from transformers.models.clip.modeling_clip import CLIPTextModelOutput

from diffusers.models import PriorTransformer
from diffusers.pipelines import DiffusionPipeline, StableDiffusionImageVariationPipeline
from diffusers.schedulers import UnCLIPScheduler
from diffusers.utils import logging, randn_tensor


snake_case__     							= logging.get_logger(__name__)  # pylint: disable=invalid-name
def  __SCREAMING_SNAKE_CASE       (				self  :str      ,						lowercase__  :Union[str, Any]      ,						lowercase__  :List[str]      ,						lowercase__  :List[Any]      ,						lowercase__  :Dict				)       ->  int:
						__magic_name__				:							Tuple				=      image.to(device=lowercase__				)
						__magic_name__				:							str				=      image  # take image as image_embeddings
						__magic_name__				:							Union[str, Any]				=      image_embeddings.unsqueeze(1				)

						# duplicate image embeddings for each generation per prompt, using mps friendly method
						__magic_name__		, __magic_name__		, __magic_name__				:							Tuple				=      image_embeddings.shape
						__magic_name__				:							Union[str, Any]				=      image_embeddings.repeat(1      ,						lowercase__      ,						1				)
						__magic_name__				:							str				=      image_embeddings.view(bs_embed * num_images_per_prompt      ,						lowercase__      ,						-1				)

						if do_classifier_free_guidance:
												__magic_name__				:							Optional[int]				=      torch.zeros_like(lowercase__				)

												# 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
												__magic_name__				:							int				=      torch.cat([uncond_embeddings, image_embeddings]				)

						return image_embeddings



class     snake_case__  (      _A  ):
				def __init__(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase = None     ,      ):




										"""simple docstring"""




										super().__init__()

										__magic_name__				:							Dict				=      {'image_encoder': None} if decoder_pipe_kwargs is None else decoder_pipe_kwargs

										__magic_name__				:							Optional[int]				=      decoder_pipe_kwargs.get('torch_dtype'     ,      _UpperCAmelCase      ) or prior.dtype

										__magic_name__				:							Optional[Any]				=      StableDiffusionImageVariationPipeline.from_pretrained(
										    'lambdalabs/sd-image-variations-diffusers'     ,      **_UpperCAmelCase      )

										# replace `_encode_image` method
										__magic_name__				:							Optional[int]				=      types.MethodType(_encode_image     ,      self.decoder_pipe      )

										self.register_modules(
										    prior=_UpperCAmelCase     ,      tokenizer=_UpperCAmelCase     ,      text_encoder=_UpperCAmelCase     ,      prior_scheduler=_UpperCAmelCase     ,      )
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase = None     ,      _UpperCAmelCase = None     ,      ):




										"""simple docstring"""




										if text_model_output is None:
																__magic_name__				:							List[str]				=      len(_UpperCAmelCase      ) if isinstance(_UpperCAmelCase     ,      _UpperCAmelCase      ) else 1
																# get prompt text embeddings
																__magic_name__				:							Tuple				=      self.tokenizer(
																    _UpperCAmelCase     ,      padding='max_length'     ,      max_length=self.tokenizer.model_max_length     ,      return_tensors='pt'     ,      )
																__magic_name__				:							int				=      text_inputs.input_ids
																__magic_name__				:							Any				=      text_inputs.attention_mask.bool().to(_UpperCAmelCase      )

																if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
																						__magic_name__				:							int				=      self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]      )
																						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}"      )
																						__magic_name__				:							Any				=      text_input_ids[:, : self.tokenizer.model_max_length]

																__magic_name__				:							Optional[Any]				=      self.text_encoder(text_input_ids.to(_UpperCAmelCase      )      )

																__magic_name__				:							Tuple				=      text_encoder_output.text_embeds
																__magic_name__				:							str				=      text_encoder_output.last_hidden_state

										else:
																__magic_name__				:							Optional[int]				=      text_model_output[0].shape[0]
																__magic_name__		, __magic_name__				:							List[Any]				=      text_model_output[0], text_model_output[1]
																__magic_name__				:							Any				=      text_attention_mask

										__magic_name__				:							List[str]				=      text_embeddings.repeat_interleave(_UpperCAmelCase     ,      dim=0      )
										__magic_name__				:							Union[str, Any]				=      text_encoder_hidden_states.repeat_interleave(_UpperCAmelCase     ,      dim=0      )
										__magic_name__				:							Dict				=      text_mask.repeat_interleave(_UpperCAmelCase     ,      dim=0      )

										if do_classifier_free_guidance:
																__magic_name__				:							List[str]				=      [''] * batch_size

																__magic_name__				:							Optional[int]				=      self.tokenizer(
																    _UpperCAmelCase     ,      padding='max_length'     ,      max_length=self.tokenizer.model_max_length     ,      truncation=_UpperCAmelCase     ,      return_tensors='pt'     ,      )
																__magic_name__				:							Optional[Any]				=      uncond_input.attention_mask.bool().to(_UpperCAmelCase      )
																__magic_name__				:							Union[str, Any]				=      self.text_encoder(uncond_input.input_ids.to(_UpperCAmelCase      )      )

																__magic_name__				:							Dict				=      uncond_embeddings_text_encoder_output.text_embeds
																__magic_name__				:							Union[str, Any]				=      uncond_embeddings_text_encoder_output.last_hidden_state

																# duplicate unconditional embeddings for each generation per prompt, using mps friendly method

																__magic_name__				:							str				=      uncond_embeddings.shape[1]
																__magic_name__				:							List[Any]				=      uncond_embeddings.repeat(1     ,      _UpperCAmelCase      )
																__magic_name__				:							Optional[int]				=      uncond_embeddings.view(batch_size * num_images_per_prompt     ,      _UpperCAmelCase      )

																__magic_name__				:							str				=      uncond_text_encoder_hidden_states.shape[1]
																__magic_name__				:							Tuple				=      uncond_text_encoder_hidden_states.repeat(1     ,      _UpperCAmelCase     ,      1      )
																__magic_name__				:							Dict				=      uncond_text_encoder_hidden_states.view(
																    batch_size * num_images_per_prompt     ,      _UpperCAmelCase     ,      -1      )
																__magic_name__				:							List[str]				=      uncond_text_mask.repeat_interleave(_UpperCAmelCase     ,      dim=0      )

																# done duplicates

																# 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
																__magic_name__				:							Dict				=      torch.cat([uncond_embeddings, text_embeddings]      )
																__magic_name__				:							Optional[int]				=      torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]      )

																__magic_name__				:							Tuple				=      torch.cat([uncond_text_mask, text_mask]      )

										return text_embeddings, text_encoder_hidden_states, text_mask
				@property
				def  UpperCamelCase_						(  self      ):




										"""simple docstring"""




										if self.device != torch.device('meta'      ) or not hasattr(self.prior     ,      '_hf_hook'      ):
																return self.device
										for module in self.prior.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     ,      _UpperCAmelCase     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										if latents is None:
																__magic_name__				:							Optional[int]				=      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}"      )
																__magic_name__				:							str				=      latents.to(_UpperCAmelCase      )

										__magic_name__				:							Dict				=      latents * scheduler.init_noise_sigma
										return latents
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase = None      ):




										"""simple docstring"""




										self.decoder_pipe.to(_UpperCAmelCase      )
										super().to(_UpperCAmelCase      )





				@torch.no_grad()
				def __call__(  self     ,      _UpperCAmelCase = None     ,      _UpperCAmelCase = None     ,      _UpperCAmelCase = None     ,      _UpperCAmelCase = 1     ,      _UpperCAmelCase = 25     ,      _UpperCAmelCase = None     ,      _UpperCAmelCase = None     ,      _UpperCAmelCase = None     ,      _UpperCAmelCase = None     ,      _UpperCAmelCase = 4.0     ,      _UpperCAmelCase = 8.0     ,      _UpperCAmelCase = 50     ,      _UpperCAmelCase = 1     ,      _UpperCAmelCase = 0.0     ,      _UpperCAmelCase = "pil"     ,      _UpperCAmelCase = True     ,      ):




										"""simple docstring"""




										if prompt is not None:
																if isinstance(_UpperCAmelCase     ,      _UpperCAmelCase      ):
																						__magic_name__				:							Any				=      1
																elif isinstance(_UpperCAmelCase     ,      _UpperCAmelCase      ):
																						__magic_name__				:							Tuple				=      len(_UpperCAmelCase      )
																else:
																						raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(_UpperCAmelCase      )}"      )
										else:
																__magic_name__				:							Optional[int]				=      text_model_output[0].shape[0]

										__magic_name__				:							Tuple				=      self._execution_device

										__magic_name__				:							List[Any]				=      batch_size * num_images_per_prompt

										__magic_name__				:							List[Any]				=      prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0

										__magic_name__		, __magic_name__		, __magic_name__				:							List[Any]				=      self._encode_prompt(
										    _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase      )

										# prior

										self.prior_scheduler.set_timesteps(_UpperCAmelCase     ,      device=_UpperCAmelCase      )
										__magic_name__				:							int				=      self.prior_scheduler.timesteps

										__magic_name__				:							Optional[Any]				=      self.prior.config.embedding_dim

										__magic_name__				:							int				=      self.prepare_latents(
										    (batch_size, embedding_dim)     ,      text_embeddings.dtype     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      _UpperCAmelCase     ,      self.prior_scheduler     ,      )

										for i, t in enumerate(self.progress_bar(_UpperCAmelCase      )      ):
																# expand the latents if we are doing classifier free guidance
																__magic_name__				:							List[str]				=      torch.cat([prior_latents] * 2      ) if do_classifier_free_guidance else prior_latents

																__magic_name__				:							Tuple				=      self.prior(
																    _UpperCAmelCase     ,      timestep=_UpperCAmelCase     ,      proj_embedding=_UpperCAmelCase     ,      encoder_hidden_states=_UpperCAmelCase     ,      attention_mask=_UpperCAmelCase     ,      ).predicted_image_embedding

																if do_classifier_free_guidance:
																						__magic_name__		, __magic_name__				:							List[str]				=      predicted_image_embedding.chunk(2      )
																						__magic_name__				:							str				=      predicted_image_embedding_uncond + prior_guidance_scale * (
																						    predicted_image_embedding_text - predicted_image_embedding_uncond
																						)

																if i + 1 == prior_timesteps_tensor.shape[0]:
																						__magic_name__				:							Optional[Any]				=      None
																else:
																						__magic_name__				:							str				=      prior_timesteps_tensor[i + 1]

																__magic_name__				:							List[str]				=      self.prior_scheduler.step(
																    _UpperCAmelCase     ,      timestep=_UpperCAmelCase     ,      sample=_UpperCAmelCase     ,      generator=_UpperCAmelCase     ,      prev_timestep=_UpperCAmelCase     ,      ).prev_sample

										__magic_name__				:							List[str]				=      self.prior.post_process_latents(_UpperCAmelCase      )

										__magic_name__				:							Optional[int]				=      prior_latents

										__magic_name__				:							Dict				=      self.decoder_pipe(
										    image=_UpperCAmelCase     ,      height=_UpperCAmelCase     ,      width=_UpperCAmelCase     ,      num_inference_steps=_UpperCAmelCase     ,      guidance_scale=_UpperCAmelCase     ,      generator=_UpperCAmelCase     ,      output_type=_UpperCAmelCase     ,      return_dict=_UpperCAmelCase     ,      num_images_per_prompt=_UpperCAmelCase     ,      eta=_UpperCAmelCase     ,      )
										return output






import numpy as np
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


snake_case__     							= logging.get_logger(__name__)
def  __SCREAMING_SNAKE_CASE       (				lowercase__  :Optional[Any]      ,						lowercase__  :List[str]				)       ->  Tuple:
						__magic_name__				:							List[str]				=      nn.functional.normalize(lowercase__				)
						__magic_name__				:							Union[str, Any]				=      nn.functional.normalize(lowercase__				)
						return torch.mm(lowercase__      ,						normalized_text_embeds.t()				)



class     snake_case__  (      _A  ):
				__lowerCAmelCase		=      CLIPConfig

				__lowerCAmelCase		=      ['''CLIPEncoderLayer''']
				def __init__(  self     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										super().__init__(_UpperCAmelCase      )

										__magic_name__				:							List[Any]				=      CLIPVisionModel(config.vision_config      )
										__magic_name__				:							Tuple				=      nn.Linear(config.vision_config.hidden_size     ,      config.projection_dim     ,      bias=_UpperCAmelCase      )

										__magic_name__				:							str				=      nn.Parameter(torch.ones(17     ,      config.projection_dim      )     ,      requires_grad=_UpperCAmelCase      )
										__magic_name__				:							Optional[Any]				=      nn.Parameter(torch.ones(3     ,      config.projection_dim      )     ,      requires_grad=_UpperCAmelCase      )

										__magic_name__				:							Optional[Any]				=      nn.Parameter(torch.ones(17      )     ,      requires_grad=_UpperCAmelCase      )
										__magic_name__				:							str				=      nn.Parameter(torch.ones(3      )     ,      requires_grad=_UpperCAmelCase      )
				@torch.no_grad()
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										__magic_name__				:							Union[str, Any]				=      self.vision_model(_UpperCAmelCase      )[1]  # pooled_output
										__magic_name__				:							Any				=      self.visual_projection(_UpperCAmelCase      )

										# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
										__magic_name__				:							Union[str, Any]				=      cosine_distance(_UpperCAmelCase     ,      self.special_care_embeds      ).cpu().float().numpy()
										__magic_name__				:							int				=      cosine_distance(_UpperCAmelCase     ,      self.concept_embeds      ).cpu().float().numpy()

										__magic_name__				:							str				=      []
										__magic_name__				:							List[Any]				=      image_embeds.shape[0]
										for i in range(_UpperCAmelCase      ):
																__magic_name__				:							Optional[Any]				=      {'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
																__magic_name__				:							Optional[int]				=      0.0

																for concept_idx in range(len(special_cos_dist[0]      )      ):
																						__magic_name__				:							Any				=      special_cos_dist[i][concept_idx]
																						__magic_name__				:							Tuple				=      self.special_care_embeds_weights[concept_idx].item()
																						__magic_name__				:							Dict				=      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]}      )
																												__magic_name__				:							str				=      0.01

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

																result.append(_UpperCAmelCase      )

										__magic_name__				:							Union[str, Any]				=      [len(res['bad_concepts']      ) > 0 for res in result]

										for idx, has_nsfw_concept in enumerate(_UpperCAmelCase      ):
																if has_nsfw_concept:
																						if torch.is_tensor(_UpperCAmelCase      ) or torch.is_tensor(images[0]      ):
																												__magic_name__				:							Union[str, Any]				=      torch.zeros_like(images[idx]      )  # black image
																						else:
																												__magic_name__				:							Optional[int]				=      np.zeros(images[idx].shape      )  # black image

										if any(_UpperCAmelCase      ):
																logger.warning(
																    'Potential NSFW content was detected in one or more images. A black image will be returned instead.'
																    ' Try again with a different prompt and/or seed.'      )

										return images, has_nsfw_concepts





				@torch.no_grad()
				def  UpperCamelCase_						(  self     ,      _UpperCAmelCase     ,      _UpperCAmelCase      ):




										"""simple docstring"""




										__magic_name__				:							List[str]				=      self.vision_model(_UpperCAmelCase      )[1]  # pooled_output
										__magic_name__				:							List[str]				=      self.visual_projection(_UpperCAmelCase      )

										__magic_name__				:							Union[str, Any]				=      cosine_distance(_UpperCAmelCase     ,      self.special_care_embeds      )
										__magic_name__				:							Optional[int]				=      cosine_distance(_UpperCAmelCase     ,      self.concept_embeds      )

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

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

										__magic_name__				:							Optional[int]				=      (cos_dist - self.concept_embeds_weights) + special_adjustment
										# concept_scores = concept_scores.round(decimals=3)
										__magic_name__				:							Union[str, Any]				=      torch.any(concept_scores > 0     ,      dim=1      )

										__magic_name__				:							Dict				=      0.0  # black image

										return images, has_nsfw_concepts


