





"""simple docstring"""


import warnings
from typing import List, Optional, Union

from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType






class 							lowercase__			(   __SCREAMING_SNAKE_CASE	):

			"""simple docstring"""
			__lowerCAmelCase     :				int										=  ["""image_processor""", """tokenizer"""]
			__lowerCAmelCase     :				Dict										=  """FlavaImageProcessor"""
			__lowerCAmelCase     :				List[str]										=  ("""BertTokenizer""", """BertTokenizerFast""")







			def __init__(      self						,   _A=None						,   _A=None						,   **_A    ):






									'''simple docstring'''







									UpperCamelCase				:		Dict				   =			None
									if "feature_extractor" in kwargs:
															warnings.warn(
															    """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
															    """ instead."""						,   _A						,   )
															UpperCamelCase				:		Union[str, Any]				   =			kwargs.pop("""feature_extractor"""    )

									UpperCamelCase				:		int				   =			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`."""    )

									super().__init__(_A						,   _A    )
									UpperCamelCase				:		List[str]				   =			self.image_processor







			def __call__(      self						,   _A = None						,   _A = None						,   _A = True						,   _A = False						,   _A = False						,   _A = None						,   _A = 0						,   _A = None						,   _A = None						,   _A = None						,   _A = None						,   _A = None						,   _A = False						,   _A = False						,   _A = False						,   _A = False						,   _A = True						,   _A = None						,   **_A						,   ):






									'''simple docstring'''







									if text is None and images is None:
															raise ValueError("""You have to specify either text or images. Both cannot be none."""    )

									if text is not None:
															UpperCamelCase				:		List[Any]				   =			self.tokenizer(
															    text=_A						,   add_special_tokens=_A						,   padding=_A						,   truncation=_A						,   max_length=_A						,   stride=_A						,   pad_to_multiple_of=_A						,   return_token_type_ids=_A						,   return_attention_mask=_A						,   return_overflowing_tokens=_A						,   return_special_tokens_mask=_A						,   return_offsets_mapping=_A						,   return_length=_A						,   verbose=_A						,   return_tensors=_A						,   **_A						,   )
									if images is not None:
															UpperCamelCase				:		int				   =			self.image_processor(
															    _A						,   return_image_mask=_A						,   return_codebook_pixels=_A						,   return_tensors=_A						,   **_A						,   )

									if text is not None and images is not None:
															encoding.update(_A    )
															return encoding
									elif text is not None:
															return encoding
									else:
															return BatchEncoding(data=dict(**_A    )						,   tensor_type=_A    )







			def   _a      (      self						,   *_A						,   **_A    ):






									'''simple docstring'''







									return self.tokenizer.batch_decode(*_A						,   **_A    )







			def   _a      (      self						,   *_A						,   **_A    ):






									'''simple docstring'''







									return self.tokenizer.decode(*_A						,   **_A    )







			@property
			def   _a      (      self    ):






									'''simple docstring'''







									UpperCamelCase				:		Optional[Any]				   =			self.tokenizer.model_input_names
									UpperCamelCase				:		Dict				   =			self.image_processor.model_input_names
									return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names    )    )







			@property
			def   _a      (      self    ):






									'''simple docstring'''







									warnings.warn(
									    """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."""						,   _A						,   )
									return self.image_processor_class







			@property
			def   _a      (      self    ):






									'''simple docstring'''







									warnings.warn(
									    """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."""						,   _A						,   )
									return self.image_processor








'''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




