
"""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       _snake_case				(		snake_case__   :     List[Any]	,      snake_case__   :     Any	,      snake_case__   :     int=1e-12     ):
	A						   =   jnp.divide(emb_a.T	,      jnp.clip(jnp.linalg.norm(snake_case__	,      axis=1     )	,      a_min=snake_case__     )     ).T
	A						   =   jnp.divide(emb_a.T	,      jnp.clip(jnp.linalg.norm(snake_case__	,      axis=1     )	,      a_min=snake_case__     )     ).T
	return jnp.matmul(snake_case__	,      norm_emb_a.T     )







class 				lowerCAmelCase_				(      nn.Module    ):



						'''simple docstring'''


						_lowerCamelCase:    CLIPConfig
						_lowerCamelCase:    jnp.dtype      =    jnp.floataa


						def 						_SCREAMING_SNAKE_CASE      ( self     :      Tuple      )     ->   Dict:
							A						   =   FlaxCLIPVisionModule(self.config.vision_config      )
							A						   =   nn.Dense(self.config.projection_dim  ,use_bias=A_  ,dtype=self.dtype      )

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

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




						def __call__( self     :      Optional[int]  ,A_     :      str      )     ->   Optional[Any]:
							A						   =   self.vision_model(A_      )[1]
							A						   =   self.visual_projection(A_      )

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

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

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

							return has_nsfw_concepts







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    Optional[Any]      =    CLIPConfig
						_lowerCamelCase:    Dict      =    '''clip_input'''
						_lowerCamelCase:    str      =    FlaxStableDiffusionSafetyCheckerModule


						def __init__( self     :      Union[str, Any]  ,A_     :      CLIPConfig  ,A_     :      Optional[Tuple] = None  ,A_     :      int = 0  ,A_     :      jnp.dtype = jnp.floataa  ,A_     :      bool = True  ,**A_     :      str  ,)     ->   int:
							if input_shape is None:
								A						   =   (1, 224, 224, 3)
							A						   =   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     :      str  ,A_     :      jax.random.KeyArray  ,A_     :      Tuple  ,A_     :      FrozenDict = None      )     ->   FrozenDict:
							# init input tensor
							A						   =   jax.random.normal(A_  ,A_      )

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

							A						   =   self.module.init(A_  ,A_      )['params']

							return random_params




						def __call__( self     :      str  ,A_     :      Optional[Any]  ,A_     :      dict = None  ,)     ->   List[str]:
							A						   =   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_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


_lowercase							   =				{
    '''configuration_clip''': [
        '''CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''CLIPConfig''',
        '''CLIPOnnxConfig''',
        '''CLIPTextConfig''',
        '''CLIPVisionConfig''',
    ],
    '''processing_clip''': ['''CLIPProcessor'''],
    '''tokenization_clip''': ['''CLIPTokenizer'''],
}

try:
		if not is_tokenizers_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		_lowercase							   =				['''CLIPTokenizerFast''']

try:
		if not is_vision_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		_lowercase							   =				['''CLIPFeatureExtractor''']
		_lowercase							   =				['''CLIPImageProcessor''']

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		_lowercase							   =				[
		    '''CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''CLIPModel''',
		    '''CLIPPreTrainedModel''',
		    '''CLIPTextModel''',
		    '''CLIPTextModelWithProjection''',
		    '''CLIPVisionModel''',
		    '''CLIPVisionModelWithProjection''',
		]

try:
		if not is_tf_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		_lowercase							   =				[
		    '''TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''TFCLIPModel''',
		    '''TFCLIPPreTrainedModel''',
		    '''TFCLIPTextModel''',
		    '''TFCLIPVisionModel''',
		]

try:
		if not is_flax_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		_lowercase							   =				[
		    '''FlaxCLIPModel''',
		    '''FlaxCLIPPreTrainedModel''',
		    '''FlaxCLIPTextModel''',
		    '''FlaxCLIPTextPreTrainedModel''',
		    '''FlaxCLIPVisionModel''',
		    '''FlaxCLIPVisionPreTrainedModel''',
		]


if TYPE_CHECKING:
		from .configuration_clip import (
		    CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
		    CLIPConfig,
		    CLIPOnnxConfig,
		    CLIPTextConfig,
		    CLIPVisionConfig,
		)
		from .processing_clip import CLIPProcessor
		from .tokenization_clip import CLIPTokenizer

		try:
				if not is_tokenizers_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .tokenization_clip_fast import CLIPTokenizerFast

		try:
				if not is_vision_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .feature_extraction_clip import CLIPFeatureExtractor
				from .image_processing_clip import CLIPImageProcessor

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_clip import (
				    CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
				    CLIPModel,
				    CLIPPreTrainedModel,
				    CLIPTextModel,
				    CLIPTextModelWithProjection,
				    CLIPVisionModel,
				    CLIPVisionModelWithProjection,
				)

		try:
				if not is_tf_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_tf_clip import (
				    TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TFCLIPModel,
				    TFCLIPPreTrainedModel,
				    TFCLIPTextModel,
				    TFCLIPVisionModel,
				)

		try:
				if not is_flax_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_flax_clip import (
				    FlaxCLIPModel,
				    FlaxCLIPPreTrainedModel,
				    FlaxCLIPTextModel,
				    FlaxCLIPTextPreTrainedModel,
				    FlaxCLIPVisionModel,
				    FlaxCLIPVisionPreTrainedModel,
				)


else:
		import sys

		_lowercase							   =				_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)