






import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
						import torch


class 							__UpperCamelCase     (  _lowerCAmelCase ):
	__snake_case						:Dict =							'char'
	__snake_case						:List[Any] =							'bpe'
	__snake_case						:int =							'wp'

__UpperCamelCase   :   List[str]      =    (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)


class 							__UpperCamelCase     (  _lowerCAmelCase ):
	__snake_case						:int =							['image_processor', 'char_tokenizer']
	__snake_case						:Dict =							'ViTImageProcessor'
	__snake_case						:List[str] =							'MgpstrTokenizer'







	def __init__(	self   :				Optional[int]							,					_lowerCAmelCase   :				List[str]=None							,					_lowerCAmelCase   :				int=None							,					**_lowerCAmelCase   :				Dict      )		->			Dict:
		"""simple docstring"""







		__lowercase   							=	None
		if "feature_extractor" in kwargs:
			warnings.warn(
			    """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
			    """ instead."""							,					_lowerCAmelCase							,					)
			__lowercase   							=	kwargs.pop("""feature_extractor"""      )

		__lowercase   							=	image_processor if image_processor is not None else feature_extractor
		if image_processor is None:
			raise ValueError("""You need to specify an `image_processor`."""      )
		if tokenizer is None:
			raise ValueError("""You need to specify a `tokenizer`."""      )

		__lowercase   							=	tokenizer
		__lowercase   							=	AutoTokenizer.from_pretrained("""gpt2"""      )
		__lowercase   							=	AutoTokenizer.from_pretrained("""bert-base-uncased"""      )

		super().__init__(_lowerCAmelCase							,					_lowerCAmelCase      )







	def __call__(	self   :				str							,					_lowerCAmelCase   :				Optional[int]=None							,					_lowerCAmelCase   :				Optional[Any]=None							,					_lowerCAmelCase   :				List[str]=None							,					**_lowerCAmelCase   :				List[str]      )		->			Dict:
		"""simple docstring"""







		if images is None and text is None:
			raise ValueError("""You need to specify either an `images` or `text` input to process."""      )

		if images is not None:
			__lowercase   							=	self.image_processor(_lowerCAmelCase							,					return_tensors=_lowerCAmelCase							,					**_lowerCAmelCase      )
		if text is not None:
			__lowercase   							=	self.char_tokenizer(_lowerCAmelCase							,					return_tensors=_lowerCAmelCase							,					**_lowerCAmelCase      )

		if text is None:
			return inputs
		elif images is None:
			return encodings
		else:
			__lowercase   							=	encodings["""input_ids"""]
			return inputs







	def 			_a (	self   :				int							,					_lowerCAmelCase   :				int      )		->			List[Any]:
		"""simple docstring"""







		__lowercase							,    __lowercase							,    __lowercase   							=	sequences
		__lowercase   							=	char_preds.size(0      )

		__lowercase							,    __lowercase   							=	self._decode_helper(_lowerCAmelCase							,					"""char"""      )
		__lowercase							,    __lowercase   							=	self._decode_helper(_lowerCAmelCase							,					"""bpe"""      )
		__lowercase							,    __lowercase   							=	self._decode_helper(_lowerCAmelCase							,					"""wp"""      )

		__lowercase   							=	[]
		__lowercase   							=	[]
		for i in range(_lowerCAmelCase      ):
			__lowercase   							=	[char_scores[i], bpe_scores[i], wp_scores[i]]
			__lowercase   							=	[char_strs[i], bpe_strs[i], wp_strs[i]]
			__lowercase   							=	scores.index(max(_lowerCAmelCase      )      )
			final_strs.append(strs[max_score_index]      )
			final_scores.append(scores[max_score_index]      )

		__lowercase   							=	{}
		__lowercase   							=	final_strs
		__lowercase   							=	final_scores
		__lowercase   							=	char_strs
		__lowercase   							=	bpe_strs
		__lowercase   							=	wp_strs
		return out







	def 			_a (	self   :				str							,					_lowerCAmelCase   :				List[str]							,					_lowerCAmelCase   :				Union[str, Any]      )		->			Tuple:
		"""simple docstring"""







		if format == DecodeType.CHARACTER:
			__lowercase   							=	self.char_decode
			__lowercase   							=	1
			__lowercase   							=	"""[s]"""
		elif format == DecodeType.BPE:
			__lowercase   							=	self.bpe_decode
			__lowercase   							=	2
			__lowercase   							=	"""#"""
		elif format == DecodeType.WORDPIECE:
			__lowercase   							=	self.wp_decode
			__lowercase   							=	102
			__lowercase   							=	"""[SEP]"""
		else:
			raise ValueError(F'Format {format} is not supported.'      )

		__lowercase							,    __lowercase   							=	[], []
		__lowercase   							=	pred_logits.size(0      )
		__lowercase   							=	pred_logits.size(1      )
		__lowercase							,    __lowercase   							=	pred_logits.topk(1							,					dim=-1							,					largest=_lowerCAmelCase							,					sorted=_lowerCAmelCase      )
		__lowercase   							=	preds_index.view(-1							,					_lowerCAmelCase      )[:, 1:]
		__lowercase   							=	decoder(_lowerCAmelCase      )
		__lowercase							,    __lowercase   							=	torch.nn.functional.softmax(_lowerCAmelCase							,					dim=2      ).max(dim=2      )
		__lowercase   							=	preds_max_prob[:, 1:]

		for index in range(_lowerCAmelCase      ):
			__lowercase   							=	preds_str[index].find(_lowerCAmelCase      )
			__lowercase   							=	preds_str[index][:pred_eos]
			__lowercase   							=	preds_index[index].cpu().tolist()
			__lowercase   							=	pred_index.index(_lowerCAmelCase      ) if eos_token in pred_index else -1
			__lowercase   							=	preds_max_prob[index][: pred_eos_index + 1]
			__lowercase   							=	pred_max_prob.cumprod(dim=0      )[-1] if pred_max_prob.nelement() != 0 else 0.0
			dec_strs.append(_lowerCAmelCase      )
			conf_scores.append(_lowerCAmelCase      )

		return dec_strs, conf_scores







	def 			_a (	self   :				Optional[int]							,					_lowerCAmelCase   :				Any      )		->			str:
		"""simple docstring"""







		__lowercase   							=	[seq.replace(""" """							,					""""""      ) for seq in self.char_tokenizer.batch_decode(_lowerCAmelCase      )]
		return decode_strs







	def 			_a (	self   :				Union[str, Any]							,					_lowerCAmelCase   :				List[Any]      )		->			int:
		"""simple docstring"""







		return self.bpe_tokenizer.batch_decode(_lowerCAmelCase      )







	def 			_a (	self   :				str							,					_lowerCAmelCase   :				int      )		->			Optional[Any]:
		"""simple docstring"""







		__lowercase   							=	[seq.replace(""" """							,					""""""      ) for seq in self.wp_tokenizer.batch_decode(_lowerCAmelCase      )]
		return decode_strs






'''simple docstring'''



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

from ...utils import logging


lowerCAmelCase_  :							int             =    logging.get_logger(__name__)
def        UpperCAmelCase (    A	:					List[Any]       ,		A	:					Optional[int]					):
							SCREAMING_SNAKE_CASE       :   Any         =      nn.functional.normalize(A					)
							SCREAMING_SNAKE_CASE       :   List[str]         =      nn.functional.normalize(A					)
							return torch.mm(A       ,		normalized_text_embeds.t()					)






class 						lowerCamelCase_				(       snake_case_      ):
						_lowerCAmelCase  : Optional[Any]						  =					CLIPConfig

						_lowerCAmelCase  : List[str]						  =					['CLIPEncoderLayer']







						def __init__(	self :   int					,     lowerCAmelCase__ :   CLIPConfig					):

													"""simple docstring"""
													super().__init__(lowerCAmelCase__					)

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

													SCREAMING_SNAKE_CASE       :   Any         =      nn.Parameter(torch.ones(17					,     config.projection_dim					)					,     requires_grad=lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   int         =      nn.Parameter(torch.ones(3					,     config.projection_dim					)					,     requires_grad=lowerCAmelCase__					)

													SCREAMING_SNAKE_CASE       :   Dict         =      nn.Parameter(torch.ones(17					)					,     requires_grad=lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   List[str]         =      nn.Parameter(torch.ones(3					)					,     requires_grad=lowerCAmelCase__					)







						@torch.no_grad()
						def        __lowercase     (	self :   List[str]					,     lowerCAmelCase__ :   List[str]					,     lowerCAmelCase__ :   Optional[Any]					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Any         =      self.vision_model(lowerCAmelCase__					)[1]  # pooled_output
													SCREAMING_SNAKE_CASE       :   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       :   Union[str, Any]         =      cosine_distance(lowerCAmelCase__					,     self.special_care_embeds					).cpu().float().numpy()
													SCREAMING_SNAKE_CASE       :   List[str]         =      cosine_distance(lowerCAmelCase__					,     self.concept_embeds					).cpu().float().numpy()

													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      []
													SCREAMING_SNAKE_CASE       :   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       :   int         =      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       :   Union[str, Any]         =      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       :   Tuple         =      0.01

																				for concept_idx in range(len(cos_dist[0]					)					):
																											SCREAMING_SNAKE_CASE       :   Optional[Any]         =      cos_dist[i][concept_idx]
																											SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      self.concept_embeds_weights[concept_idx].item()
																											SCREAMING_SNAKE_CASE       :   Dict         =      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       :   Dict         =      [len(res['''bad_concepts''']					) > 0 for res in result]

													return images, has_nsfw_concepts







						@torch.no_grad()
						def        __lowercase     (	self :   List[str]					,     lowerCAmelCase__ :   torch.FloatTensor					,     lowerCAmelCase__ :   torch.FloatTensor					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      self.vision_model(lowerCAmelCase__					)[1]  # pooled_output
													SCREAMING_SNAKE_CASE       :   List[Any]         =      self.visual_projection(lowerCAmelCase__					)

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

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

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

													return images, has_nsfw_concepts




