




"""simple docstring"""

import warnings
from typing import List, Optional, Union

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





class 				lowercase_       (     _a							):



 '''simple docstring'''
 UpperCAmelCase    :     Dict        =	['''image_processor''', '''tokenizer''']
 UpperCAmelCase    :     List[Any]        =	'''ViltImageProcessor'''
 UpperCAmelCase    :     Any        =	('''BertTokenizer''', '''BertTokenizerFast''')

 def __init__( self       :       Any    ,							_UpperCAmelCase       :       int=None    ,							_UpperCAmelCase       :       List[Any]=None    ,							**_UpperCAmelCase       :       str		):
       _A					   =   None
       if "feature_extractor" in kwargs:
             warnings.warn(
                 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
                 ' instead.'    ,							UpperCamelCase__    ,							)
             _A					   =   kwargs.pop('feature_extractor'		)

       _A					   =   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__(UpperCamelCase__    ,							UpperCamelCase__		)
       _A					   =   self.image_processor

 def __call__( self       :       Tuple    ,							_UpperCAmelCase       :       Optional[int]    ,							_UpperCAmelCase       :       Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None    ,							_UpperCAmelCase       :       bool = True    ,							_UpperCAmelCase       :       Union[bool, str, PaddingStrategy] = False    ,							_UpperCAmelCase       :       Union[bool, str, TruncationStrategy] = None    ,							_UpperCAmelCase       :       Optional[int] = None    ,							_UpperCAmelCase       :       int = 0    ,							_UpperCAmelCase       :       Optional[int] = None    ,							_UpperCAmelCase       :       Optional[bool] = None    ,							_UpperCAmelCase       :       Optional[bool] = None    ,							_UpperCAmelCase       :       bool = False    ,							_UpperCAmelCase       :       bool = False    ,							_UpperCAmelCase       :       bool = False    ,							_UpperCAmelCase       :       bool = False    ,							_UpperCAmelCase       :       bool = True    ,							_UpperCAmelCase       :       Optional[Union[str, TensorType]] = None    ,							**_UpperCAmelCase       :       Optional[Any]    ,							):
       _A					   =   self.tokenizer(
           text=UpperCamelCase__    ,							add_special_tokens=UpperCamelCase__    ,							padding=UpperCamelCase__    ,							truncation=UpperCamelCase__    ,							max_length=UpperCamelCase__    ,							stride=UpperCamelCase__    ,							pad_to_multiple_of=UpperCamelCase__    ,							return_token_type_ids=UpperCamelCase__    ,							return_attention_mask=UpperCamelCase__    ,							return_overflowing_tokens=UpperCamelCase__    ,							return_special_tokens_mask=UpperCamelCase__    ,							return_offsets_mapping=UpperCamelCase__    ,							return_length=UpperCamelCase__    ,							verbose=UpperCamelCase__    ,							return_tensors=UpperCamelCase__    ,							**UpperCamelCase__    ,							)
       # add pixel_values + pixel_mask
       _A					   =   self.image_processor(UpperCamelCase__    ,							return_tensors=UpperCamelCase__		)
       encoding.update(UpperCamelCase__		)

       return encoding

 def 			lowerCAmelCase_							( self       :       int    ,							*_UpperCAmelCase       :       List[Any]    ,							**_UpperCAmelCase       :       str		):
       return self.tokenizer.batch_decode(*UpperCamelCase__    ,							**UpperCamelCase__		)

 def 			lowerCAmelCase_							( self       :       Tuple    ,							*_UpperCAmelCase       :       Optional[int]    ,							**_UpperCAmelCase       :       Optional[int]		):
       return self.tokenizer.decode(*UpperCamelCase__    ,							**UpperCamelCase__		)

 @property
 def 			lowerCAmelCase_							( self       :       str		):
       _A					   =   self.tokenizer.model_input_names
       _A					   =   self.image_processor.model_input_names
       return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names		)		)

 @property
 def 			lowerCAmelCase_							( self       :       Union[str, Any]		):
       warnings.warn(
           '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'    ,							UpperCamelCase__    ,							)
       return self.image_processor_class



 @property
 def 			lowerCAmelCase_							( self       :       Optional[Any]		):
       warnings.warn(
           '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'    ,							UpperCamelCase__    ,							)
       return self.image_processor






'''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 				__lowerCamelCase				(   A__    ,						A__    ,						A__=1e-1_2    )       ->	Dict:






   """simple docstring"""
   UpperCamelCase					=  jnp.divide(emb_a.T    ,						jnp.clip(jnp.linalg.norm(A__    ,						axis=1    )    ,						a_min=A__    )    ).T
   UpperCamelCase					=  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  SCREAMING_SNAKE_CASE (  nn.Module		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  42
    _SCREAMING_SNAKE_CASE	  =  jnp.floataa






    def  A       (  self      :					List[Any] ):


       """simple docstring"""







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

       UpperCamelCase					=  self.param('concept_embeds'  ,						jax.nn.initializers.ones  ,						(1_7, self.config.projection_dim) )
       UpperCamelCase					=  self.param(
           'special_care_embeds'  ,						jax.nn.initializers.ones  ,						(3, self.config.projection_dim) )

       UpperCamelCase					=  self.param('concept_embeds_weights'  ,						jax.nn.initializers.ones  ,						(1_7,) )
       UpperCamelCase					=  self.param('special_care_embeds_weights'  ,						jax.nn.initializers.ones  ,						(3,) )






    def __call__(  self      :					str  ,						UpperCamelCase__      :					List[str] ):


       """simple docstring"""







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

       UpperCamelCase					=  jax_cosine_distance(UpperCamelCase__  ,						self.special_care_embeds )
       UpperCamelCase					=  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
       UpperCamelCase					=  0.0

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

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

       return has_nsfw_concepts

class  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  CLIPConfig
    _SCREAMING_SNAKE_CASE	  =  """clip_input"""
    _SCREAMING_SNAKE_CASE	  =  FlaxStableDiffusionSafetyCheckerModule






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


       """simple docstring"""







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






    def  A       (  self      :					int  ,						UpperCamelCase__      :					jax.random.KeyArray  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					FrozenDict = None ):


       """simple docstring"""







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

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

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

       return random_params






    def __call__(  self      :					List[Any]  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					dict = None  ,						):


       """simple docstring"""







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

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

