

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__		(    lowerCamelCase_     ,				lowerCamelCase_     ,				lowerCamelCase_=1E-12		):
							A      :					str      		=					jnp.divide(emb_a.T     ,				jnp.clip(jnp.linalg.norm(lowerCamelCase_     ,				axis=1		)     ,				a_min=lowerCamelCase_		)		).T
							A      :					Optional[int]      		=					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 					__lowercase  (						nn.Module				):





							"""simple docstring"""

							UpperCAmelCase_						:		CLIPConfig
							UpperCAmelCase_						:		jnp.dtype								=	jnp.floataa




							def       snake_case			(					self						)		->       List[str]:
														A      :					Optional[int]      		=					FlaxCLIPVisionModule(self.config.vision_config						)
														A      :					Union[str, Any]      		=					nn.Dense(self.config.projection_dim    ,						use_bias=__UpperCAmelCase    ,						dtype=self.dtype						)

														A      :					Optional[Any]      		=					self.param('''concept_embeds'''    ,						jax.nn.initializers.ones    ,						(17, self.config.projection_dim)						)
														A      :					Tuple      		=					self.param(
														    '''special_care_embeds'''    ,						jax.nn.initializers.ones    ,						(3, self.config.projection_dim)						)

														A      :					List[Any]      		=					self.param('''concept_embeds_weights'''    ,						jax.nn.initializers.ones    ,						(17,)						)
														A      :					Dict      		=					self.param('''special_care_embeds_weights'''    ,						jax.nn.initializers.ones    ,						(3,)						)






							def __call__(					self    ,						__UpperCAmelCase						)		->       int:
														A      :					Dict      		=					self.vision_model(__UpperCAmelCase						)[1]
														A      :					Dict      		=					self.visual_projection(__UpperCAmelCase						)

														A      :					Optional[Any]      		=					jax_cosine_distance(__UpperCAmelCase    ,						self.special_care_embeds						)
														A      :					int      		=					jax_cosine_distance(__UpperCAmelCase    ,						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      :					List[Any]      		=					0.0

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

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

														return has_nsfw_concepts







class 					__lowercase  (						_SCREAMING_SNAKE_CASE				):





							"""simple docstring"""

							UpperCAmelCase_						:		List[str]								=	CLIPConfig
							UpperCAmelCase_						:		Union[str, Any]								=	'''clip_input'''
							UpperCAmelCase_						:		Any								=	FlaxStableDiffusionSafetyCheckerModule




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




							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase = None						)		->       FrozenDict:
														# init input tensor
														A      :					Dict      		=					jax.random.normal(__UpperCAmelCase    ,						__UpperCAmelCase						)

														A		,		A      :					Optional[Any]      		=					jax.random.split(__UpperCAmelCase						)
														A      :					Optional[Any]      		=					{'''params''': params_rng, '''dropout''': dropout_rng}

														A      :					Tuple      		=					self.module.init(__UpperCAmelCase    ,						__UpperCAmelCase						)['''params''']

														return random_params






							def __call__(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase = None    ,						)		->       Tuple:
														A      :					Any      		=					jnp.transpose(__UpperCAmelCase    ,						(0, 2, 3, 1)						)

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









import unittest

from transformers import load_tool
from transformers.utils import is_torch_available


if is_torch_available():
		import torch

from transformers.testing_utils import require_torch

from .test_tools_common import ToolTesterMixin







@require_torch
class 					__lowercase  (						unittest.TestCase		,       _SCREAMING_SNAKE_CASE				):





							"""simple docstring"""

							def       snake_case			(					self						)		->       Optional[Any]:
														A      :					Optional[Any]      		=					load_tool('''text-to-speech'''						)
														self.tool.setup()




							def       snake_case			(					self						)		->       Union[str, Any]:
														# SpeechT5 isn't deterministic
														torch.manual_seed(0						)
														A      :					Optional[Any]      		=					self.tool('''hey'''						)
														A      :					List[str]      		=					result.to_raw()
														self.assertTrue(
														    torch.allclose(
														        resulting_tensor[:3]    ,						torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5]						)    ,						)						)






							def       snake_case			(					self						)		->       Optional[Any]:
														# SpeechT5 isn't deterministic
														torch.manual_seed(0						)
														A      :					int      		=					self.tool('''hey'''						)
														A      :					Any      		=					result.to_raw()
														self.assertTrue(
														    torch.allclose(
														        resulting_tensor[:3]    ,						torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5]						)    ,						)						)






