

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

from ...utils import logging


lowerCAmelCase							:  List[Any]            =						logging.get_logger(__name__)







def       A_				(   _UpperCAmelCase    ,     _UpperCAmelCase   ):
						SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	nn.functional.normalize(_lowerCamelCase   )
						SCREAMING_SNAKE_CASE_:			Tuple  		=	nn.functional.normalize(_lowerCamelCase   )
						return torch.mm(_lowerCamelCase    ,     normalized_text_embeds.t()   )



class   __lowercase    (			__lowercase     ):




			"""simple docstring"""







			_UpperCAmelCase       :							Optional[int]      							=					CLIPConfig

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



			def __init__(			self  :					Dict       ,						lowerCAmelCase__  :					CLIPConfig):
									super().__init__(lowerCAmelCase__)

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

									SCREAMING_SNAKE_CASE_:			str  		=	nn.Parameter(torch.ones(17       ,						config.projection_dim)       ,						requires_grad=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Dict  		=	nn.Parameter(torch.ones(3       ,						config.projection_dim)       ,						requires_grad=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	nn.Parameter(torch.ones(17)       ,						requires_grad=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Tuple  		=	nn.Parameter(torch.ones(3)       ,						requires_grad=lowerCAmelCase__)



			@torch.no_grad()
			def 	_SCREAMING_SNAKE_CASE      (			self  :					str       ,						lowerCAmelCase__  :					Union[str, Any]       ,						lowerCAmelCase__  :					Optional[int]):
									SCREAMING_SNAKE_CASE_:			Dict  		=	self.vision_model(lowerCAmelCase__)[1]  # pooled_output
									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	self.visual_projection(lowerCAmelCase__)

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

									SCREAMING_SNAKE_CASE_:			Tuple  		=	[]
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	image_embeds.shape[0]
									for i in range(lowerCAmelCase__):
															SCREAMING_SNAKE_CASE_:			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
															SCREAMING_SNAKE_CASE_:			Tuple  		=	0.0

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

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

															result.append(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			Any  		=	[len(res["bad_concepts"]) > 0 for res in result]

									return images, has_nsfw_concepts




			@torch.no_grad()
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]       ,						lowerCAmelCase__  :					torch.FloatTensor       ,						lowerCAmelCase__  :					torch.FloatTensor):
									SCREAMING_SNAKE_CASE_:			Any  		=	self.vision_model(lowerCAmelCase__)[1]  # pooled_output
									SCREAMING_SNAKE_CASE_:			int  		=	self.visual_projection(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			Dict  		=	cosine_distance(lowerCAmelCase__       ,						self.special_care_embeds)
									SCREAMING_SNAKE_CASE_:			Any  		=	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
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	0.0

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

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

									return images, has_nsfw_concepts








import os

# Precomputes a list of the 100 first triangular numbers
lowerCAmelCase							:  Optional[int]            =						[int(0.5 * n * (n + 1)) for n in range(1, 101)]







def       A_				(   ):
						SCREAMING_SNAKE_CASE_:			List[str]  		=	os.path.dirname(os.path.realpath(_UpperCAmelCase   )   )
						SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	os.path.join(_UpperCAmelCase    ,     "words.txt"   )

						SCREAMING_SNAKE_CASE_:			Dict  		=	""
						with open(_UpperCAmelCase   ) as f:
												SCREAMING_SNAKE_CASE_:			int  		=	f.readline()

						SCREAMING_SNAKE_CASE_:			Optional[int]  		=	[word.strip("\""   ) for word in words.strip("\r\n"   ).split(","   )]
						SCREAMING_SNAKE_CASE_:			List[Any]  		=	[
						    word
						    for word in [sum(ord(_UpperCAmelCase   ) - 64 for x in word   ) for word in words]
						    if word in TRIANGULAR_NUMBERS
						]
						return len(_UpperCAmelCase   )


if __name__ == "__main__":
						print(solution())






