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

from ...utils import logging


__lowerCamelCase :     List[str]          =  logging.get_logger(__name__)




def     _snake_case     (       lowerCAmelCase							:       str       ,			lowerCAmelCase							:       Optional[int]     ):
		"""simple docstring"""







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







class 		a__						( A__ ):
					A     	=							CLIPConfig

					A     	=							['CLIPEncoderLayer']

					def __init__(   self				:	Dict,_A				:	CLIPConfig   ):







							"""simple docstring"""






							super().__init__(_A   )

							SCREAMING_SNAKE_CASE_  :		Optional[Any]    				=   CLIPVisionModel(config.vision_config   )
							SCREAMING_SNAKE_CASE_  :		str    				=   nn.Linear(config.vision_config.hidden_size,config.projection_dim,bias=_A   )

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

							SCREAMING_SNAKE_CASE_  :		Dict    				=   nn.Parameter(torch.ones(17   ),requires_grad=_A   )
							SCREAMING_SNAKE_CASE_  :		Any    				=   nn.Parameter(torch.ones(3   ),requires_grad=_A   )

					@torch.no_grad()
					def     __UpperCamelCase       (   self				:	List[Any],_A				:	Tuple,_A				:	str   ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str    				=   self.vision_model(_A   )[1]  # pooled_output
							SCREAMING_SNAKE_CASE_  :		Tuple    				=   self.visual_projection(_A   )

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

							SCREAMING_SNAKE_CASE_  :		List[str]    				=   []
							SCREAMING_SNAKE_CASE_  :		List[Any]    				=   image_embeds.shape[0]
							for i in range(_A   ):
									SCREAMING_SNAKE_CASE_  :		List[str]    				=   {"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_  :		Any    				=   0.0

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

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

									result.append(_A   )

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

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

							if any(_A   ):
									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				:	int,_A				:	torch.FloatTensor,_A				:	torch.FloatTensor   ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[Any]    				=   self.vision_model(_A   )[1]  # pooled_output
							SCREAMING_SNAKE_CASE_  :		Any    				=   self.visual_projection(_A   )

							SCREAMING_SNAKE_CASE_  :		int    				=   cosine_distance(_A,self.special_care_embeds   )
							SCREAMING_SNAKE_CASE_  :		List[str]    				=   cosine_distance(_A,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_  :		Dict    				=   special_cos_dist - self.special_care_embeds_weights + adjustment
							# special_scores = special_scores.round(decimals=3)
							SCREAMING_SNAKE_CASE_  :		Tuple    				=   torch.any(special_scores > 0,dim=1   )
							SCREAMING_SNAKE_CASE_  :		Optional[Any]    				=   special_care * 0.01
							SCREAMING_SNAKE_CASE_  :		Tuple    				=   special_adjustment.unsqueeze(1   ).expand(-1,cos_dist.shape[1]   )

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

							SCREAMING_SNAKE_CASE_  :		List[Any]    				=   0.0  # black image

							return images, has_nsfw_concepts

import warnings

from ...utils import logging
from .image_processing_vit import ViTImageProcessor


__lowerCamelCase :     Tuple          =  logging.get_logger(__name__)






class 		a__						( A__ ):

					def __init__(   self				:	List[Any],*_A				:	Union[str, Any],**_A				:	List[Any]   ):







							"""simple docstring"""






							warnings.warn(
							    "The class ViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
							    " use ViTImageProcessor instead.",_A,)
							super().__init__(*_A,**_A   )
