

'''simple docstring'''



from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union

import pyarrow as pa


if TYPE_CHECKING:
   from .features import FeatureType

@dataclass
class       SCREAMING_SNAKE_CASE       :






      '''simple docstring'''






      SCREAMING_SNAKE_CASE__			:					List[str]
      SCREAMING_SNAKE_CASE__			:					Optional[str]     =					None
      # Automatically constructed
      SCREAMING_SNAKE_CASE__			:					ClassVar[str]     =					"dict"
      SCREAMING_SNAKE_CASE__			:					ClassVar[Any]     =					None
      SCREAMING_SNAKE_CASE__			:					str     =					field(default='''Translation'''   ,init=__snake_case   ,repr=__snake_case       )




      def __call__(       self			:		Dict ):



          """simple docstring"""





          return pa.struct({lang: pa.string() for lang in sorted(self.languages )} )




      def 						__UpperCAmelCase      (       self			:		Optional[Any] ):



          """simple docstring"""





          from .features import Value

          return {k: Value('string' ) for k in sorted(self.languages )}



@dataclass
class       SCREAMING_SNAKE_CASE       :






      '''simple docstring'''






      SCREAMING_SNAKE_CASE__			:					Optional[List]     =					None
      SCREAMING_SNAKE_CASE__			:					Optional[int]     =					None
      SCREAMING_SNAKE_CASE__			:					Optional[str]     =					None
      # Automatically constructed
      SCREAMING_SNAKE_CASE__			:					ClassVar[str]     =					"dict"
      SCREAMING_SNAKE_CASE__			:					ClassVar[Any]     =					None
      SCREAMING_SNAKE_CASE__			:					str     =					field(default='''TranslationVariableLanguages'''   ,init=__snake_case   ,repr=__snake_case       )




      def 						__UpperCAmelCase      (       self			:		int ):



          """simple docstring"""





          _snake_case			:			Union[str, Any]				       =		sorted(set(self.languages ) ) if self.languages else None
          _snake_case			:			str				       =		len(self.languages ) if self.languages else None




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



          """simple docstring"""





          return pa.struct({'language': pa.list_(pa.string() ), 'translation': pa.list_(pa.string() )} )




      def 						__UpperCAmelCase      (       self			:		int  ,       snake_case			:		Dict ):



          """simple docstring"""





          _snake_case			:			Any				       =		set(self.languages )
          if self.languages and set(snake_case ) - lang_set:
              raise ValueError(
                  F"""Some languages in example ({', '.join(sorted(set(snake_case ) - lang_set ) )}) are not in valid set ({', '.join(snake_case )}).""" )

          # Convert dictionary into tuples, splitting out cases where there are
          # multiple translations for a single language.
          _snake_case			:			int				       =		[]
          for lang, text in translation_dict.items():
              if isinstance(snake_case  ,       snake_case ):
                  translation_tuples.append((lang, text) )
              else:
                  translation_tuples.extend([(lang, el) for el in text] )

        # Ensure translations are in ascending order by language code.
          _snake_case       ,				_snake_case			:			Union[str, Any]				       =		zip(*sorted(snake_case ) )

          return {"language": languages, "translation": translations}




      def 						__UpperCAmelCase      (       self			:		int ):



          """simple docstring"""





          from .features import Sequence, Value

          return {
              "language": Sequence(Value('string' ) ),
              "translation": Sequence(Value('string' ) ),
          }







"""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      UpperCAmelCase     (       _lowercase :   str			,   _lowercase :   int			,   _lowercase :   Optional[int]=1E-12	)						-> List[str]:


	"""simple docstring"""




	lowerCAmelCase_      							=			jnp.divide(emb_a.T			,   jnp.clip(jnp.linalg.norm(_lowercase			,   axis=1	)			,   a_min=_lowercase	)	).T
	lowerCAmelCase_      							=			jnp.divide(emb_a.T			,   jnp.clip(jnp.linalg.norm(_lowercase			,   axis=1	)			,   a_min=_lowercase	)	).T
	return jnp.matmul(_lowercase			,   norm_emb_a.T	)







class    __a						( nn.Module							):
				lowerCamelCase     :       CLIPConfig
				lowerCamelCase     :       jnp.dtype			       =jnp.floataa







				def      lowerCamelCase_     ( self   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			FlaxCLIPVisionModule(self.config.vision_config   )
					lowerCAmelCase_      							=			nn.Dense(self.config.projection_dim      ,	use_bias=UpperCAmelCase      ,	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      ,	UpperCAmelCase   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			self.vision_model(UpperCAmelCase   )[1]
					lowerCAmelCase_      							=			self.visual_projection(UpperCAmelCase   )

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

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

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

					return has_nsfw_concepts







class    __a						( __snake_case							):
				lowerCamelCase     :       Optional[Any]			       =CLIPConfig
				lowerCamelCase     :       List[str]			       ='clip_input'
				lowerCamelCase     :       int			       =FlaxStableDiffusionSafetyCheckerModule







				def __init__( self      ,	UpperCAmelCase      ,	UpperCAmelCase = None      ,	UpperCAmelCase = 0      ,	UpperCAmelCase = jnp.floataa      ,	UpperCAmelCase = True      ,	**UpperCAmelCase      ,	):

					'''simple docstring'''






					if input_shape is None:
						lowerCAmelCase_      							=			(1, 224, 224, 3)
					lowerCAmelCase_      							=			self.module_class(config=UpperCAmelCase      ,	dtype=UpperCAmelCase      ,	**UpperCAmelCase   )
					super().__init__(UpperCAmelCase      ,	UpperCAmelCase      ,	input_shape=UpperCAmelCase      ,	seed=UpperCAmelCase      ,	dtype=UpperCAmelCase      ,	_do_init=_do_init   )







				def      lowerCamelCase_     ( self      ,	UpperCAmelCase      ,	UpperCAmelCase      ,	UpperCAmelCase = None   ):

					'''simple docstring'''






					lowerCAmelCase_      							=			jax.random.normal(UpperCAmelCase      ,	UpperCAmelCase   )

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

					lowerCAmelCase_      							=			self.module.init(UpperCAmelCase      ,	UpperCAmelCase   )['''params''']

					return random_params







				def __call__( self      ,	UpperCAmelCase      ,	UpperCAmelCase = None      ,	):

					'''simple docstring'''






					lowerCAmelCase_      							=			jnp.transpose(UpperCAmelCase      ,	(0, 2, 3, 1)   )

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