





"""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 		__lowercase     (   snake_case_  :  List[str]				,snake_case_  :  int				,snake_case_  :  Dict=1e-12						)   ->Any:



    '''simple docstring'''







    __A    :						str						 =     jnp.divide(emb_a.T				,jnp.clip(jnp.linalg.norm(snake_case_				,axis=1						)				,a_min=snake_case_						)						).T
    __A    :						List[Any]						 =     jnp.divide(emb_a.T				,jnp.clip(jnp.linalg.norm(snake_case_				,axis=1						)				,a_min=snake_case_						)						).T
    return jnp.matmul(snake_case_				,norm_emb_a.T						)






class 		__snake_case					(		nn.Module     ):





 """simple docstring"""


 _lowerCamelCase        =     42
 _lowerCamelCase        =     jnp.floataa

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Optional[Any]						 =     FlaxCLIPVisionModule(self.config.vision_config  )
     __A    :						Any						 =     nn.Dense(self.config.projection_dim					,						use_bias=__lowerCamelCase					,						dtype=self.dtype  )

     __A    :						List[str]						 =     self.param('''concept_embeds'''					,						jax.nn.initializers.ones					,						(17, self.config.projection_dim)  )
     __A    :						str						 =     self.param(
         '''special_care_embeds'''					,						jax.nn.initializers.ones					,						(3, self.config.projection_dim)  )

     __A    :						Union[str, Any]						 =     self.param('''concept_embeds_weights'''					,						jax.nn.initializers.ones					,						(17,)  )
     __A    :						str						 =     self.param('''special_care_embeds_weights'''					,						jax.nn.initializers.ones					,						(3,)  )







 def __call__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Any						 =     self.vision_model(__lowerCamelCase  )[1]
     __A    :						Union[str, Any]						 =     self.visual_projection(__lowerCamelCase  )

     __A    :						Dict						 =     jax_cosine_distance(__lowerCamelCase					,						self.special_care_embeds  )
     __A    :						Optional[Any]						 =     jax_cosine_distance(__lowerCamelCase					,						self.concept_embeds  )

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

     __A    :						str						 =     special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
     __A    :						Optional[int]						 =     jnp.round(__lowerCamelCase					,						3  )
     __A    :						Union[str, Any]						 =     jnp.any(special_scores > 0					,						axis=1					,						keepdims=__lowerCamelCase  )
     # Use a lower threshold if an image has any special care concept
     __A    :						Union[str, Any]						 =     is_special_care * 0.0_1

     __A    :						Dict						 =     cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
     __A    :						str						 =     jnp.round(__lowerCamelCase					,						3  )
     __A    :						Any						 =     jnp.any(concept_scores > 0					,						axis=1  )

     return has_nsfw_concepts






class 		__snake_case					(		SCREAMING_SNAKE_CASE__     ):





 """simple docstring"""


 _lowerCamelCase        =     CLIPConfig
 _lowerCamelCase        =     """clip_input"""
 _lowerCamelCase        =     FlaxStableDiffusionSafetyCheckerModule

 def __init__(    self					,						__lowerCamelCase					,						__lowerCamelCase = None					,						__lowerCamelCase = 0					,						__lowerCamelCase = jnp.floataa					,						__lowerCamelCase = True					,						**__lowerCamelCase					,						):



     '''simple docstring'''




     if input_shape is None:
         __A    :						Any						 =     (1, 224, 224, 3)
     __A    :						Optional[int]						 =     self.module_class(config=__lowerCamelCase					,						dtype=__lowerCamelCase					,						**__lowerCamelCase  )
     super().__init__(__lowerCamelCase					,						__lowerCamelCase					,						input_shape=__lowerCamelCase					,						seed=__lowerCamelCase					,						dtype=__lowerCamelCase					,						_do_init=_do_init  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase = None  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     jax.random.normal(__lowerCamelCase					,						__lowerCamelCase  )

     __A ,       __A    :						Optional[int]						 =     jax.random.split(__lowerCamelCase  )
     __A    :						Optional[int]						 =     {'''params''': params_rng, '''dropout''': dropout_rng}

     __A    :						Any						 =     self.module.init(__lowerCamelCase					,						__lowerCamelCase  )['''params''']

     return random_params







 def __call__(    self					,						__lowerCamelCase					,						__lowerCamelCase = None					,						):



     '''simple docstring'''




     __A    :						Optional[int]						 =     jnp.transpose(__lowerCamelCase					,						(0, 2, 3, 1)  )

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











"""simple docstring"""



# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch

from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer
from .base import PipelineTool






class 		__snake_case					(		SCREAMING_SNAKE_CASE__     ):





 """simple docstring"""


 _lowerCamelCase        =     """facebook/bart-large-mnli"""
 _lowerCamelCase        =     (
     """This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which """
     """should be the text to classify, and `labels`, which should be the list of labels to use for classification. """
     """It returns the most likely label in the list of provided `labels` for the input text."""
 )
 _lowerCamelCase        =     """text_classifier"""
 _lowerCamelCase        =     AutoTokenizer
 _lowerCamelCase        =     AutoModelForSequenceClassification

 _lowerCamelCase        =     ["""text""", ["""text"""]]
 _lowerCamelCase        =     ["""text"""]

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     super().setup()
     __A    :						List[str]						 =     self.model.config
     __A    :						int						 =     -1
     for idx, label in config.idalabel.items():
         if label.lower().startswith('''entail'''  ):
             __A    :						List[str]						 =     int(__lowerCamelCase  )
     if self.entailment_id == -1:
         raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.'''  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Union[str, Any]						 =     labels
     return self.pre_processor(
         [text] * len(__lowerCamelCase  )					,						[F"""This example is {label}""" for label in labels]					,						return_tensors='''pt'''					,						padding='''max_length'''					,						)







 def 					UpperCamelCase__(    self					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     outputs.logits
     __A    :						List[str]						 =     torch.argmax(logits[:, 2]  ).item()
     return self._labels[label_id]




