

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

from ...utils import logging


lowerCamelCase__				:  Optional[int]													=  logging.get_logger(__name__)
def       UpperCamelCase					(			_lowerCAmelCase     :						List[str],  _lowerCAmelCase     :						str )				->			Dict:
	_UpperCAmelCase    :							int									=					nn.functional.normalize(snake_case__ )
	_UpperCAmelCase    :							Union[str, Any]									=					nn.functional.normalize(snake_case__ )
	return torch.mm(snake_case__,  normalized_text_embeds.t() )






class     _UpperCAmelCase			(		a__):
			__a :       int									=							CLIPConfig

			__a :       Union[str, Any]									=							["CLIPEncoderLayer"]
			def __init__(		self      ,		_A     )    ->    List[str]:






				'''simple docstring'''







				super().__init__(SCREAMING_SNAKE_CASE_     )

				_UpperCAmelCase    :							int									=					CLIPVisionModel(config.vision_config     )
				_UpperCAmelCase    :							int									=					nn.Linear(config.vision_config.hidden_size      ,		config.projection_dim      ,		bias=SCREAMING_SNAKE_CASE_     )

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

				_UpperCAmelCase    :							Dict									=					nn.Parameter(torch.ones(17     )      ,		requires_grad=SCREAMING_SNAKE_CASE_     )
				_UpperCAmelCase    :							Optional[Any]									=					nn.Parameter(torch.ones(3     )      ,		requires_grad=SCREAMING_SNAKE_CASE_     )
			@torch.no_grad()
			def 							__snake_case (		self      ,		_A      ,		_A     )    ->    Union[str, Any]:






				'''simple docstring'''







				_UpperCAmelCase    :							Optional[int]									=					self.vision_model(SCREAMING_SNAKE_CASE_     )[1]  # pooled_output
				_UpperCAmelCase    :							int									=					self.visual_projection(SCREAMING_SNAKE_CASE_     )

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

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

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

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

					result.append(SCREAMING_SNAKE_CASE_     )

				_UpperCAmelCase    :							int									=					[len(res["""bad_concepts"""]     ) > 0 for res in result]

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

				if any(SCREAMING_SNAKE_CASE_     ):
					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 							__snake_case (		self      ,		_A      ,		_A     )    ->    Optional[int]:






				'''simple docstring'''







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

				_UpperCAmelCase    :							str									=					cosine_distance(SCREAMING_SNAKE_CASE_      ,		self.special_care_embeds     )
				_UpperCAmelCase    :							Any									=					cosine_distance(SCREAMING_SNAKE_CASE_      ,		self.concept_embeds     )

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

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

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

				_UpperCAmelCase    :							Any									=					0.0  # black image

				return images, has_nsfw_concepts








"""simple docstring"""






def       UpperCamelCase					(			_lowerCAmelCase     :						float,  _lowerCAmelCase     :						float )				->			float:
	_UpperCAmelCase    :							List[Any]									=					float()
	try:
		_UpperCAmelCase    :							Optional[Any]									=					mass * acceleration
	except Exception:
		return -0.0
	return force


if __name__ == "__main__":
						import doctest

						# run doctest
						doctest.testmod()

						# demo
						lowerCamelCase__				:  Any													=  12.5
						lowerCamelCase__				:  Union[str, Any]													=  10
						lowerCamelCase__				:  Optional[Any]													=  newtons_second_law_of_motion(mass, acceleration)
						print('''The force is ''', force, '''N''')





