


"""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_      (				UpperCamelCase__	: List[str]				,   UpperCamelCase__	: Optional[Any]				,   UpperCamelCase__	: List[Any]=1E-12 ):






 """simple docstring"""







 __lowercase									=	jnp.divide(emb_a.T				,   jnp.clip(jnp.linalg.norm(UpperCamelCase__				,   axis=1 )				,   a_min=UpperCamelCase__ ) ).T
 __lowercase									=	jnp.divide(emb_a.T				,   jnp.clip(jnp.linalg.norm(UpperCamelCase__				,   axis=1 )				,   a_min=UpperCamelCase__ ) ).T
 return jnp.matmul(UpperCamelCase__				,   norm_emb_a.T )





class    lowerCamelCase__						(		nn.Module    ):
      a :     CLIPConfig
      a :     jnp.dtype											=		jnp.floataa
      def SCREAMING_SNAKE_CASE_	(		self	:	Optional[int]							):






       '''simple docstring'''


       __lowercase									=	FlaxCLIPVisionModule(self.config.vision_config							)
       __lowercase									=	nn.Dense(self.config.projection_dim      ,       use_bias=A_      ,       dtype=self.dtype							)

       __lowercase									=	self.param("""concept_embeds"""      ,       jax.nn.initializers.ones      ,       (1_7, 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      ,       (1_7,)							)
       __lowercase									=	self.param("""special_care_embeds_weights"""      ,       jax.nn.initializers.ones      ,       (3,)							)






      def __call__(		self	:	Union[str, Any]      ,       A_	:	List[str]							):






       '''simple docstring'''


       __lowercase									=	self.vision_model(A_							)[1]
       __lowercase									=	self.visual_projection(A_							)

       __lowercase									=	jax_cosine_distance(A_      ,       self.special_care_embeds							)
       __lowercase									=	jax_cosine_distance(A_      ,       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(A_      ,       3							)
       __lowercase									=	jnp.any(special_scores > 0      ,       axis=1      ,       keepdims=A_							)
       # 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(A_      ,       3							)
       __lowercase									=	jnp.any(concept_scores > 0      ,       axis=1							)

       return has_nsfw_concepts






class    lowerCamelCase__						(		_a    ):
      a :     Tuple											=		CLIPConfig
      a :     List[Any]											=		"""clip_input"""
      a :     int											=		FlaxStableDiffusionSafetyCheckerModule
      def __init__(		self	:	str      ,       A_	:	CLIPConfig      ,       A_	:	Optional[Tuple] = None      ,       A_	:	int = 0      ,       A_	:	jnp.dtype = jnp.floataa      ,       A_	:	bool = True      ,       **A_	:	Any      ,       ):






       '''simple docstring'''


       if input_shape is None:
        __lowercase									=	(1, 2_2_4, 2_2_4, 3)
       __lowercase									=	self.module_class(config=A_      ,       dtype=A_      ,       **A_							)
       super().__init__(A_      ,       A_      ,       input_shape=A_      ,       seed=A_      ,       dtype=A_      ,       _do_init=_do_init							)
      def SCREAMING_SNAKE_CASE_	(		self	:	Any      ,       A_	:	jax.random.KeyArray      ,       A_	:	Tuple      ,       A_	:	FrozenDict = None							):






       '''simple docstring'''


       __lowercase									=	jax.random.normal(A_      ,       A_							)

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

       __lowercase									=	self.module.init(A_      ,       A_							)["""params"""]

       return random_params






      def __call__(		self	:	Any      ,       A_	:	Tuple      ,       A_	:	dict = None      ,       ):






       '''simple docstring'''


       __lowercase									=	jnp.transpose(A_      ,       (0, 2, 3, 1)							)

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




"""simple docstring"""

from typing import TYPE_CHECKING

from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


UpperCAmelCase__  							={"configuration_van": ["VAN_PRETRAINED_CONFIG_ARCHIVE_MAP", "VanConfig"]}


try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       UpperCAmelCase__  							=[
           "VAN_PRETRAINED_MODEL_ARCHIVE_LIST",
           "VanForImageClassification",
           "VanModel",
           "VanPreTrainedModel",
       ]

if TYPE_CHECKING:
       from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_van import (
                  VAN_PRETRAINED_MODEL_ARCHIVE_LIST,
                  VanForImageClassification,
                  VanModel,
                  VanPreTrainedModel,
              )

else:
       import sys

       UpperCAmelCase__  							=_LazyModule(__name__, globals()["__file__"], _import_structure)
