
'''simple docstring'''
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


lowercase__						       =      logging.get_logger(__name__)




def    _UpperCamelCase						(       SCREAMING_SNAKE_CASE__ ,       SCREAMING_SNAKE_CASE__			)  ->							int:


		'''simple docstring'''


		snake_case  :       int     			=						nn.functional.normalize(a_			)
		snake_case  :       Optional[int]     			=						nn.functional.normalize(a_			)
		return torch.mm(a_ ,       normalized_text_embeds.t()			)






class 	snake_case__       (      snake_case_					):







		"""simple docstring"""

		lowerCamelCase     							=						CLIPConfig

		lowerCamelCase     							=						["""CLIPEncoderLayer"""]



		def __init__(      self				:			Union[str, Any]  ,	UpperCamelCase__				:			str      )						->			List[str]:






				"""simple docstring"""







				super().__init__(UpperCamelCase__      )

				snake_case  :       Tuple     			=						CLIPVisionModel(config.vision_config      )
				snake_case  :       Union[str, Any]     			=						nn.Linear(config.vision_config.hidden_size  ,	config.projection_dim  ,	bias=UpperCamelCase__      )

				snake_case  :       Any     			=						nn.Parameter(torch.ones(17  ,	config.projection_dim      )  ,	requires_grad=UpperCamelCase__      )
				snake_case  :       Optional[Any]     			=						nn.Parameter(torch.ones(3  ,	config.projection_dim      )  ,	requires_grad=UpperCamelCase__      )

				snake_case  :       List[Any]     			=						nn.Parameter(torch.ones(17      )  ,	requires_grad=UpperCamelCase__      )
				snake_case  :       Dict     			=						nn.Parameter(torch.ones(3      )  ,	requires_grad=UpperCamelCase__      )



		@torch.no_grad()
		def       lowerCAmelCase				(      self				:			List[Any]  ,	UpperCamelCase__				:			Dict  ,	UpperCamelCase__				:			Tuple      )						->			Optional[int]:






				"""simple docstring"""







				snake_case  :       List[Any]     			=						self.vision_model(UpperCamelCase__      )[1]  # pooled_output
				snake_case  :       Tuple     			=						self.visual_projection(UpperCamelCase__      )

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

				snake_case  :       Optional[int]     			=						[]
				snake_case  :       Tuple     			=						image_embeds.shape[0]
				for i in range(UpperCamelCase__      ):
						snake_case  :       Union[str, 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
						snake_case  :       Dict     			=						0.0

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

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

						result.append(UpperCamelCase__      )

				snake_case  :       int     			=						[len(res['''bad_concepts''']      ) > 0 for res in result]

				return images, has_nsfw_concepts



		@torch.no_grad()
		def       lowerCAmelCase				(      self				:			Optional[Any]  ,	UpperCamelCase__				:			Any  ,	UpperCamelCase__				:			int      )						->			Dict:






				"""simple docstring"""







				snake_case  :       Dict     			=						self.vision_model(UpperCamelCase__      )[1]  # pooled_output
				snake_case  :       Optional[int]     			=						self.visual_projection(UpperCamelCase__      )

				snake_case  :       Optional[int]     			=						cosine_distance(UpperCamelCase__  ,	self.special_care_embeds      )
				snake_case  :       Dict     			=						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
				snake_case  :       List[str]     			=						0.0

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

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

				return images, has_nsfw_concepts










from typing import List, Optional, Tuple, Union

import torch

from ...schedulers import DDIMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput




class 					UpperCamelCase_ (     snake_case_							):



	'''simple docstring'''




	def __init__(			self			,     a			,     a   )			->       Optional[Any]:
								super().__init__()

								# make sure scheduler can always be converted to DDIM
								snake_case_           =				DDIMScheduler.from_config(scheduler.config   )

								self.register_modules(unet=a			,     scheduler=a   )






	@torch.no_grad()
	def __call__(			self			,     a = 1			,     a = None			,     a = 0.0			,     a = 50			,     a = None			,     a = "pil"			,     a = True			,     )			->       Union[ImagePipelineOutput, Tuple]:

								# Sample gaussian noise to begin loop
								if isinstance(self.unet.config.sample_size			,     a   ):
															snake_case_           =				(
															    batch_size,
															    self.unet.config.in_channels,
															    self.unet.config.sample_size,
															    self.unet.config.sample_size,
															)
								else:
															snake_case_           =				(batch_size, self.unet.config.in_channels, *self.unet.config.sample_size)

								if isinstance(a			,     a   ) and len(a   ) != batch_size:
															raise ValueError(
															    F'''You have passed a list of generators of length {len(a   )}, but requested an effective batch'''
															    F''' size of {batch_size}. Make sure the batch size matches the length of the generators.'''   )

								snake_case_           =				randn_tensor(a			,     generator=a			,     device=self.device			,     dtype=self.unet.dtype   )

								# set step values
								self.scheduler.set_timesteps(a   )

								for t in self.progress_bar(self.scheduler.timesteps   ):
															# 1. predict noise model_output
															snake_case_           =				self.unet(a			,     a   ).sample

															# 2. predict previous mean of image x_t-1 and add variance depending on eta
															# eta corresponds to η in paper and should be between [0, 1]
															# do x_t -> x_t-1
															snake_case_           =				self.scheduler.step(
															    a			,     a			,     a			,     eta=a			,     use_clipped_model_output=a			,     generator=a   ).prev_sample

								snake_case_           =				(image / 2 + 0.5).clamp(0			,     1   )
								snake_case_           =				image.cpu().permute(0			,     2			,     3			,     1   ).numpy()
								if output_type == "pil":
															snake_case_           =				self.numpy_to_pil(a   )

								if not return_dict:
															return (image,)

								return ImagePipelineOutput(images=a   )





