

'''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  a__       (    _SCREAMING_SNAKE_CASE   :       List[str]	,				_SCREAMING_SNAKE_CASE   :       Dict	,				_SCREAMING_SNAKE_CASE   :       List[Any]=1E-12				)     ->					List[str]:


	"""simple docstring"""





	UpperCAmelCase_     :      str						=  jnp.divide(emb_a.T	,				jnp.clip(jnp.linalg.norm(__a	,				axis=1				)	,				a_min=__a				)				).T
	UpperCAmelCase_     :      Optional[int]						=  jnp.divide(emb_a.T	,				jnp.clip(jnp.linalg.norm(__a	,				axis=1				)	,				a_min=__a				)				).T
	return jnp.matmul(__a	,				norm_emb_a.T				)
class 					_snake_case		(nn.Module):
			__A  :	List[str]        =42
			__A  :	int        =jnp.floataa






			def 		UpperCamelCase__							(  self     ):
				UpperCAmelCase_     :      Optional[int]						=  FlaxCLIPVisionModule(self.config.vision_config     )
				UpperCAmelCase_     :      Optional[int]						=  nn.Dense(self.config.projection_dim			,use_bias=_snake_case			,dtype=self.dtype     )

				UpperCAmelCase_     :      List[str]						=  self.param("concept_embeds"			,jax.nn.initializers.ones			,(17, self.config.projection_dim)     )
				UpperCAmelCase_     :      Optional[Any]						=  self.param(
				    "special_care_embeds"			,jax.nn.initializers.ones			,(3, self.config.projection_dim)     )

				UpperCAmelCase_     :      int						=  self.param("concept_embeds_weights"			,jax.nn.initializers.ones			,(17,)     )
				UpperCAmelCase_     :      Dict						=  self.param("special_care_embeds_weights"			,jax.nn.initializers.ones			,(3,)     )






			def __call__(  self			,_snake_case     ):
				UpperCAmelCase_     :      Optional[Any]						=  self.vision_model(_snake_case     )[1]
				UpperCAmelCase_     :      Union[str, Any]						=  self.visual_projection(_snake_case     )

				UpperCAmelCase_     :      Union[str, Any]						=  jax_cosine_distance(_snake_case			,self.special_care_embeds     )
				UpperCAmelCase_     :      Optional[int]						=  jax_cosine_distance(_snake_case			,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_     :      Any						=  0.0

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

				UpperCAmelCase_     :      Tuple						=  cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
				UpperCAmelCase_     :      int						=  jnp.round(_snake_case			,3     )
				UpperCAmelCase_     :      Any						=  jnp.any(concept_scores > 0			,axis=1     )

				return has_nsfw_concepts




class 					_snake_case		(_lowercase):
			__A  :	List[str]        =CLIPConfig
			__A  :	Tuple        ="clip_input"
			__A  :	List[str]        =FlaxStableDiffusionSafetyCheckerModule






			def __init__(  self			,_snake_case			,_snake_case = None			,_snake_case = 0			,_snake_case = jnp.floataa			,_snake_case = True			,**_snake_case			,):
				if input_shape is None:
					UpperCAmelCase_     :      Tuple						=  (1, 2_24, 2_24, 3)
				UpperCAmelCase_     :      List[str]						=  self.module_class(config=_snake_case			,dtype=_snake_case			,**_snake_case     )
				super().__init__(_snake_case			,_snake_case			,input_shape=_snake_case			,seed=_snake_case			,dtype=_snake_case			,_do_init=_do_init     )






			def 		UpperCamelCase__							(  self			,_snake_case			,_snake_case			,_snake_case = None     ):
				UpperCAmelCase_     :      Optional[int]						=  jax.random.normal(_snake_case			,_snake_case     )

				UpperCAmelCase_					,					UpperCAmelCase_     :      Dict						=  jax.random.split(_snake_case     )
				UpperCAmelCase_     :      Tuple						=  {"params": params_rng, "dropout": dropout_rng}

				UpperCAmelCase_     :      int						=  self.module.init(_snake_case			,_snake_case     )["params"]

				return random_params






			def __call__(  self			,_snake_case			,_snake_case = None			,):
				UpperCAmelCase_     :      List[Any]						=  jnp.transpose(_snake_case			,(0, 2, 3, 1)     )

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






"""simple docstring"""





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


UpperCamelCase_       :    List[str]						      =			{'''configuration_sew''': ['''SEW_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SEWConfig''']}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCamelCase_       :    Tuple						      =			[
		    '''SEW_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''SEWForCTC''',
		    '''SEWForSequenceClassification''',
		    '''SEWModel''',
		    '''SEWPreTrainedModel''',
		]

if TYPE_CHECKING:
		from .configuration_sew import SEW_PRETRAINED_CONFIG_ARCHIVE_MAP, SEWConfig

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_sew import (
				    SEW_PRETRAINED_MODEL_ARCHIVE_LIST,
				    SEWForCTC,
				    SEWForSequenceClassification,
				    SEWModel,
				    SEWPreTrainedModel,
				)


else:
		import sys

		UpperCamelCase_       :    List[str]						      =			_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)




