





'''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"""






				lowercase         = jnp.divide(emb_a.T		,							jnp.clip(jnp.linalg.norm(lowerCAmelCase_		,							axis=1							)		,							a_min=lowerCAmelCase_							)							).T
				lowercase         = 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       UpperCAmelCase (						nn.Module  ):
		UpperCAmelCase					:	CLIPConfig
		UpperCAmelCase					:	jnp.dtype 			=		jnp.floataa




		def 				UpperCAmelCase__   (self      :	int				)					-> Any:
						lowercase         = FlaxCLIPVisionModule(self.config.vision_config				)
						lowercase         = nn.Dense(self.config.projection_dim							,			use_bias=A__							,			dtype=self.dtype				)

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

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





		def __call__(self      :	Union[str, Any]							,			A__      :	Dict				)					-> Tuple:
						lowercase         = self.vision_model(A__				)[1]
						lowercase         = self.visual_projection(A__				)

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

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

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

						return has_nsfw_concepts




class       UpperCAmelCase (						_lowercase  ):
		UpperCAmelCase					:	Tuple 			=		CLIPConfig
		UpperCAmelCase					:	List[Any] 			=		'''clip_input'''
		UpperCAmelCase					:	Union[str, Any] 			=		FlaxStableDiffusionSafetyCheckerModule




		def __init__(self      :	Tuple							,			A__      :	CLIPConfig							,			A__      :	Optional[Tuple] = None							,			A__      :	int = 0							,			A__      :	jnp.dtype = jnp.floataa							,			A__      :	bool = True							,			**A__      :	Tuple							,			)					-> Union[str, Any]:
						if input_shape is None:
										lowercase         = (1, 2_2_4, 2_2_4, 3)
						lowercase         = self.module_class(config=A__							,			dtype=A__							,			**A__				)
						super().__init__(A__							,			A__							,			input_shape=A__							,			seed=A__							,			dtype=A__							,			_do_init=_do_init				)




		def 				UpperCAmelCase__   (self      :	Any							,			A__      :	jax.random.KeyArray							,			A__      :	Tuple							,			A__      :	FrozenDict = None				)					-> FrozenDict:
						# init input tensor
						lowercase         = jax.random.normal(A__							,			A__				)

						lowercase   ,							lowercase         = jax.random.split(A__				)
						lowercase         = {"params": params_rng, "dropout": dropout_rng}

						lowercase         = self.module.init(A__							,			A__				)["params"]

						return random_params





		def __call__(self      :	int							,			A__      :	Any							,			A__      :	dict = None							,			)					-> Optional[Any]:
						lowercase         = 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 warnings
from contextlib import contextmanager

from ....processing_utils import ProcessorMixin

class       UpperCAmelCase (						_lowercase  ):
		UpperCAmelCase					:	Optional[Any] 			=		'''MCTCTFeatureExtractor'''
		UpperCAmelCase					:	Tuple 			=		'''AutoTokenizer'''




		def __init__(self      :	int							,			A__      :	Tuple							,			A__      :	Union[str, Any]				)					-> Dict:
						super().__init__(A__							,			A__				)
						lowercase         = self.feature_extractor
						lowercase         = False




		def __call__(self      :	Tuple							,			*A__      :	str							,			**A__      :	Dict				)					-> int:
						# For backward compatibility
						if self._in_target_context_manager:
										return self.current_processor(*A__							,			**A__				)

						if "raw_speech" in kwargs:
										warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."				)
										lowercase         = kwargs.pop("raw_speech"				)
						else:
										lowercase         = kwargs.pop("audio"							,			A__				)
						lowercase         = kwargs.pop("sampling_rate"							,			A__				)
						lowercase         = kwargs.pop("text"							,			A__				)
						if len(A__				) > 0:
										lowercase         = args[0]
										lowercase         = args[1:]

						if audio is None and text is None:
										raise ValueError("You need to specify either an `audio` or `text` input to process."				)

						if audio is not None:
										lowercase         = self.feature_extractor(A__							,			*A__							,			sampling_rate=A__							,			**A__				)
						if text is not None:
										lowercase         = self.tokenizer(A__							,			**A__				)

						if text is None:
										return inputs
						elif audio is None:
										return encodings
						else:
										lowercase         = encodings["input_ids"]
										return inputs




		def 				UpperCAmelCase__   (self      :	Tuple							,			*A__      :	str							,			**A__      :	str				)					-> str:
						return self.tokenizer.batch_decode(*A__							,			**A__				)




		def 				UpperCAmelCase__   (self      :	Any							,			*A__      :	List[Any]							,			**A__      :	List[str]				)					-> Tuple:
						# For backward compatibility
						if self._in_target_context_manager:
										return self.current_processor.pad(*A__							,			**A__				)

						lowercase         = kwargs.pop("input_features"							,			A__				)
						lowercase         = kwargs.pop("labels"							,			A__				)
						if len(A__				) > 0:
										lowercase         = args[0]
										lowercase         = args[1:]

						if input_features is not None:
										lowercase         = self.feature_extractor.pad(A__							,			*A__							,			**A__				)
						if labels is not None:
										lowercase         = self.tokenizer.pad(A__							,			**A__				)

						if labels is None:
										return input_features
						elif input_features is None:
										return labels
						else:
										lowercase         = labels["input_ids"]
										return input_features




		def 				UpperCAmelCase__   (self      :	Tuple							,			*A__      :	Optional[int]							,			**A__      :	Optional[int]				)					-> Tuple:
						return self.tokenizer.decode(*A__							,			**A__				)





		@contextmanager
		def 				UpperCAmelCase__   (self      :	Optional[Any]				)					-> Union[str, Any]:
						warnings.warn(
						    "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
						    "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
						    "your audio inputs, or in a separate call."				)
						lowercase         = True
						lowercase         = self.tokenizer
						yield
						lowercase         = self.feature_extractor
						lowercase         = False




