




"""simple docstring"""

import argparse
import os
import re

import packaging.version


a					=			"examples/"
a					=			{
    "examples": (re.compile(r'''^check_min_version\(\"[^\"]+\"\)\s*$''', re.MULTILINE), "check_min_version(\"VERSION\")\n"),
    "init": (re.compile(r'''^__version__\s+=\s+\"([^\"]+)\"\s*$''', re.MULTILINE), "__version__ = \"VERSION\"\n"),
    "setup": (re.compile(r'''^(\s*)version\s*=\s*\"[^\"]+\",''', re.MULTILINE), R"\1version=\"VERSION\","),
    "doc": (re.compile(r'''^(\s*)release\s*=\s*\"[^\"]+\"$''', re.MULTILINE), "release = \"VERSION\"\n"),
}
a					=			{
    "init": "src/transformers/__init__.py",
    "setup": "setup.py",
}
a					=			"README.md"






def 						_snake_case     (					_snake_case							:					Optional[int]				,  _snake_case							:					Dict				,  _snake_case							:					Optional[Any]							)    ->					Optional[Any]:






      '''simple docstring'''


      with open(A__				,  'r'				,  encoding='utf-8'				,  newline='\n'							) as f:
            _A					   =   f.read()
      _A   ,    _A					   =   REPLACE_PATTERNS[pattern]
      _A					   =   replace.replace('VERSION'				,  A__							)
      _A					   =   re_pattern.sub(A__				,  A__							)
      with open(A__				,  'w'				,  encoding='utf-8'				,  newline='\n'							) as f:
            f.write(A__							)






def 						_snake_case     (					_snake_case							:					List[str]							)    ->					Optional[int]:






      '''simple docstring'''


      for folder, directories, fnames in os.walk(A__							):
            # Removing some of the folders with non-actively maintained examples from the walk
            if "research_projects" in directories:
                  directories.remove('research_projects'							)
            if "legacy" in directories:
                  directories.remove('legacy'							)
            for fname in fnames:
                  if fname.endswith('.py'							):
                        update_version_in_file(os.path.join(A__				,  A__							)				,  A__				,  pattern='examples'							)






def 						_snake_case     (					_snake_case							:					Any				,  _snake_case							:					Union[str, Any]=False							)    ->					List[str]:






      '''simple docstring'''


      for pattern, fname in REPLACE_FILES.items():
            update_version_in_file(A__				,  A__				,  A__							)
      if not patch:
            update_version_in_examples(A__							)






def 						_snake_case     (					)    ->					Optional[Any]:






      '''simple docstring'''


      _A					   =   '🤗 Transformers currently provides the following architectures'
      _A					   =   '1. Want to contribute a new model?'
      with open(A__				,  'r'				,  encoding='utf-8'				,  newline='\n'							) as f:
            _A					   =   f.readlines()

      # Find the start of the list.
      _A					   =   0
      while not lines[start_index].startswith(_start_prompt							):
            start_index += 1
      start_index += 1

      _A					   =   start_index
      # Update the lines in the model list.
      while not lines[index].startswith(_end_prompt							):
            if lines[index].startswith('1.'							):
                  _A					   =   lines[index].replace(
                      'https://huggingface.co/docs/transformers/main/model_doc'				,  'https://huggingface.co/docs/transformers/model_doc'				,  )
            index += 1

      with open(A__				,  'w'				,  encoding='utf-8'				,  newline='\n'							) as f:
            f.writelines(A__							)






def 						_snake_case     (					)    ->					Optional[Any]:






      '''simple docstring'''


      with open(REPLACE_FILES['init']				,  'r'							) as f:
            _A					   =   f.read()
      _A					   =   REPLACE_PATTERNS['init'][0].search(A__							).groups()[0]
      return packaging.version.parse(A__							)






def 						_snake_case     (					_snake_case							:					Any=False							)    ->					Union[str, Any]:






      '''simple docstring'''


      _A					   =   get_version()
      if patch and default_version.is_devrelease:
            raise ValueError('Can\'t create a patch version from the dev branch, checkout a released version!'							)
      if default_version.is_devrelease:
            _A					   =   default_version.base_version
      elif patch:
            _A					   =   F'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}'''
      else:
            _A					   =   F'''{default_version.major}.{default_version.minor + 1}.0'''

      # Now let's ask nicely if that's the right one.
      _A					   =   input(F'''Which version are you releasing? [{default_version}]'''							)
      if len(A__							) == 0:
            _A					   =   default_version

      print(F'''Updating version to {version}.'''							)
      global_version_update(A__				,  patch=A__							)
      if not patch:
            print('Cleaning main README, don\'t forget to run `make fix-copies`.'							)
            clean_main_ref_in_model_list()






def 						_snake_case     (					)    ->					int:






      '''simple docstring'''


      _A					   =   get_version()
      _A					   =   F'''{current_version.major}.{current_version.minor + 1}.0.dev0'''
      _A					   =   current_version.base_version

      # Check with the user we got that right.
      _A					   =   input(F'''Which version are we developing now? [{dev_version}]'''							)
      if len(A__							) == 0:
            _A					   =   dev_version

      print(F'''Updating version to {version}.'''							)
      global_version_update(A__							)
      print('Cleaning main README, don\'t forget to run `make fix-copies`.'							)
      clean_main_ref_in_model_list()


if __name__ == "__main__":
       a					=			argparse.ArgumentParser()
       parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''')
       parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''')
       a					=			parser.parse_args()
       if not args.post_release:
              pre_release_work(patch=args.patch)
       elif args.patch:
              print('''Nothing to do after a patch :-)''')
       else:
              post_release_work()






'''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 				__lowerCamelCase				(   A__    ,						A__    ,						A__=1e-1_2    )       ->	Dict:






   """simple docstring"""
   UpperCamelCase					=  jnp.divide(emb_a.T    ,						jnp.clip(jnp.linalg.norm(A__    ,						axis=1    )    ,						a_min=A__    )    ).T
   UpperCamelCase					=  jnp.divide(emb_a.T    ,						jnp.clip(jnp.linalg.norm(A__    ,						axis=1    )    ,						a_min=A__    )    ).T
   return jnp.matmul(A__    ,						norm_emb_a.T    )

class  SCREAMING_SNAKE_CASE (  nn.Module		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  42
    _SCREAMING_SNAKE_CASE	  =  jnp.floataa






    def  A       (  self      :					List[Any] ):


       """simple docstring"""







       UpperCamelCase					=  FlaxCLIPVisionModule(self.config.vision_config )
       UpperCamelCase					=  nn.Dense(self.config.projection_dim  ,						use_bias=UpperCamelCase__  ,						dtype=self.dtype )

       UpperCamelCase					=  self.param('concept_embeds'  ,						jax.nn.initializers.ones  ,						(1_7, self.config.projection_dim) )
       UpperCamelCase					=  self.param(
           'special_care_embeds'  ,						jax.nn.initializers.ones  ,						(3, self.config.projection_dim) )

       UpperCamelCase					=  self.param('concept_embeds_weights'  ,						jax.nn.initializers.ones  ,						(1_7,) )
       UpperCamelCase					=  self.param('special_care_embeds_weights'  ,						jax.nn.initializers.ones  ,						(3,) )






    def __call__(  self      :					str  ,						UpperCamelCase__      :					List[str] ):


       """simple docstring"""







       UpperCamelCase					=  self.vision_model(UpperCamelCase__ )[1]
       UpperCamelCase					=  self.visual_projection(UpperCamelCase__ )

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

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

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

       return has_nsfw_concepts

class  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  CLIPConfig
    _SCREAMING_SNAKE_CASE	  =  """clip_input"""
    _SCREAMING_SNAKE_CASE	  =  FlaxStableDiffusionSafetyCheckerModule






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


       """simple docstring"""







       if input_shape is None:
          UpperCamelCase					=  (1, 2_2_4, 2_2_4, 3)
       UpperCamelCase					=  self.module_class(config=UpperCamelCase__  ,						dtype=UpperCamelCase__  ,						**UpperCamelCase__ )
       super().__init__(UpperCamelCase__  ,						UpperCamelCase__  ,						input_shape=UpperCamelCase__  ,						seed=UpperCamelCase__  ,						dtype=UpperCamelCase__  ,						_do_init=_do_init )






    def  A       (  self      :					int  ,						UpperCamelCase__      :					jax.random.KeyArray  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					FrozenDict = None ):


       """simple docstring"""







       UpperCamelCase					=  jax.random.normal(UpperCamelCase__  ,						UpperCamelCase__ )

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

       UpperCamelCase					=  self.module.init(UpperCamelCase__  ,						UpperCamelCase__ )['params']

       return random_params






    def __call__(  self      :					List[Any]  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					dict = None  ,						):


       """simple docstring"""







       UpperCamelCase					=  jnp.transpose(UpperCamelCase__  ,						(0, 2, 3, 1) )

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

