"""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     __UpperCAmelCase					(			lowercase   ,lowercase   ,lowercase=1E-12		):







  """simple docstring"""
  _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   ):
    _snake_case     :  CLIPConfig
    _snake_case     :  jnp.dtype     							=							jnp.floataa


    def      lowerCAmelCase_  (					self	:  Any					):
      _UpperCAmelCase						 =      FlaxCLIPVisionModule(self.config.vision_config					)
      _UpperCAmelCase						 =      nn.Dense(self.config.projection_dim   ,				use_bias=__lowerCAmelCase   ,				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	:  str   ,				__lowerCAmelCase	:  Any					):
      _UpperCAmelCase						 =      self.vision_model(__lowerCAmelCase					)[1]
      _UpperCAmelCase						 =      self.visual_projection(__lowerCAmelCase					)

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

      _UpperCAmelCase						 =      special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
      _UpperCAmelCase						 =      jnp.round(__lowerCAmelCase   ,				3					)
      _UpperCAmelCase						 =      jnp.any(special_scores > 0   ,				axis=1   ,				keepdims=__lowerCAmelCase					)
      # 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(__lowerCAmelCase   ,				3					)
      _UpperCAmelCase						 =      jnp.any(concept_scores > 0   ,				axis=1					)

      return has_nsfw_concepts



class        a				(		lowerCAmelCase_   ):
    _snake_case     :  Dict     							=							CLIPConfig
    _snake_case     :  Optional[Any]     							=							'clip_input'
    _snake_case     :  List[str]     							=							FlaxStableDiffusionSafetyCheckerModule


    def __init__(					self	:  int   ,				__lowerCAmelCase	:  CLIPConfig   ,				__lowerCAmelCase	:  Optional[Tuple] = None   ,				__lowerCAmelCase	:  int = 0   ,				__lowerCAmelCase	:  jnp.dtype = jnp.floataa   ,				__lowerCAmelCase	:  bool = True   ,				**__lowerCAmelCase	:  Optional[int]   ,				):
      if input_shape is None:
        _UpperCAmelCase						 =      (1, 224, 224, 3)
      _UpperCAmelCase						 =      self.module_class(config=__lowerCAmelCase   ,				dtype=__lowerCAmelCase   ,				**__lowerCAmelCase					)
      super().__init__(__lowerCAmelCase   ,				__lowerCAmelCase   ,				input_shape=__lowerCAmelCase   ,				seed=__lowerCAmelCase   ,				dtype=__lowerCAmelCase   ,				_do_init=_do_init					)


    def      lowerCAmelCase_  (					self	:  List[Any]   ,				__lowerCAmelCase	:  jax.random.KeyArray   ,				__lowerCAmelCase	:  Tuple   ,				__lowerCAmelCase	:  FrozenDict = None					):
      # init input tensor
      _UpperCAmelCase						 =      jax.random.normal(__lowerCAmelCase   ,				__lowerCAmelCase					)

      _UpperCAmelCase ,				_UpperCAmelCase						 =      jax.random.split(__lowerCAmelCase					)
      _UpperCAmelCase						 =      {"""params""": params_rng, """dropout""": dropout_rng}

      _UpperCAmelCase						 =      self.module.init(__lowerCAmelCase   ,				__lowerCAmelCase					)["""params"""]

      return random_params


    def __call__(					self	:  Optional[int]   ,				__lowerCAmelCase	:  Dict   ,				__lowerCAmelCase	:  dict = None   ,				):
      _UpperCAmelCase						 =      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"""


import random






def     __UpperCAmelCase					(			lowercase   ,lowercase   ,lowercase = False		):







  """simple docstring"""
  _UpperCAmelCase						 =      {i: [] for i in range(lowercase		)}

  # if probability is greater or equal than 1, then generate a complete graph
  if probability >= 1:
    return complete_graph(lowercase		)
  # if probability is lower or equal than 0, then return a graph without edges
  if probability <= 0:
    return graph

  # for each couple of nodes, add an edge from u to v
  # if the number randomly generated is greater than probability probability
  for i in range(lowercase		):
    for j in range(i + 1   ,lowercase		):
      if random.random() < probability:
        graph[i].append(lowercase		)
        if not directed:
          # if the graph is undirected, add an edge in from j to i, either
          graph[j].append(lowercase		)
  return graph






def     __UpperCAmelCase					(			lowercase		):







  """simple docstring"""
  return {
      i: [j for j in range(lowercase		) if i != j] for i in range(lowercase		)
  }


if __name__ == "__main__":
    import doctest

    doctest.testmod()
