


import warnings

from ...utils import is_sklearn_available, requires_backends


if is_sklearn_available():
    from scipy.stats import pearsonr, spearmanr
    from sklearn.metrics import fa_score, matthews_corrcoef


__snake_case   							=						(
    '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate '''
    '''library. You can have a look at this example script for pointers: '''
    '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py'''
)






def 		_A		(		_lowercase					,  _lowercase )					-> str:


     """simple docstring"""


     warnings.warn(_lowercase					,  _lowercase )
     requires_backends(_lowercase					,  'sklearn' )
     return (preds == labels).mean()






def 		_A		(		_lowercase					,  _lowercase )					-> Optional[int]:


     """simple docstring"""


     warnings.warn(_lowercase					,  _lowercase )
     requires_backends(_lowercase					,  'sklearn' )
     __UpperCamelCase =			simple_accuracy(_lowercase					,  _lowercase )
     __UpperCamelCase =			fa_score(y_true=_lowercase					,  y_pred=_lowercase )
     return {
         "acc": acc,
         "f1": fa,
         "acc_and_f1": (acc + fa) / 2,
     }






def 		_A		(		_lowercase					,  _lowercase )					-> List[str]:


     """simple docstring"""


     warnings.warn(_lowercase					,  _lowercase )
     requires_backends(_lowercase					,  'sklearn' )
     __UpperCamelCase =			pearsonr(_lowercase					,  _lowercase )[0]
     __UpperCamelCase =			spearmanr(_lowercase					,  _lowercase )[0]
     return {
         "pearson": pearson_corr,
         "spearmanr": spearman_corr,
         "corr": (pearson_corr + spearman_corr) / 2,
     }






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase )					-> Dict:


     """simple docstring"""


     warnings.warn(_lowercase					,  _lowercase )
     requires_backends(_lowercase					,  'sklearn' )
     assert len(_lowercase ) == len(_lowercase ), f'''Predictions and labels have mismatched lengths {len(_lowercase )} and {len(_lowercase )}'''
     if task_name == "cola":
          return {"mcc": matthews_corrcoef(_lowercase					,  _lowercase )}
     elif task_name == "sst-2":
          return {"acc": simple_accuracy(_lowercase					,  _lowercase )}
     elif task_name == "mrpc":
          return acc_and_fa(_lowercase					,  _lowercase )
     elif task_name == "sts-b":
          return pearson_and_spearman(_lowercase					,  _lowercase )
     elif task_name == "qqp":
          return acc_and_fa(_lowercase					,  _lowercase )
     elif task_name == "mnli":
          return {"mnli/acc": simple_accuracy(_lowercase					,  _lowercase )}
     elif task_name == "mnli-mm":
          return {"mnli-mm/acc": simple_accuracy(_lowercase					,  _lowercase )}
     elif task_name == "qnli":
          return {"acc": simple_accuracy(_lowercase					,  _lowercase )}
     elif task_name == "rte":
          return {"acc": simple_accuracy(_lowercase					,  _lowercase )}
     elif task_name == "wnli":
          return {"acc": simple_accuracy(_lowercase					,  _lowercase )}
     elif task_name == "hans":
          return {"acc": simple_accuracy(_lowercase					,  _lowercase )}
     else:
          raise KeyError(_lowercase )






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase )					-> Union[str, Any]:


     """simple docstring"""


     warnings.warn(_lowercase					,  _lowercase )
     requires_backends(_lowercase					,  'sklearn' )
     if len(_lowercase ) != len(_lowercase ):
          raise ValueError(f'''Predictions and labels have mismatched lengths {len(_lowercase )} and {len(_lowercase )}''' )
     if task_name == "xnli":
          return {"acc": simple_accuracy(_lowercase					,  _lowercase )}
     else:
          raise KeyError(_lowercase )






'''simple docstring'''

from typing import Optional, Tuple

import jax
import jax.numpy as jnp
from flax import linen as nn
from flax.core.frozen_dict import FrozenDict
from transformers import CLIPConfig, FlaxPreTrainedModel
from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule

def _SCREAMING_SNAKE_CASE (A    ,					A    ,					A=1E-12			)			->			str:






       """simple docstring"""







       lowercase__      =					jnp.divide(emb_a.T    ,					jnp.clip(jnp.linalg.norm(A    ,					axis=1			)    ,					a_min=A			)			).T
       lowercase__      =					jnp.divide(emb_a.T    ,					jnp.clip(jnp.linalg.norm(A    ,					axis=1			)    ,					a_min=A			)			).T
       return jnp.matmul(A    ,					norm_emb_a.T			)
class     __lowerCAmelCase		(nn.Module	):





      '''simple docstring'''






      lowerCAmelCase__   :	CLIPConfig
      lowerCAmelCase__   :	jnp.dtype       =				jnp.floataa



      def  UpperCamelCase__						(self       :       Union[str, Any]					):

             '''simple docstring'''







             lowercase__      =					FlaxCLIPVisionModule(self.config.vision_config					)
             lowercase__      =					nn.Dense(self.config.projection_dim  ,		use_bias=UpperCamelCase  ,		dtype=self.dtype					)

             lowercase__      =					self.param('''concept_embeds'''  ,		jax.nn.initializers.ones  ,		(17, self.config.projection_dim)					)
             lowercase__      =					self.param(
                 '''special_care_embeds'''  ,		jax.nn.initializers.ones  ,		(3, self.config.projection_dim)					)

             lowercase__      =					self.param('''concept_embeds_weights'''  ,		jax.nn.initializers.ones  ,		(17,)					)
             lowercase__      =					self.param('''special_care_embeds_weights'''  ,		jax.nn.initializers.ones  ,		(3,)					)






      def __call__(self       :       Union[str, Any]  ,		UpperCamelCase       :       Tuple					):

             '''simple docstring'''







             lowercase__      =					self.vision_model(UpperCamelCase					)[1]
             lowercase__      =					self.visual_projection(UpperCamelCase					)

             lowercase__      =					jax_cosine_distance(UpperCamelCase  ,		self.special_care_embeds					)
             lowercase__      =					jax_cosine_distance(UpperCamelCase  ,		self.concept_embeds					)

             # increase this value to create a stronger `nfsw` filter
             # at the cost of increasing the possibility of filtering benign image inputs
             lowercase__      =					0.0

             lowercase__      =					special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
             lowercase__      =					jnp.round(UpperCamelCase  ,		3					)
             lowercase__      =					jnp.any(special_scores > 0  ,		axis=1  ,		keepdims=UpperCamelCase					)
             # Use a lower threshold if an image has any special care concept
             lowercase__      =					is_special_care * 0.01

             lowercase__      =					cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
             lowercase__      =					jnp.round(UpperCamelCase  ,		3					)
             lowercase__      =					jnp.any(concept_scores > 0  ,		axis=1					)

             return has_nsfw_concepts






class     __lowerCAmelCase		(lowercase_	):





      '''simple docstring'''






      lowerCAmelCase__   :	Union[str, Any]       =				CLIPConfig
      lowerCAmelCase__   :	Optional[int]       =				"""clip_input"""
      lowerCAmelCase__   :	Any       =				FlaxStableDiffusionSafetyCheckerModule



      def __init__(self       :       Optional[int]  ,		UpperCamelCase       :       CLIPConfig  ,		UpperCamelCase       :       Optional[Tuple] = None  ,		UpperCamelCase       :       int = 0  ,		UpperCamelCase       :       jnp.dtype = jnp.floataa  ,		UpperCamelCase       :       bool = True  ,		**UpperCamelCase       :       List[Any]  ,		):

             '''simple docstring'''







             if input_shape is None:
                    lowercase__      =					(1, 224, 224, 3)
             lowercase__      =					self.module_class(config=UpperCamelCase  ,		dtype=UpperCamelCase  ,		**UpperCamelCase					)
             super().__init__(UpperCamelCase  ,		UpperCamelCase  ,		input_shape=UpperCamelCase  ,		seed=UpperCamelCase  ,		dtype=UpperCamelCase  ,		_do_init=_do_init					)



      def  UpperCamelCase__						(self       :       Any  ,		UpperCamelCase       :       jax.random.KeyArray  ,		UpperCamelCase       :       Tuple  ,		UpperCamelCase       :       FrozenDict = None					):

             '''simple docstring'''







             lowercase__      =					jax.random.normal(UpperCamelCase  ,		UpperCamelCase					)

             lowercase__     ,lowercase__      =					jax.random.split(UpperCamelCase					)
             lowercase__      =					{'''params''': params_rng, '''dropout''': dropout_rng}

             lowercase__      =					self.module.init(UpperCamelCase  ,		UpperCamelCase					)['''params''']

             return random_params






      def __call__(self       :       Optional[Any]  ,		UpperCamelCase       :       Tuple  ,		UpperCamelCase       :       dict = None  ,		):

             '''simple docstring'''







             lowercase__      =					jnp.transpose(UpperCamelCase  ,		(0, 2, 3, 1)					)

             return self.module.apply(
                 {'''params''': params or self.params}  ,		jnp.array(UpperCamelCase  ,		dtype=jnp.floataa					)  ,		rngs={}  ,		)




