



"""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      (   lowercase_		,	lowercase_		,	lowercase_=1e-12						):
						UpperCAmelCase             = jnp.divide(emb_a.T		,	jnp.clip(jnp.linalg.norm(lowercase_		,	axis=1						)		,	a_min=lowercase_						)						).T
						UpperCAmelCase             = jnp.divide(emb_a.T		,	jnp.clip(jnp.linalg.norm(lowercase_		,	axis=1						)		,	a_min=lowercase_						)						).T
						return jnp.matmul(lowercase_		,	norm_emb_a.T						)







class       A_			(     nn.Module				):



						"""simple docstring"""
						__UpperCamelCase						=							42
						__UpperCamelCase						=							jnp.floataa






						def 	UpperCAmelCase__     (					self :List[Any]					)				->			str:
												UpperCAmelCase             = FlaxCLIPVisionModule(self.config.vision_config					)
												UpperCAmelCase             = nn.Dense(self.config.projection_dim   ,  use_bias=lowercase_   ,  dtype=self.dtype					)

												UpperCAmelCase             = self.param('concept_embeds'   ,  jax.nn.initializers.ones   ,  (17, 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   ,  (17,)					)
												UpperCAmelCase             = self.param('special_care_embeds_weights'   ,  jax.nn.initializers.ones   ,  (3,)					)






						def __call__(					self :List[Any]   ,  lowercase_ :str					)				->			int:
												UpperCAmelCase             = self.vision_model(lowercase_					)[1]
												UpperCAmelCase             = self.visual_projection(lowercase_					)

												UpperCAmelCase             = jax_cosine_distance(lowercase_   ,  self.special_care_embeds					)
												UpperCAmelCase             = jax_cosine_distance(lowercase_   ,  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(lowercase_   ,  3					)
												UpperCAmelCase             = jnp.any(special_scores > 0   ,  axis=1   ,  keepdims=lowercase_					)
												# Use a lower threshold if an image has any special care concept
												UpperCAmelCase             = is_special_care * 0.01

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

												return has_nsfw_concepts







class       A_			(     SCREAMING_SNAKE_CASE_				):



						"""simple docstring"""
						__UpperCamelCase						=							CLIPConfig
						__UpperCamelCase						=							"""clip_input"""
						__UpperCamelCase						=							FlaxStableDiffusionSafetyCheckerModule






						def __init__(					self :Optional[Any]   ,  lowercase_ :CLIPConfig   ,  lowercase_ :Optional[Tuple] = None   ,  lowercase_ :int = 0   ,  lowercase_ :jnp.dtype = jnp.floataa   ,  lowercase_ :bool = True   ,  **lowercase_ :List[Any]   ,  )				->			Optional[Any]:
												if input_shape is None:
																		UpperCAmelCase             = (1, 2_24, 2_24, 3)
												UpperCAmelCase             = self.module_class(config=lowercase_   ,  dtype=lowercase_   ,  **lowercase_					)
												super().__init__(lowercase_   ,  lowercase_   ,  input_shape=lowercase_   ,  seed=lowercase_   ,  dtype=lowercase_   ,  _do_init=_do_init					)






						def 	UpperCAmelCase__     (					self :Optional[int]   ,  lowercase_ :jax.random.KeyArray   ,  lowercase_ :Tuple   ,  lowercase_ :FrozenDict = None					)				->			FrozenDict:
												# init input tensor
												UpperCAmelCase             = jax.random.normal(lowercase_   ,  lowercase_					)

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

												UpperCAmelCase             = self.module.init(lowercase_   ,  lowercase_					)['params']

												return random_params






						def __call__(					self :List[Any]   ,  lowercase_ :Tuple   ,  lowercase_ :dict = None   ,  )				->			Optional[int]:
												UpperCAmelCase             = jnp.transpose(lowercase_   ,  (0, 2, 3, 1)					)

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








def 			UpperCAmelCase__				(			_A      : dict							):





  '''simple docstring'''







  a__  =set()
  # To detect a back edge, keep track of vertices currently in the recursion stack
  a__  =set()
  return any(
      node not in visited and depth_first_search(_A	,      _A	,      _A	,      _A							)
      for node in graph							)




def 			UpperCAmelCase__				(			_A      : dict	,      _A      : int	,      _A      : set	,      _A      : set							):





  '''simple docstring'''







  visited.add(_A							)
  rec_stk.add(_A							)

  for node in graph[vertex]:
    if node not in visited:
      if depth_first_search(_A	,      _A	,      _A	,      _A							):
        return True
    elif node in rec_stk:
      return True

    # The node needs to be removed from recursion stack before function ends
  rec_stk.remove(_A							)
  return False


if __name__ == "__main__":
       from doctest import testmod

       testmod()
