


"""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_      (      _lowerCAmelCase   :    str,   _lowerCAmelCase   :    List[Any],   _lowerCAmelCase   :    Dict=1e-1_2				):






     """simple docstring"""

     _a					= jnp.divide(emb_a.T,   jnp.clip(jnp.linalg.norm(__lowerCAmelCase,   axis=1				),   a_min=__lowerCAmelCase				)				).T
     _a					= 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 ):

     '''simple docstring'''
     A_				:		CLIPConfig
     A_				:		jnp.dtype			=						jnp.floataa


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

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

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

          return has_nsfw_concepts







class 			__lowerCamelCase     (    __lowercase ):

     '''simple docstring'''
     A_				:		List[str]			=						CLIPConfig
     A_				:		List[Any]			=						"""clip_input"""
     A_				:		Union[str, Any]			=						FlaxStableDiffusionSafetyCheckerModule


     def __init__(					self			, __UpperCAmelCase			, __UpperCAmelCase = None			, __UpperCAmelCase = 0			, __UpperCAmelCase = jnp.floataa			, __UpperCAmelCase = True			, **__UpperCAmelCase			, )				->							Optional[Any]:
          if input_shape is None:
               _a					= (1, 224, 224, 3)
          _a					= 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 							_UpperCAmelCase					(					self			, __UpperCAmelCase			, __UpperCAmelCase			, __UpperCAmelCase = None							)				->							FrozenDict:
          # init input tensor
          _a					= jax.random.normal(SCREAMING_SNAKE_CASE__			, SCREAMING_SNAKE_CASE__							)

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

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

          return random_params





     def __call__(					self			, __UpperCAmelCase			, __UpperCAmelCase = None			, )				->							Optional[int]:
          _a					= 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 Optional

from .. import Features, NamedSplit
from ..packaged_modules.text.text import Text
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader

class    lowerCAmelCase__     (	__lowercase			):






		def __init__(		self		:							Tuple							,			SCREAMING_SNAKE_CASE__		:							NestedDataStructureLike[PathLike]							,			SCREAMING_SNAKE_CASE__		:							Optional[NamedSplit] = None							,			SCREAMING_SNAKE_CASE__		:							Optional[Features] = None							,			SCREAMING_SNAKE_CASE__		:							str = None							,			SCREAMING_SNAKE_CASE__		:							bool = False							,			SCREAMING_SNAKE_CASE__		:							bool = False							,			SCREAMING_SNAKE_CASE__		:							Optional[int] = None							,			**SCREAMING_SNAKE_CASE__		:							str							,			)     ->							Union[str, Any]:
						super().__init__(
						    SCREAMING_SNAKE_CASE__							,			split=SCREAMING_SNAKE_CASE__							,			features=SCREAMING_SNAKE_CASE__							,			cache_dir=SCREAMING_SNAKE_CASE__							,			keep_in_memory=SCREAMING_SNAKE_CASE__							,			streaming=SCREAMING_SNAKE_CASE__							,			num_proc=SCREAMING_SNAKE_CASE__							,			**SCREAMING_SNAKE_CASE__							,			)
						__lowerCamelCase    					=	path_or_paths if isinstance(SCREAMING_SNAKE_CASE__							,			SCREAMING_SNAKE_CASE__  ) else {self.split: path_or_paths}
						__lowerCamelCase    					=	Text(
						    cache_dir=SCREAMING_SNAKE_CASE__							,			data_files=SCREAMING_SNAKE_CASE__							,			features=SCREAMING_SNAKE_CASE__							,			**SCREAMING_SNAKE_CASE__							,			)







		def  __A       (		self		:							int  )     ->							Dict:
						# Build iterable dataset
						if self.streaming:
										__lowerCamelCase    					=	self.builder.as_streaming_dataset(split=self.split  )
						# Build regular (map-style) dataset
						else:
										__lowerCamelCase    					=	None
										__lowerCamelCase    					=	None
										__lowerCamelCase    					=	None
										__lowerCamelCase    					=	None

										self.builder.download_and_prepare(
										    download_config=SCREAMING_SNAKE_CASE__							,			download_mode=SCREAMING_SNAKE_CASE__							,			verification_mode=SCREAMING_SNAKE_CASE__							,			base_path=SCREAMING_SNAKE_CASE__							,			num_proc=self.num_proc							,			)
										__lowerCamelCase    					=	self.builder.as_dataset(
										    split=self.split							,			verification_mode=SCREAMING_SNAKE_CASE__							,			in_memory=self.keep_in_memory  )
						return dataset



