





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     lowerCamelCase_	(      lowerCAmelCase:	List[str]    ,							lowerCAmelCase:	str    ,							lowerCAmelCase:	Tuple=1E-12				)->		int:
  _snake_case   :				List[Any]														=	jnp.divide(emb_a.T    ,							jnp.clip(jnp.linalg.norm(lowerCAmelCase    ,							axis=1				)    ,							a_min=lowerCAmelCase				)				).T
  _snake_case   :				Tuple														=	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      :					Optional[Any]							):


    '''simple docstring'''





    _snake_case   :				Optional[Any]														=	FlaxCLIPVisionModule(self.config.vision_config							)
    _snake_case   :				Optional[Any]														=	nn.Dense(self.config.projection_dim      ,				use_bias=UpperCamelCase      ,				dtype=self.dtype							)

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

    _snake_case   :				Optional[int]														=	self.param('concept_embeds_weights'      ,				jax.nn.initializers.ones      ,				(17,)							)
    _snake_case   :				Union[str, Any]														=	self.param('special_care_embeds_weights'      ,				jax.nn.initializers.ones      ,				(3,)							)







  def __call__(      self      :					Tuple      ,				UpperCamelCase      :					List[Any]							):


    '''simple docstring'''





    _snake_case   :				int														=	self.vision_model(UpperCamelCase							)[1]
    _snake_case   :				Any														=	self.visual_projection(UpperCamelCase							)

    _snake_case   :				int														=	jax_cosine_distance(UpperCamelCase      ,				self.special_care_embeds							)
    _snake_case   :				List[str]														=	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
    _snake_case   :				List[str]														=	0.0

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

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

    return has_nsfw_concepts




class        _lowerCAmelCase    (			UpperCAmelCase_							):


  '''simple docstring'''
  a_							:       int      					=CLIPConfig
  a_							:       str      					="""clip_input"""
  a_							:       Dict      					=FlaxStableDiffusionSafetyCheckerModule







  def __init__(      self      :					List[Any]      ,				UpperCamelCase      :					CLIPConfig      ,				UpperCamelCase      :					Optional[Tuple] = None      ,				UpperCamelCase      :					int = 0      ,				UpperCamelCase      :					jnp.dtype = jnp.floataa      ,				UpperCamelCase      :					bool = True      ,				**UpperCamelCase      :					Optional[int]      ,				):


    '''simple docstring'''





    if input_shape is None:
      _snake_case   :				Optional[int]														=	(1, 2_24, 2_24, 3)
    _snake_case   :				int														=	self.module_class(config=UpperCamelCase      ,				dtype=UpperCamelCase      ,				**UpperCamelCase							)
    super().__init__(UpperCamelCase      ,				UpperCamelCase      ,				input_shape=UpperCamelCase      ,				seed=UpperCamelCase      ,				dtype=UpperCamelCase      ,				_do_init=_do_init							)







  def UpperCamelCase_ (      self      :					Dict      ,				UpperCamelCase      :					jax.random.KeyArray      ,				UpperCamelCase      :					Tuple      ,				UpperCamelCase      :					FrozenDict = None							):


    '''simple docstring'''





    _snake_case   :				List[str]														=	jax.random.normal(UpperCamelCase      ,				UpperCamelCase							)

    _snake_case							,					_snake_case   :				Tuple														=	jax.random.split(UpperCamelCase							)
    _snake_case   :				List[Any]														=	{'params': params_rng, 'dropout': dropout_rng}

    _snake_case   :				Optional[Any]														=	self.module.init(UpperCamelCase      ,				UpperCamelCase							)['params']

    return random_params







  def __call__(      self      :					Union[str, Any]      ,				UpperCamelCase      :					Optional[Any]      ,				UpperCamelCase      :					dict = None      ,				):


    '''simple docstring'''





    _snake_case   :				Optional[Any]														=	jnp.transpose(UpperCamelCase      ,				(0, 2, 3, 1)							)

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











def     lowerCamelCase_	(      lowerCAmelCase:	bytes				)->		str:
  return "".join([hex(lowerCAmelCase				)[2:].zfill(2				).upper() for byte in list(lowerCAmelCase				)]				)


def     lowerCamelCase_	(      lowerCAmelCase:	str				)->		bytes:
  # Check data validity, following RFC3548
  # https://www.ietf.org/rfc/rfc3548.txt
  if (len(lowerCAmelCase				) % 2) != 0:
    raise ValueError(
        'Base16 encoded data is invalid:\nData does not have an even number of hex digits.'				)
  # Check the character set - the standard base16 alphabet
  # is uppercase according to RFC3548 section 6
  if not set(lowerCAmelCase				) <= set('0123456789ABCDEF'				):
    raise ValueError(
        'Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters.'				)
  # For every two hexadecimal digits (= a byte), turn it into an integer.
  # Then, string the result together into bytes, and return it.
  return bytes(int(data[i] + data[i + 1]    ,							16				) for i in range(0    ,							len(lowerCAmelCase				)    ,							2				)				)


if __name__ == "__main__":
      import doctest

      doctest.testmod()




