


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 							__magic_name__    (     lowerCAmelCase_     ,	lowerCAmelCase_     ,	lowerCAmelCase_=1E-12):
	'''simple docstring'''


	lowerCamelCase_					:				Any              =  jnp.divide(emb_a.T     ,	jnp.clip(jnp.linalg.norm(_lowerCamelCase     ,	axis=1)     ,	a_min=_lowerCamelCase)).T
	lowerCamelCase_					:				Optional[int]              =  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"""
						__UpperCAmelCase       :						Optional[int]    	=			42
						__UpperCAmelCase       :						int    	=			jnp.floataa




						def 	_UpperCamelCase					(       self      ):
							lowerCamelCase_					:				Optional[int]              =  FlaxCLIPVisionModule(self.config.vision_config      )
							lowerCamelCase_					:				Union[str, Any]              =  nn.Dense(self.config.projection_dim ,				use_bias=SCREAMING_SNAKE_CASE_ ,				dtype=self.dtype      )

							lowerCamelCase_					:				str              =  self.param("concept_embeds" ,				jax.nn.initializers.ones ,				(17, self.config.projection_dim)      )
							lowerCamelCase_					:				Dict              =  self.param(
							    "special_care_embeds" ,				jax.nn.initializers.ones ,				(3, self.config.projection_dim)      )

							lowerCamelCase_					:				Tuple              =  self.param("concept_embeds_weights" ,				jax.nn.initializers.ones ,				(17,)      )
							lowerCamelCase_					:				Union[str, Any]              =  self.param("special_care_embeds_weights" ,				jax.nn.initializers.ones ,				(3,)      )




						def __call__(       self ,				a_      ):
							lowerCamelCase_					:				Dict              =  self.vision_model(SCREAMING_SNAKE_CASE_      )[1]
							lowerCamelCase_					:				Optional[Any]              =  self.visual_projection(SCREAMING_SNAKE_CASE_      )

							lowerCamelCase_					:				Tuple              =  jax_cosine_distance(SCREAMING_SNAKE_CASE_ ,				self.special_care_embeds      )
							lowerCamelCase_					:				int              =  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
							lowerCamelCase_					:				Dict              =  0.0

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

							lowerCamelCase_					:				Tuple              =  cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
							lowerCamelCase_					:				Any              =  jnp.round(SCREAMING_SNAKE_CASE_ ,				3      )
							lowerCamelCase_					:				Optional[Any]              =  jnp.any(concept_scores > 0 ,				axis=1      )

							return has_nsfw_concepts





class        lowerCAmelCase__ (					lowercase__  ):






						"""simple docstring"""
						__UpperCAmelCase       :						Optional[int]    	=			CLIPConfig
						__UpperCAmelCase       :						Dict    	=			'''clip_input'''
						__UpperCAmelCase       :						Tuple    	=			FlaxStableDiffusionSafetyCheckerModule




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


							if input_shape is None:
								lowerCamelCase_					:				int              =  (1, 224, 224, 3)
							lowerCamelCase_					:				Tuple              =  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 ,				a_ ,				a_ ,				a_ = None      ):
							lowerCamelCase_					:				int              =  jax.random.normal(SCREAMING_SNAKE_CASE_ ,				SCREAMING_SNAKE_CASE_      )

							lowerCamelCase_       ,lowerCamelCase_					:				int              =  jax.random.split(SCREAMING_SNAKE_CASE_      )
							lowerCamelCase_					:				Any              =  {"params": params_rng, "dropout": dropout_rng}

							lowerCamelCase_					:				Any              =  self.module.init(SCREAMING_SNAKE_CASE_ ,				SCREAMING_SNAKE_CASE_      )["params"]

							return random_params




						def __call__(       self ,				a_ ,				a_ = None ,				):
							lowerCamelCase_					:				Dict              =  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={} ,				)



"""simple docstring"""






import os
import unittest

from huggingface_hub.utils import are_progress_bars_disabled

import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar



class 			lowercase					( unittest.TestCase		):






			def 					UpperCAmelCase							(self  :	Union[str, Any]			)       ->	Optional[Any]:





				"""simple docstring"""


				lowerCAmelCase												=  logging.get_logger()

				# the current default level is logging.WARNING
				lowerCAmelCase												=  logging.get_verbosity()

				logging.set_verbosity_error()
				self.assertEqual(logger.getEffectiveLevel()      ,logging.get_verbosity()			)

				logging.set_verbosity_warning()
				self.assertEqual(logger.getEffectiveLevel()      ,logging.get_verbosity()			)

				logging.set_verbosity_info()
				self.assertEqual(logger.getEffectiveLevel()      ,logging.get_verbosity()			)

				logging.set_verbosity_debug()
				self.assertEqual(logger.getEffectiveLevel()      ,logging.get_verbosity()			)

				# restore to the original level
				logging.set_verbosity(SCREAMING_SNAKE_CASE_			)






			def 					UpperCAmelCase							(self  :	Union[str, Any]			)       ->	Optional[int]:





				"""simple docstring"""


				lowerCAmelCase												=  logging.get_verbosity()

				lowerCAmelCase												=  logging.get_logger('''transformers.models.bart.tokenization_bart'''			)
				lowerCAmelCase												=  '''Testing 1, 2, 3'''

				# should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
				if level_origin <= logging.WARNING:
					with CaptureLogger(SCREAMING_SNAKE_CASE_			) as cl:
						logger.warning(SCREAMING_SNAKE_CASE_			)
					self.assertEqual(cl.out      ,msg + '''\n'''			)

				# this is setting the level for all of `transformers.*` loggers
				logging.set_verbosity_error()

				# should not be able to log warnings
				with CaptureLogger(SCREAMING_SNAKE_CASE_			) as cl:
					logger.warning(SCREAMING_SNAKE_CASE_			)
				self.assertEqual(cl.out      ,''''''			)

				# should be able to log warnings again
				logging.set_verbosity_warning()
				with CaptureLogger(SCREAMING_SNAKE_CASE_			) as cl:
					logger.warning(SCREAMING_SNAKE_CASE_			)
				self.assertEqual(cl.out      ,msg + '''\n'''			)

				# restore to the original level
				logging.set_verbosity(SCREAMING_SNAKE_CASE_			)






			@mockenv(TRANSFORMERS_VERBOSITY='''error'''			)
			def 					UpperCAmelCase							(self  :	Any			)       ->	str:





				"""simple docstring"""


				transformers.utils.logging._reset_library_root_logger()
				# this action activates the env var
				lowerCAmelCase												=  logging.get_logger('''transformers.models.bart.tokenization_bart'''			)

				lowerCAmelCase												=  os.getenv('''TRANSFORMERS_VERBOSITY'''      ,SCREAMING_SNAKE_CASE_			)
				lowerCAmelCase												=  logging.log_levels[env_level_str]

				lowerCAmelCase												=  logging.get_verbosity()
				self.assertEqual(
				    SCREAMING_SNAKE_CASE_      ,SCREAMING_SNAKE_CASE_      ,F"""TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}"""      ,)

				# restore to the original level
				lowerCAmelCase												=  ''''''
				transformers.utils.logging._reset_library_root_logger()






			@mockenv(TRANSFORMERS_VERBOSITY='''super-error'''			)
			def 					UpperCAmelCase							(self  :	List[Any]			)       ->	Tuple:





				"""simple docstring"""


				transformers.utils.logging._reset_library_root_logger()
				lowerCAmelCase												=  logging.logging.getLogger()
				with CaptureLogger(SCREAMING_SNAKE_CASE_			) as cl:
					# this action activates the env var
					logging.get_logger('''transformers.models.bart.tokenization_bart'''			)
				self.assertIn('''Unknown option TRANSFORMERS_VERBOSITY=super-error'''      ,cl.out			)

				# no need to restore as nothing was changed






			def 					UpperCAmelCase							(self  :	Dict			)       ->	Any:





				"""simple docstring"""


				transformers.utils.logging._reset_library_root_logger()

				lowerCAmelCase												=  logging.get_logger('''transformers.models.bart.tokenization_bart'''			)
				lowerCAmelCase												=  '''Testing 1, 2, 3'''

				with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='''1'''			):
					# nothing should be logged as env var disables this method
					with CaptureLogger(SCREAMING_SNAKE_CASE_			) as cl:
						logger.warning_advice(SCREAMING_SNAKE_CASE_			)
					self.assertEqual(cl.out      ,''''''			)

				with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=''''''			):
					# should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
					with CaptureLogger(SCREAMING_SNAKE_CASE_			) as cl:
						logger.warning_advice(SCREAMING_SNAKE_CASE_			)
					self.assertEqual(cl.out      ,msg + '''\n'''			)





def __magic_name__	(				)					->						List[Any]:

	'''simple docstring'''




	disable_progress_bar()
	assert are_progress_bars_disabled()

	enable_progress_bar()
	assert not are_progress_bars_disabled()


