



'''simple docstring'''





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

from ...utils import logging


lowercase_		       =  logging.get_logger(__name__)




def lowerCAmelCase  (__A  ,	__A):



     """simple docstring"""



     _a      =  nn.functional.normalize(lowercase__)
     _a      =  nn.functional.normalize(lowercase__)
     return torch.mm(lowercase__  ,	normalized_text_embeds.t())






class __A			(  A__						):



 '''simple docstring'''







 __lowerCamelCase    :       Optional[Any]          =       CLIPConfig

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



 def __init__(self ,   A       )    ->     Tuple:


      """simple docstring"""



      super().__init__(lowerCAmelCase__       )

      _a      =  CLIPVisionModel(config.vision_config       )
      _a      =  nn.Linear(config.vision_config.hidden_size ,   config.projection_dim ,   bias=lowerCAmelCase__       )

      _a      =  nn.Parameter(torch.ones(17 ,   config.projection_dim       ) ,   requires_grad=lowerCAmelCase__       )
      _a      =  nn.Parameter(torch.ones(3 ,   config.projection_dim       ) ,   requires_grad=lowerCAmelCase__       )

      _a      =  nn.Parameter(torch.ones(17       ) ,   requires_grad=lowerCAmelCase__       )
      _a      =  nn.Parameter(torch.ones(3       ) ,   requires_grad=lowerCAmelCase__       )



 @torch.no_grad()
 def 					a__  (self ,   A ,   A       )    ->     Dict:


      """simple docstring"""



      _a      =  self.vision_model(lowerCAmelCase__       )[1]  # pooled_output
      _a      =  self.visual_projection(lowerCAmelCase__       )

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

      _a      =  []
      _a      =  image_embeds.shape[0]
      for i in range(lowerCAmelCase__       ):
           _a      =  {'''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
           _a      =  0.0

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

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

           result.append(lowerCAmelCase__       )

      _a      =  [len(res['''bad_concepts''']       ) > 0 for res in result]

      return images, has_nsfw_concepts



 @torch.no_grad()
 def 					a__  (self ,   A ,   A       )    ->     Any:


      """simple docstring"""



      _a      =  self.vision_model(lowerCAmelCase__       )[1]  # pooled_output
      _a      =  self.visual_projection(lowerCAmelCase__       )

      _a      =  cosine_distance(lowerCAmelCase__ ,   self.special_care_embeds       )
      _a      =  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
      _a      =  0.0

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

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

      return images, has_nsfw_concepts







import importlib.metadata
import operator
import re
import sys
from typing import Optional

from packaging import version


__lowerCAmelCase	: Union[str, Any]  				={
    '<': operator.lt,
    '<=': operator.le,
    '==': operator.eq,
    '!=': operator.ne,
    '>=': operator.ge,
    '>': operator.gt,
}


def        _UpperCamelCase							(      lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__      ):
						if got_ver is None or want_ver is None:
												raise ValueError(
												    F'''Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider'''
												    F''' reinstalling {pkg}.'''      )
						if not ops[op](version.parse(lowercase__      )    ,       version.parse(lowercase__      )      ):
												raise ImportError(
												    F'''{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}'''      )


def        _UpperCamelCase							(      lowercase__    ,       lowercase__ = None      ):
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		F'''\n{hint}''' if hint is not None else ''''''

						# non-versioned check
						if re.match(R'''^[\w_\-\d]+$'''    ,       lowercase__      ):
												__SCREAMING_SNAKE_CASE			,			__SCREAMING_SNAKE_CASE			,			__SCREAMING_SNAKE_CASE						:     str					=		requirement, None, None
						else:
												__SCREAMING_SNAKE_CASE						:     List[Any]					=		re.findall(R'''^([^!=<>\s]+)([\s!=<>]{1,2}.+)'''    ,       lowercase__      )
												if not match:
																		raise ValueError(
																		    '''requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but'''
																		    F''' got {requirement}'''      )
												__SCREAMING_SNAKE_CASE			,			__SCREAMING_SNAKE_CASE						:     Tuple					=		match[0]
												__SCREAMING_SNAKE_CASE						:     Optional[int]					=		want_full.split(''','''      )  # there could be multiple requirements
												__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		{}
												for w in want_range:
																		__SCREAMING_SNAKE_CASE						:     Any					=		re.findall(R'''^([\s!=<>]{1,2})(.+)'''    ,       lowercase__      )
																		if not match:
																								raise ValueError(
																								    '''requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,'''
																								    F''' but got {requirement}'''      )
																		__SCREAMING_SNAKE_CASE			,			__SCREAMING_SNAKE_CASE						:     Tuple					=		match[0]
																		__SCREAMING_SNAKE_CASE						:     List[Any]					=		want_ver
																		if op not in ops:
																								raise ValueError(F'''{requirement}: need one of {list(ops.keys()      )}, but got {op}'''      )

    # special case
						if pkg == "python":
												__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		'''.'''.join([str(lowercase__      ) for x in sys.version_info[:3]]      )
												for op, want_ver in wanted.items():
																		_compare_versions(lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__      )
												return

						# check if any version is installed
						try:
												__SCREAMING_SNAKE_CASE						:     Optional[int]					=		importlib.metadata.version(lowercase__      )
						except importlib.metadata.PackageNotFoundError:
												raise importlib.metadata.PackageNotFoundError(
												    F'''The \'{requirement}\' distribution was not found and is required by this application. {hint}'''      )

						# check that the right version is installed if version number or a range was provided
						if want_ver is not None:
												for op, want_ver in wanted.items():
																		_compare_versions(lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__      )


def        _UpperCamelCase							(      lowercase__      ):
						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		'''Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main'''
						return require_version(lowercase__    ,       lowercase__      )
