
'''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_ (  lowerCamelCase_      ,			lowerCamelCase_      ,			lowerCamelCase_=1e-1_2			):







 """simple docstring"""


 lowerCAmelCase__     :   int     		=	jnp.divide(emb_a.T      ,			jnp.clip(jnp.linalg.norm(lowerCamelCase_      ,			axis=1			)      ,			a_min=lowerCamelCase_			)			).T
 lowerCAmelCase__     :   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  ):
 A_				:				CLIPConfig
 A_				:				jnp.dtype	=			jnp.floataa


 def    _A	(    self  : List[Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[int]     		=	FlaxCLIPVisionModule(self.config.vision_config    )
  lowerCAmelCase__     :   Optional[Any]     		=	nn.Dense(self.config.projection_dim			,							use_bias=a__			,							dtype=self.dtype    )

  lowerCAmelCase__     :   Any     		=	self.param("concept_embeds"			,							jax.nn.initializers.ones			,							(17, self.config.projection_dim)    )
  lowerCAmelCase__     :   Any     		=	self.param(
      "special_care_embeds"			,							jax.nn.initializers.ones			,							(3, self.config.projection_dim)    )

  lowerCAmelCase__     :   Dict     		=	self.param("concept_embeds_weights"			,							jax.nn.initializers.ones			,							(17,)    )
  lowerCAmelCase__     :   int     		=	self.param("special_care_embeds_weights"			,							jax.nn.initializers.ones			,							(3,)    )


 def __call__(    self  : Optional[int]			,							a__  : Optional[Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	self.vision_model(a__    )[1]
  lowerCAmelCase__     :   Optional[int]     		=	self.visual_projection(a__    )

  lowerCAmelCase__     :   Tuple     		=	jax_cosine_distance(a__			,							self.special_care_embeds    )
  lowerCAmelCase__     :   Optional[int]     		=	jax_cosine_distance(a__			,							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__     :   Tuple     		=	0.0

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

  lowerCAmelCase__     :   List[Any]     		=	cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
  lowerCAmelCase__     :   List[Any]     		=	jnp.round(a__			,							3    )
  lowerCAmelCase__     :   Optional[int]     		=	jnp.any(concept_scores > 0			,							axis=1    )

  return has_nsfw_concepts




class    lowerCAmelCase       (     UpperCamelCase_  ):
 A_				:				Any	=			CLIPConfig
 A_				:				List[Any]	=			"""clip_input"""
 A_				:				Tuple	=			FlaxStableDiffusionSafetyCheckerModule


 def __init__(    self  : str			,							a__  : CLIPConfig			,							a__  : Optional[Tuple] = None			,							a__  : int = 0			,							a__  : jnp.dtype = jnp.floataa			,							a__  : bool = True			,							**a__  : int			,							):
  '''simple docstring'''

  if input_shape is None:
   lowerCAmelCase__     :   Any     		=	(1, 224, 224, 3)
  lowerCAmelCase__     :   str     		=	self.module_class(config=a__			,							dtype=a__			,							**a__    )
  super().__init__(a__			,							a__			,							input_shape=a__			,							seed=a__			,							dtype=a__			,							_do_init=_do_init    )


 def    _A	(    self  : Optional[int]			,							a__  : jax.random.KeyArray			,							a__  : Tuple			,							a__  : FrozenDict = None    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	jax.random.normal(a__			,							a__    )

  lowerCAmelCase__		,     lowerCAmelCase__     :   Any     		=	jax.random.split(a__    )
  lowerCAmelCase__     :   Optional[Any]     		=	{"params": params_rng, "dropout": dropout_rng}

  lowerCAmelCase__     :   Any     		=	self.module.init(a__			,							a__    )["params"]

  return random_params


 def __call__(    self  : Dict			,							a__  : str			,							a__  : dict = None			,							):
  '''simple docstring'''

  lowerCAmelCase__     :   str     		=	jnp.transpose(a__			,							(0, 2, 3, 1)    )

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







'''simple docstring'''

import os


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_doctest_list.py
snake_case									=    """."""


if __name__ == "__main__":
     snake_case									=    os.path.join(REPO_PATH, """utils/documentation_tests.txt""")
     snake_case									=    []
     snake_case									=    []
     with open(doctest_file_path) as fp:
          for line in fp:
               snake_case									=    line.strip()
               snake_case									=    os.path.join(REPO_PATH, line)
               if not (os.path.isfile(path) or os.path.isdir(path)):
                    non_existent_paths.append(line)
               all_paths.append(path)
     if len(non_existent_paths) > 0:
          snake_case									=    """\n""".join(non_existent_paths)
          raise ValueError(f'`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}')
     if all_paths != sorted(all_paths):
          raise ValueError("""Files in `utils/documentation_tests.txt` are not in alphabetical order.""")





