






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

from ...utils import logging


__UpperCamelCase   :   Tuple      =    logging.get_logger(__name__)





def 					snake_case	(  lowerCamelCase					,	lowerCamelCase       ):




	'''simple docstring'''







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




class 							__UpperCamelCase     (  _lowerCAmelCase ):
	__snake_case						:Optional[Any] =							CLIPConfig

	__snake_case						:Optional[Any] =							['CLIPEncoderLayer']







	def __init__(	self   :				Optional[int]							,					_lowerCAmelCase   :				int      )		->			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   :				List[str]							,					_lowerCAmelCase   :				Optional[int]							,					_lowerCAmelCase   :				Dict      )		->			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   :				List[str]							,					_lowerCAmelCase   :				Optional[int]							,					_lowerCAmelCase   :				List[Any]      )		->			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




from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import BaseOutput, is_torch_available, is_transformers_available





@dataclass
class 					__lowerCAmelCase	(   SCREAMING_SNAKE_CASE				):
  _a		     =    42
  _a		     =    42


if is_transformers_available() and is_torch_available():
  from .pipeline_semantic_stable_diffusion import SemanticStableDiffusionPipeline


