




'''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(							SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_=1e-1_2     )		->		Optional[int]:
			A_									= jnp.divide(emb_a.T       ,jnp.clip(jnp.linalg.norm(SCREAMING_SNAKE_CASE_       ,axis=1     )       ,a_min=SCREAMING_SNAKE_CASE_     )     ).T
			A_									= jnp.divide(emb_a.T       ,jnp.clip(jnp.linalg.norm(SCREAMING_SNAKE_CASE_       ,axis=1     )       ,a_min=SCREAMING_SNAKE_CASE_     )     ).T
			return jnp.matmul(SCREAMING_SNAKE_CASE_       ,norm_emb_a.T     )
class   __UpperCAmelCase				(     nn.Module				):



					'''simple docstring'''





					_UpperCamelCase							=		42
					_UpperCamelCase							=		jnp.floataa



					def     __snake_case						(	self     :						Tuple)    ->							Tuple:
								A_									= FlaxCLIPVisionModule(self.config.vision_config)
								A_									= nn.Dense(self.config.projection_dim      ,       use_bias=_lowercase      ,       dtype=self.dtype)

								A_									= self.param('concept_embeds'      ,       jax.nn.initializers.ones      ,       (17, self.config.projection_dim))
								A_									= self.param(
								    'special_care_embeds'      ,       jax.nn.initializers.ones      ,       (3, self.config.projection_dim))

								A_									= self.param('concept_embeds_weights'      ,       jax.nn.initializers.ones      ,       (17,))
								A_									= self.param('special_care_embeds_weights'      ,       jax.nn.initializers.ones      ,       (3,))



					def __call__(	self     :						List[str]      ,       _lowercase     :						List[str])    ->							str:
								A_									= self.vision_model(_lowercase)[1]
								A_									= self.visual_projection(_lowercase)

								A_									= jax_cosine_distance(_lowercase      ,       self.special_care_embeds)
								A_									= jax_cosine_distance(_lowercase      ,       self.concept_embeds)

								# increase this value to create a stronger `nfsw` filter
								# at the cost of increasing the possibility of filtering benign image inputs
								A_									= 0.0

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

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

								return has_nsfw_concepts





class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					_UpperCamelCase							=		CLIPConfig
					_UpperCamelCase							=		"""clip_input"""
					_UpperCamelCase							=		FlaxStableDiffusionSafetyCheckerModule



					def __init__(	self     :						Any      ,       _lowercase     :						CLIPConfig      ,       _lowercase     :						Optional[Tuple] = None      ,       _lowercase     :						int = 0      ,       _lowercase     :						jnp.dtype = jnp.floataa      ,       _lowercase     :						bool = True      ,       **_lowercase     :						Any      ,       )    ->							List[Any]:
								if input_shape is None:
											A_									= (1, 224, 224, 3)
								A_									= self.module_class(config=_lowercase      ,       dtype=_lowercase      ,       **_lowercase)
								super().__init__(_lowercase      ,       _lowercase      ,       input_shape=_lowercase      ,       seed=_lowercase      ,       dtype=_lowercase      ,       _do_init=_do_init)



					def     __snake_case						(	self     :						Dict      ,       _lowercase     :						jax.random.KeyArray      ,       _lowercase     :						Tuple      ,       _lowercase     :						FrozenDict = None)    ->							FrozenDict:
								# init input tensor
								A_									= jax.random.normal(_lowercase      ,       _lowercase)

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

								A_									= self.module.init(_lowercase      ,       _lowercase)['params']

								return random_params



					def __call__(	self     :						Dict      ,       _lowercase     :						List[Any]      ,       _lowercase     :						dict = None      ,       )    ->							Optional[int]:
								A_									= jnp.transpose(_lowercase      ,       (0, 2, 3, 1))

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










'''simple docstring'''
import os
from typing import List, Optional, Union

from ...image_processing_utils import BatchFeature
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
from ..auto import AutoTokenizer
class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					_UpperCamelCase							=		["""image_processor""", """tokenizer"""]
					_UpperCamelCase							=		"""BlipImageProcessor"""
					_UpperCamelCase							=		"""AutoTokenizer"""



					def __init__(	self     :						Union[str, Any]      ,       _lowercase     :						Union[str, Any]      ,       _lowercase     :						List[Any]      ,       _lowercase     :						List[str])    ->							Union[str, Any]:
								super().__init__(_lowercase      ,       _lowercase)

								# add QFormer tokenizer
								A_									= qformer_tokenizer



					def __call__(	self     :						Optional[int]      ,       _lowercase     :						ImageInput = None      ,       _lowercase     :						Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None      ,       _lowercase     :						bool = True      ,       _lowercase     :						Union[bool, str, PaddingStrategy] = False      ,       _lowercase     :						Union[bool, str, TruncationStrategy] = None      ,       _lowercase     :						Optional[int] = None      ,       _lowercase     :						int = 0      ,       _lowercase     :						Optional[int] = None      ,       _lowercase     :						Optional[bool] = None      ,       _lowercase     :						bool = False      ,       _lowercase     :						bool = False      ,       _lowercase     :						bool = False      ,       _lowercase     :						bool = False      ,       _lowercase     :						bool = False      ,       _lowercase     :						bool = True      ,       _lowercase     :						Optional[Union[str, TensorType]] = None      ,       **_lowercase     :						List[Any]      ,       )    ->							BatchFeature:
								if images is None and text is None:
											raise ValueError('You have to specify at least images or text.')

								A_									= BatchFeature()

								if text is not None:
											A_									= self.tokenizer(
											    text=_lowercase      ,       add_special_tokens=_lowercase      ,       padding=_lowercase      ,       truncation=_lowercase      ,       max_length=_lowercase      ,       stride=_lowercase      ,       pad_to_multiple_of=_lowercase      ,       return_attention_mask=_lowercase      ,       return_overflowing_tokens=_lowercase      ,       return_special_tokens_mask=_lowercase      ,       return_offsets_mapping=_lowercase      ,       return_token_type_ids=_lowercase      ,       return_length=_lowercase      ,       verbose=_lowercase      ,       return_tensors=_lowercase      ,       **_lowercase      ,       )
											encoding.update(_lowercase)
											A_									= self.qformer_tokenizer(
											    text=_lowercase      ,       add_special_tokens=_lowercase      ,       padding=_lowercase      ,       truncation=_lowercase      ,       max_length=_lowercase      ,       stride=_lowercase      ,       pad_to_multiple_of=_lowercase      ,       return_attention_mask=_lowercase      ,       return_overflowing_tokens=_lowercase      ,       return_special_tokens_mask=_lowercase      ,       return_offsets_mapping=_lowercase      ,       return_token_type_ids=_lowercase      ,       return_length=_lowercase      ,       verbose=_lowercase      ,       return_tensors=_lowercase      ,       **_lowercase      ,       )
											A_									= qformer_text_encoding.pop('input_ids')
											A_									= qformer_text_encoding.pop('attention_mask')

								if images is not None:
											A_									= self.image_processor(_lowercase      ,       return_tensors=_lowercase)
											encoding.update(_lowercase)

								return encoding



					def     __snake_case						(	self     :						List[Any]      ,       *_lowercase     :						Optional[Any]      ,       **_lowercase     :						List[Any])    ->							Union[str, Any]:
								return self.tokenizer.batch_decode(*_lowercase      ,       **_lowercase)



					def     __snake_case						(	self     :						Optional[int]      ,       *_lowercase     :						List[Any]      ,       **_lowercase     :						List[str])    ->							str:
								return self.tokenizer.decode(*_lowercase      ,       **_lowercase)



					@property
					# Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names
					def     __snake_case						(	self     :						Any)    ->							Optional[int]:
								A_									= self.tokenizer.model_input_names
								A_									= self.image_processor.model_input_names
								return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))



					def     __snake_case						(	self     :						Optional[Any]      ,       _lowercase     :						Optional[int]      ,       **_lowercase     :						int)    ->							Tuple:
								if os.path.isfile(_lowercase):
											raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file')
								os.makedirs(_lowercase      ,       exist_ok=_lowercase)
								A_									= os.path.join(_lowercase      ,       'qformer_tokenizer')
								self.qformer_tokenizer.save_pretrained(_lowercase)
								return super().save_pretrained(_lowercase      ,       **_lowercase)



					@classmethod
					def     __snake_case						(	cls     :						Dict      ,       _lowercase     :						Dict      ,       **_lowercase     :						int)    ->							Any:
								A_									= AutoTokenizer.from_pretrained(_lowercase      ,       subfolder='qformer_tokenizer')
								A_									= cls._get_arguments_from_pretrained(_lowercase      ,       **_lowercase)
								args.append(_lowercase)
								return cls(*_lowercase)




