
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  __magic_name__ (   __lowerCAmelCase	:						str		,  __lowerCAmelCase	:						List[Any]		,  __lowerCAmelCase	:						Dict=1E-12							)			->   Any:
				__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    lowerCAmelCase__     (	nn.Module			):
		a__       :						CLIPConfig
		a__       :						jnp.dtype        =		jnp.floataa






		def  __A       (		self		:							int  )     ->							List[str]:
						__lowerCamelCase    					=	FlaxCLIPVisionModule(self.config.vision_config  )
						__lowerCamelCase    					=	nn.Dense(self.config.projection_dim							,			use_bias=SCREAMING_SNAKE_CASE__							,			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[Any]							,			SCREAMING_SNAKE_CASE__		:							List[str]  )     ->							Tuple:
						__lowerCamelCase    					=	self.vision_model(SCREAMING_SNAKE_CASE__  )[1]
						__lowerCamelCase    					=	self.visual_projection(SCREAMING_SNAKE_CASE__  )

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

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

						return has_nsfw_concepts





class    lowerCAmelCase__     (	__lowercase			):
		a__       :						List[str]        =		CLIPConfig
		a__       :						List[Any]        =		"""clip_input"""
		a__       :						Union[str, Any]        =		FlaxStableDiffusionSafetyCheckerModule






		def __init__(		self		:							Optional[int]							,			SCREAMING_SNAKE_CASE__		:							CLIPConfig							,			SCREAMING_SNAKE_CASE__		:							Optional[Tuple] = None							,			SCREAMING_SNAKE_CASE__		:							int = 0							,			SCREAMING_SNAKE_CASE__		:							jnp.dtype = jnp.floataa							,			SCREAMING_SNAKE_CASE__		:							bool = True							,			**SCREAMING_SNAKE_CASE__		:							str							,			)     ->							Optional[Any]:
						if input_shape is None:
										__lowerCamelCase    					=	(1, 2_24, 2_24, 3)
						__lowerCamelCase    					=	self.module_class(config=SCREAMING_SNAKE_CASE__							,			dtype=SCREAMING_SNAKE_CASE__							,			**SCREAMING_SNAKE_CASE__  )
						super().__init__(SCREAMING_SNAKE_CASE__							,			SCREAMING_SNAKE_CASE__							,			input_shape=SCREAMING_SNAKE_CASE__							,			seed=SCREAMING_SNAKE_CASE__							,			dtype=SCREAMING_SNAKE_CASE__							,			_do_init=_do_init  )






		def  __A       (		self		:							Union[str, Any]							,			SCREAMING_SNAKE_CASE__		:							jax.random.KeyArray							,			SCREAMING_SNAKE_CASE__		:							Tuple							,			SCREAMING_SNAKE_CASE__		:							FrozenDict = None  )     ->							FrozenDict:
						# init input tensor
						__lowerCamelCase    					=	jax.random.normal(SCREAMING_SNAKE_CASE__							,			SCREAMING_SNAKE_CASE__  )

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

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

						return random_params







		def __call__(		self		:							Optional[Any]							,			SCREAMING_SNAKE_CASE__		:							List[str]							,			SCREAMING_SNAKE_CASE__		:							dict = None							,			)     ->							Optional[int]:
						__lowerCamelCase    					=	jnp.transpose(SCREAMING_SNAKE_CASE__							,			(0, 2, 3, 1)  )

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





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


SCREAMING_SNAKE_CASE__   :			List[str]												=    {
    "configuration_blip": [
        "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "BlipConfig",
        "BlipTextConfig",
        "BlipVisionConfig",
    ],
    "processing_blip": ["BlipProcessor"],
}

try:
					if not is_vision_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__   :			str												=    ["BlipImageProcessor"]


try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__   :			int												=    [
					    "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
					    "BlipModel",
					    "BlipPreTrainedModel",
					    "BlipForConditionalGeneration",
					    "BlipForQuestionAnswering",
					    "BlipVisionModel",
					    "BlipTextModel",
					    "BlipForImageTextRetrieval",
					]

try:
					if not is_tf_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					SCREAMING_SNAKE_CASE__   :			Any												=    [
					    "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
					    "TFBlipModel",
					    "TFBlipPreTrainedModel",
					    "TFBlipForConditionalGeneration",
					    "TFBlipForQuestionAnswering",
					    "TFBlipVisionModel",
					    "TFBlipTextModel",
					    "TFBlipForImageTextRetrieval",
					]

if TYPE_CHECKING:
					from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig
					from .processing_blip import BlipProcessor

					try:
										if not is_vision_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .image_processing_blip import BlipImageProcessor

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_blip import (
										    BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
										    BlipForConditionalGeneration,
										    BlipForImageTextRetrieval,
										    BlipForQuestionAnswering,
										    BlipModel,
										    BlipPreTrainedModel,
										    BlipTextModel,
										    BlipVisionModel,
										)

					try:
										if not is_tf_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_tf_blip import (
										    TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
										    TFBlipForConditionalGeneration,
										    TFBlipForImageTextRetrieval,
										    TFBlipForQuestionAnswering,
										    TFBlipModel,
										    TFBlipPreTrainedModel,
										    TFBlipTextModel,
										    TFBlipVisionModel,
										)

else:
					import sys

					SCREAMING_SNAKE_CASE__   :			Tuple												=    _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



