




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 		a_							( __lowerCAmelCase   , __lowerCAmelCase   , __lowerCAmelCase=1E-12				):
  lowerCAmelCase__										=      jnp.divide(emb_a.T   , jnp.clip(jnp.linalg.norm(__lowerCAmelCase   , axis=1				)   , a_min=__lowerCAmelCase				)				).T
  lowerCAmelCase__										=      jnp.divide(emb_a.T   , jnp.clip(jnp.linalg.norm(__lowerCAmelCase   , axis=1				)   , a_min=__lowerCAmelCase				)				).T
  return jnp.matmul(__lowerCAmelCase   , norm_emb_a.T				)





class     SCREAMING_SNAKE_CASE__		(nn.Module			):
     lowercase_ :      CLIPConfig
     lowercase_ :      jnp.dtype				= jnp.floataa
     def        A__      (						self	:		int						):



       """simple docstring"""
       lowerCAmelCase__										=      FlaxCLIPVisionModule(self.config.vision_config						)
       lowerCAmelCase__										=      nn.Dense(self.config.projection_dim       ,						use_bias=__lowerCamelCase       ,						dtype=self.dtype						)

       lowerCAmelCase__										=      self.param('''concept_embeds'''       ,						jax.nn.initializers.ones       ,						(17, self.config.projection_dim)						)
       lowerCAmelCase__										=      self.param(
           '''special_care_embeds'''       ,						jax.nn.initializers.ones       ,						(3, self.config.projection_dim)						)

       lowerCAmelCase__										=      self.param('''concept_embeds_weights'''       ,						jax.nn.initializers.ones       ,						(17,)						)
       lowerCAmelCase__										=      self.param('''special_care_embeds_weights'''       ,						jax.nn.initializers.ones       ,						(3,)						)



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



       """simple docstring"""
       lowerCAmelCase__										=      self.vision_model(__lowerCamelCase						)[1]
       lowerCAmelCase__										=      self.visual_projection(__lowerCamelCase						)

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

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

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

       return has_nsfw_concepts





class     SCREAMING_SNAKE_CASE__		(_a			):
     lowercase_ :      Tuple				= CLIPConfig
     lowercase_ :      Union[str, Any]				= "clip_input"
     lowercase_ :      Any				= FlaxStableDiffusionSafetyCheckerModule
     def __init__(						self	:		str       ,						__lowerCamelCase	:		CLIPConfig       ,						__lowerCamelCase	:		Optional[Tuple] = None       ,						__lowerCamelCase	:		int = 0       ,						__lowerCamelCase	:		jnp.dtype = jnp.floataa       ,						__lowerCamelCase	:		bool = True       ,						**__lowerCamelCase	:		Dict       ,						):



       """simple docstring"""
       if input_shape is None:
         lowerCAmelCase__										=      (1, 2_24, 2_24, 3)
       lowerCAmelCase__										=      self.module_class(config=__lowerCamelCase       ,						dtype=__lowerCamelCase       ,						**__lowerCamelCase						)
       super().__init__(__lowerCamelCase       ,						__lowerCamelCase       ,						input_shape=__lowerCamelCase       ,						seed=__lowerCamelCase       ,						dtype=__lowerCamelCase       ,						_do_init=_do_init						)
     def        A__      (						self	:		Tuple       ,						__lowerCamelCase	:		jax.random.KeyArray       ,						__lowerCamelCase	:		Tuple       ,						__lowerCamelCase	:		FrozenDict = None						):



       """simple docstring"""
       # init input tensor
       lowerCAmelCase__										=      jax.random.normal(__lowerCamelCase       ,						__lowerCamelCase						)

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

       lowerCAmelCase__										=      self.module.init(__lowerCamelCase       ,						__lowerCamelCase						)['''params''']

       return random_params



     def __call__(						self	:		List[Any]       ,						__lowerCamelCase	:		str       ,						__lowerCamelCase	:		dict = None       ,						):



       """simple docstring"""
       lowerCAmelCase__										=      jnp.transpose(__lowerCamelCase       ,						(0, 2, 3, 1)						)

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







from typing import TYPE_CHECKING

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


__magic_name__  :  Union[str, Any]					=       {
    """configuration_altclip""": [
        """ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """AltCLIPConfig""",
        """AltCLIPTextConfig""",
        """AltCLIPVisionConfig""",
    ],
    """processing_altclip""": ["""AltCLIPProcessor"""],
}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __magic_name__  :  str					=       [
          """ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """AltCLIPPreTrainedModel""",
          """AltCLIPModel""",
          """AltCLIPTextModel""",
          """AltCLIPVisionModel""",
      ]


if TYPE_CHECKING:
      from .configuration_altclip import (
          ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
          AltCLIPConfig,
          AltCLIPTextConfig,
          AltCLIPVisionConfig,
      )
      from .processing_altclip import AltCLIPProcessor

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_altclip import (
                ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
                AltCLIPModel,
                AltCLIPPreTrainedModel,
                AltCLIPTextModel,
                AltCLIPVisionModel,
            )


else:
      import sys

      __magic_name__  :  str					=       _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

