"""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 			lowercase__(       __SCREAMING_SNAKE_CASE							:     Any     ,			__SCREAMING_SNAKE_CASE							:     int     ,			__SCREAMING_SNAKE_CASE							:     Optional[int]=1E-12      ):
     lowercase_	:				Dict													=	jnp.divide(emb_a.T     ,			jnp.clip(jnp.linalg.norm(__SCREAMING_SNAKE_CASE     ,			axis=1      )     ,			a_min=__SCREAMING_SNAKE_CASE      )      ).T
     lowercase_	:				Optional[Any]													=	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  ):
   lowercase							=  42
   lowercase							=  jnp.floataa
   def 			_UpperCAmelCase   (			self			)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				Union[str, Any]													=	FlaxCLIPVisionModule(self.config.vision_config			)
        lowercase_	:				Any													=	nn.Dense(self.config.projection_dim     ,use_bias=__UpperCamelCase     ,dtype=self.dtype			)

        lowercase_	:				int													=	self.param('concept_embeds'     ,jax.nn.initializers.ones     ,(17, self.config.projection_dim)			)
        lowercase_	:				Any													=	self.param(
            'special_care_embeds'     ,jax.nn.initializers.ones     ,(3, self.config.projection_dim)			)

        lowercase_	:				List[str]													=	self.param('concept_embeds_weights'     ,jax.nn.initializers.ones     ,(17,)			)
        lowercase_	:				Optional[int]													=	self.param('special_care_embeds_weights'     ,jax.nn.initializers.ones     ,(3,)			)







   def __call__(			self     ,__UpperCamelCase			)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	self.vision_model(__UpperCamelCase			)[1]
        lowercase_	:				int													=	self.visual_projection(__UpperCamelCase			)

        lowercase_	:				Dict													=	jax_cosine_distance(__UpperCamelCase     ,self.special_care_embeds			)
        lowercase_	:				Any													=	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
        lowercase_	:				List[str]													=	0.0

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

        lowercase_	:				int													=	cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
        lowercase_	:				str													=	jnp.round(__UpperCamelCase     ,3			)
        lowercase_	:				Optional[int]													=	jnp.any(concept_scores > 0     ,axis=1			)

        return has_nsfw_concepts







class        UpperCamelCase		(			lowercase_  ):
   lowercase							=  CLIPConfig
   lowercase							=  'clip_input'
   lowercase							=  FlaxStableDiffusionSafetyCheckerModule
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase = None     ,__UpperCamelCase = 0     ,__UpperCamelCase = jnp.floataa     ,__UpperCamelCase = True     ,**__UpperCamelCase     ,)	->      Any:


        '''simple docstring'''


        if input_shape is None:
             lowercase_	:				int													=	(1, 224, 224, 3)
        lowercase_	:				Optional[Any]													=	self.module_class(config=__UpperCamelCase     ,dtype=__UpperCamelCase     ,**__UpperCamelCase			)
        super().__init__(__UpperCamelCase     ,__UpperCamelCase     ,input_shape=__UpperCamelCase     ,seed=__UpperCamelCase     ,dtype=__UpperCamelCase     ,_do_init=_do_init			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase = None			)	->      FrozenDict:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	jax.random.normal(__UpperCamelCase     ,__UpperCamelCase			)

        lowercase_							,  lowercase_	:				int													=	jax.random.split(__UpperCamelCase			)
        lowercase_	:				List[str]													=	{'params': params_rng, 'dropout': dropout_rng}

        lowercase_	:				Dict													=	self.module.init(__UpperCamelCase     ,__UpperCamelCase			)['params']

        return random_params







   def __call__(			self     ,__UpperCamelCase     ,__UpperCamelCase = None     ,)	->      str:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	jnp.transpose(__UpperCamelCase     ,(0, 2, 3, 1)			)

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


"""simple docstring"""







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
       import PIL


__SCREAMING_SNAKE_CASE    	=logging.get_logger(__name__)







class        UpperCamelCase		(			lowercase_  ):
   lowercase							=  ['pixel_values']
   def __init__(			self     ,__UpperCamelCase = True     ,__UpperCamelCase = None     ,__UpperCamelCase = 0.9     ,__UpperCamelCase = PILImageResampling.BICUBIC     ,__UpperCamelCase = True     ,__UpperCamelCase = None     ,__UpperCamelCase = 1 / 255     ,__UpperCamelCase = True     ,__UpperCamelCase = True     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,**__UpperCamelCase     ,)	->      None:


        '''simple docstring'''


        super().__init__(**__UpperCamelCase			)
        lowercase_	:				Optional[int]													=	size if size is not None else {'shortest_edge': 224}
        lowercase_	:				Union[str, Any]													=	get_size_dict(__UpperCamelCase     ,default_to_square=__UpperCamelCase			)
        lowercase_	:				Union[str, Any]													=	crop_size if crop_size is not None else {'height': 224, 'width': 224}
        lowercase_	:				Optional[int]													=	get_size_dict(__UpperCamelCase     ,param_name='crop_size'			)

        lowercase_	:				List[str]													=	do_resize
        lowercase_	:				List[Any]													=	size
        lowercase_	:				int													=	crop_pct
        lowercase_	:				Dict													=	resample
        lowercase_	:				List[str]													=	do_center_crop
        lowercase_	:				Union[str, Any]													=	crop_size
        lowercase_	:				List[Any]													=	do_rescale
        lowercase_	:				Tuple													=	rescale_factor
        lowercase_	:				Tuple													=	do_normalize
        lowercase_	:				Union[str, Any]													=	image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
        lowercase_	:				int													=	image_std if image_std is not None else IMAGENET_DEFAULT_STD
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase = None     ,__UpperCamelCase = PILImageResampling.BICUBIC     ,__UpperCamelCase = None     ,**__UpperCamelCase     ,)	->      np.ndarray:


        '''simple docstring'''


        lowercase_	:				Any													=	get_size_dict(__UpperCamelCase     ,default_to_square=__UpperCamelCase			)
        if "shortest_edge" not in size and ("height" not in size or "width" not in size):
             raise ValueError(f'''size must contain \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'''			)
        if crop_pct is not None:
             if "shortest_edge" in size:
                  lowercase_	:				Union[str, Any]													=	int(size['shortest_edge'] / crop_pct			)
             elif "height" in size and "width" in size:
                  if size["height"] == size["width"]:
                       lowercase_	:				Tuple													=	int(size['height'] / crop_pct			)
                  else:
                       lowercase_	:				Dict													=	(int(size['height'] / crop_pct			), int(size['width'] / crop_pct			))
             else:
                  raise ValueError('Invalid size for resize: {}'.format(__UpperCamelCase			)			)

             lowercase_	:				int													=	get_resize_output_image_size(__UpperCamelCase     ,size=__UpperCamelCase     ,default_to_square=__UpperCamelCase			)
        else:
             if "shortest_edge" in size:
                  lowercase_	:				Optional[int]													=	get_resize_output_image_size(__UpperCamelCase     ,size=size['shortest_edge']     ,default_to_square=__UpperCamelCase			)
             elif "height" in size and "width" in size:
                  lowercase_	:				Dict													=	(size['height'], size['width'])
             else:
                  raise ValueError('Invalid size for resize: {}'.format(__UpperCamelCase			)			)

        return resize(__UpperCamelCase     ,size=__UpperCamelCase     ,resample=__UpperCamelCase     ,data_format=__UpperCamelCase     ,**__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase = None     ,**__UpperCamelCase     ,)	->      np.ndarray:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	get_size_dict(__UpperCamelCase			)
        if "height" not in size or "width" not in size:
             raise ValueError(f'''size must contain \'height\' and \'width\' as keys. Got {size.keys()}'''			)
        return center_crop(__UpperCamelCase     ,size=(size['height'], size['width'])     ,data_format=__UpperCamelCase     ,**__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase = None     ,**__UpperCamelCase     ,)	->      str:


        '''simple docstring'''


        return rescale(__UpperCamelCase     ,scale=__UpperCamelCase     ,data_format=__UpperCamelCase     ,**__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase = None     ,**__UpperCamelCase     ,)	->      np.ndarray:


        '''simple docstring'''


        return normalize(__UpperCamelCase     ,mean=__UpperCamelCase     ,std=__UpperCamelCase     ,data_format=__UpperCamelCase     ,**__UpperCamelCase			)







   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = None     ,__UpperCamelCase = ChannelDimension.FIRST     ,**__UpperCamelCase     ,)	->      PIL.Image.Image:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	do_resize if do_resize is not None else self.do_resize
        lowercase_	:				Optional[int]													=	crop_pct if crop_pct is not None else self.crop_pct
        lowercase_	:				List[str]													=	resample if resample is not None else self.resample
        lowercase_	:				str													=	do_center_crop if do_center_crop is not None else self.do_center_crop
        lowercase_	:				Tuple													=	do_rescale if do_rescale is not None else self.do_rescale
        lowercase_	:				Union[str, Any]													=	rescale_factor if rescale_factor is not None else self.rescale_factor
        lowercase_	:				str													=	do_normalize if do_normalize is not None else self.do_normalize
        lowercase_	:				str													=	image_mean if image_mean is not None else self.image_mean
        lowercase_	:				Tuple													=	image_std if image_std is not None else self.image_std

        lowercase_	:				Optional[Any]													=	size if size is not None else self.size
        lowercase_	:				Tuple													=	get_size_dict(__UpperCamelCase     ,default_to_square=__UpperCamelCase			)
        lowercase_	:				Union[str, Any]													=	crop_size if crop_size is not None else self.crop_size
        lowercase_	:				List[str]													=	get_size_dict(__UpperCamelCase     ,param_name='crop_size'			)

        lowercase_	:				str													=	make_list_of_images(__UpperCamelCase			)

        if not valid_images(__UpperCamelCase			):
             raise ValueError(
                 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
                 'torch.Tensor, tf.Tensor or jax.ndarray.'			)

        if do_resize and size is None or resample is None:
             raise ValueError('Size and resample must be specified if do_resize is True.'			)

        if do_center_crop and crop_pct is None:
             raise ValueError('Crop_pct must be specified if do_center_crop is True.'			)

        if do_rescale and rescale_factor is None:
             raise ValueError('Rescale factor must be specified if do_rescale is True.'			)

        if do_normalize and (image_mean is None or image_std is None):
             raise ValueError('Image mean and std must be specified if do_normalize is True.'			)

        # All transformations expect numpy arrays.
        lowercase_	:				Optional[Any]													=	[to_numpy_array(__UpperCamelCase			) for image in images]

        if do_resize:
             lowercase_	:				str													=	[self.resize(image=__UpperCamelCase     ,size=__UpperCamelCase     ,crop_pct=__UpperCamelCase     ,resample=__UpperCamelCase			) for image in images]

        if do_center_crop:
             lowercase_	:				str													=	[self.center_crop(image=__UpperCamelCase     ,size=__UpperCamelCase			) for image in images]

        if do_rescale:
             lowercase_	:				Any													=	[self.rescale(image=__UpperCamelCase     ,scale=__UpperCamelCase			) for image in images]

        if do_normalize:
             lowercase_	:				int													=	[self.normalize(image=__UpperCamelCase     ,mean=__UpperCamelCase     ,std=__UpperCamelCase			) for image in images]

        lowercase_	:				Dict													=	[to_channel_dimension_format(__UpperCamelCase     ,__UpperCamelCase			) for image in images]

        lowercase_	:				Any													=	{'pixel_values': images}
        return BatchFeature(data=__UpperCamelCase     ,tensor_type=__UpperCamelCase			)

