

'''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       UpperCamelCase(     UpperCAmelCase_  ,       UpperCAmelCase_	):
 UpperCAmelCase       :	Dict											= nn.functional.normalize(UpperCAmelCase_	)
 UpperCAmelCase       :	List[str]											= nn.functional.normalize(UpperCAmelCase_	)
 return torch.mm(UpperCAmelCase_  ,       normalized_text_embeds.t()	)




class        A_ (				_UpperCAmelCase							):






     '''simple docstring'''



     UpperCAmelCase_						:	str  		=  CLIPConfig

     UpperCAmelCase_						:	str  		=  ["""CLIPEncoderLayer"""]


     def __init__(		self :     Tuple     ,			lowercase_ :     List[Any]       )						->	Optional[int]:
      super().__init__(lowercase_       )

      UpperCAmelCase       :	Union[str, Any]											= CLIPVisionModel(config.vision_config       )
      UpperCAmelCase       :	List[Any]											= nn.Linear(config.vision_config.hidden_size     ,			config.projection_dim     ,			bias=lowercase_       )

      UpperCAmelCase       :	str											= nn.Parameter(torch.ones(17     ,			config.projection_dim       )     ,			requires_grad=lowercase_       )
      UpperCAmelCase       :	int											= nn.Parameter(torch.ones(3     ,			config.projection_dim       )     ,			requires_grad=lowercase_       )

      UpperCAmelCase       :	List[Any]											= nn.Parameter(torch.ones(17       )     ,			requires_grad=lowercase_       )
      UpperCAmelCase       :	Optional[int]											= nn.Parameter(torch.ones(3       )     ,			requires_grad=lowercase_       )


     @torch.no_grad()
     def    UpperCAmelCase_       (		self :     Dict     ,			lowercase_ :     Optional[Any]     ,			lowercase_ :     Dict       )						->	Optional[Any]:
      UpperCAmelCase       :	Tuple											= self.vision_model(lowercase_       )[1]  # pooled_output
      UpperCAmelCase       :	List[Any]											= self.visual_projection(lowercase_       )

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

      UpperCAmelCase       :	Tuple											= []
      UpperCAmelCase       :	List[str]											= image_embeds.shape[0]
      for i in range(lowercase_       ):
       UpperCAmelCase       :	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
       UpperCAmelCase       :	Optional[int]											= 0.0

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

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

       result.append(lowercase_       )

      UpperCAmelCase       :	Union[str, Any]											= [len(res['bad_concepts']       ) > 0 for res in result]

      return images, has_nsfw_concepts




     @torch.no_grad()
     def    UpperCAmelCase_       (		self :     int     ,			lowercase_ :     List[Any]     ,			lowercase_ :     Tuple       )						->	Union[str, Any]:
      UpperCAmelCase       :	Optional[Any]											= self.vision_model(lowercase_       )[1]  # pooled_output
      UpperCAmelCase       :	Optional[Any]											= self.visual_projection(lowercase_       )

      UpperCAmelCase       :	str											= cosine_distance(lowercase_     ,			self.special_care_embeds       )
      UpperCAmelCase       :	Union[str, Any]											= cosine_distance(lowercase_     ,			self.concept_embeds       )

      # increase this value to create a stronger `nsfw` filter
      # at the cost of increasing the possibility of filtering benign images
      UpperCAmelCase       :	List[str]											= 0.0

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

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

      return images, has_nsfw_concepts











"""simple docstring"""





from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import fa_score, matthews_corrcoef

import datasets


SCREAMING_SNAKE_CASE__					=   "\\n@inproceedings{wang2019glue,\n  title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n  author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n  note={In the Proceedings of ICLR.},\n  year={2019}\n}\n"

SCREAMING_SNAKE_CASE__					=   "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n"

SCREAMING_SNAKE_CASE__					=   "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n    predictions: list of predictions to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n    \"accuracy\": Accuracy\n    \"f1\": F1 score\n    \"pearson\": Pearson Correlation\n    \"spearmanr\": Spearman Correlation\n    \"matthews_correlation\": Matthew Correlation\nExamples:\n\n    >>> glue_metric = datasets.load_metric('glue', 'sst2')  # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'mrpc')  # 'mrpc' or 'qqp'\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'accuracy': 1.0, 'f1': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'stsb')\n    >>> references = [0., 1., 2., 3., 4., 5.]\n    >>> predictions = [0., 1., 2., 3., 4., 5.]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n    {'pearson': 1.0, 'spearmanr': 1.0}\n\n    >>> glue_metric = datasets.load_metric('glue', 'cola')\n    >>> references = [0, 1]\n    >>> predictions = [0, 1]\n    >>> results = glue_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'matthews_correlation': 1.0}\n"


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Tuple							,						SCREAMING_SNAKE_CASE     :						List[Any]			):







      '''simple docstring'''




      return float((preds == labels).mean()			)


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Optional[Any]							,						SCREAMING_SNAKE_CASE     :						Any			):







      '''simple docstring'''




      lowerCAmelCase  						=       simple_accuracy(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)
      lowerCAmelCase  						=       float(fa_score(y_true=SCREAMING_SNAKE_CASE							,						y_pred=SCREAMING_SNAKE_CASE			)			)
      return {
          "accuracy": acc,
          "f1": fa,
      }


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						List[str]							,						SCREAMING_SNAKE_CASE     :						Tuple			):







      '''simple docstring'''




      lowerCAmelCase  						=       float(pearsonr(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)[0]			)
      lowerCAmelCase  						=       float(spearmanr(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			)[0]			)
      return {
          "pearson": pearson_corr,
          "spearmanr": spearman_corr,
      }






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,  _KWARGS_DESCRIPTION					)
class 		lowercase					(					datasets.Metric					):





      def     _snake_case			(       self )		->     List[str]:
            if self.config_name not in [
                "sst2",
                "mnli",
                "mnli_mismatched",
                "mnli_matched",
                "cola",
                "stsb",
                "mrpc",
                "qqp",
                "qnli",
                "rte",
                "wnli",
                "hans",
            ]:
                  raise KeyError(
                      """You should supply a configuration name selected in """
                      """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """
                      """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" )
            return datasets.MetricInfo(
                description=_DESCRIPTION      ,						citation=_CITATION      ,						inputs_description=_KWARGS_DESCRIPTION      ,						features=datasets.Features(
                    {
                        """predictions""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ),
                        """references""": datasets.Value("""int64""" if self.config_name != """stsb""" else """float32""" ),
                    } )      ,						codebase_urls=[]      ,						reference_urls=[]      ,						format="""numpy"""      ,						)





      def     _snake_case			(       self      ,						lowercase      ,						lowercase )		->     Any:
            if self.config_name == "cola":
                  return {"matthews_correlation": matthews_corrcoef(lowercase      ,						lowercase )}
            elif self.config_name == "stsb":
                  return pearson_and_spearman(lowercase      ,						lowercase )
            elif self.config_name in ["mrpc", "qqp"]:
                  return acc_and_fa(lowercase      ,						lowercase )
            elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]:
                  return {"accuracy": simple_accuracy(lowercase      ,						lowercase )}
            else:
                  raise KeyError(
                      """You should supply a configuration name selected in """
                      """[\"sst2\", \"mnli\", \"mnli_mismatched\", \"mnli_matched\", """
                      """\"cola\", \"stsb\", \"mrpc\", \"qqp\", \"qnli\", \"rte\", \"wnli\", \"hans\"]""" )






