



"""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__			(     lowerCamelCase__				,      lowerCamelCase__				,      lowerCamelCase__=1E-1_2			) ->							Any:
							A         =					jnp.divide(emb_a.T				,      jnp.clip(jnp.linalg.norm(lowerCamelCase__				,      axis=1			)				,      a_min=lowerCamelCase__			)			).T
							A         =					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     ):
		lowerCAmelCase_       :	CLIPConfig
		lowerCAmelCase_       :	jnp.dtype 							=     jnp.floataa



		def 					A_		( self  :    Any				)			->						List[str]:






									'''simple docstring'''

									A         =					FlaxCLIPVisionModule(self.config.vision_config				)
									A         =					nn.Dense(self.config.projection_dim      ,							use_bias=snake_case      ,							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  :    str      ,							snake_case  :    str				)			->						Union[str, Any]:






									'''simple docstring'''

									A         =					self.vision_model(snake_case				)[1]
									A         =					self.visual_projection(snake_case				)

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

									A         =					special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
									A         =					jnp.round(snake_case      ,							3				)
									A         =					jnp.any(special_scores > 0      ,							axis=1      ,							keepdims=snake_case				)
									# 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(snake_case      ,							3				)
									A         =					jnp.any(concept_scores > 0      ,							axis=1				)

									return has_nsfw_concepts






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	Dict 							=     CLIPConfig
		lowerCAmelCase_       :	Dict 							=     """clip_input"""
		lowerCAmelCase_       :	List[str] 							=     FlaxStableDiffusionSafetyCheckerModule



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






									'''simple docstring'''

									if input_shape is None:
																A         =					(1, 224, 224, 3)
									A         =					self.module_class(config=snake_case      ,							dtype=snake_case      ,							**snake_case				)
									super().__init__(snake_case      ,							snake_case      ,							input_shape=snake_case      ,							seed=snake_case      ,							dtype=snake_case      ,							_do_init=_do_init				)



		def 					A_		( self  :    List[Any]      ,							snake_case  :    jax.random.KeyArray      ,							snake_case  :    Tuple      ,							snake_case  :    FrozenDict = None				)			->						FrozenDict:






									'''simple docstring'''

									A         =					jax.random.normal(snake_case      ,							snake_case				)

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

									A         =					self.module.init(snake_case      ,							snake_case				)['params']

									return random_params



		def __call__( self  :    Optional[Any]      ,							snake_case  :    Union[str, Any]      ,							snake_case  :    dict = None      ,							)			->						Optional[int]:






									'''simple docstring'''

									A         =					jnp.transpose(snake_case      ,							(0, 2, 3, 1)				)

									return self.module.apply(
									    {'params': params or self.params}      ,							jnp.array(snake_case      ,							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,
    is_batched,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


A    =			logging.get_logger(__name__)






class      UpperCAmelCase__		(      UpperCamelCase     ):
		lowerCAmelCase_       :	Tuple 							=     ["""pixel_values"""]



		def __init__( self  :    int      ,							snake_case  :    bool = True      ,							snake_case  :    Optional[Dict[str, int]] = None      ,							snake_case  :    PILImageResampling = PILImageResampling.BICUBIC      ,							snake_case  :    bool = True      ,							snake_case  :    bool = True      ,							snake_case  :    Union[int, float] = 1 / 255      ,							snake_case  :    Dict[str, int] = None      ,							snake_case  :    bool = True      ,							snake_case  :    Optional[Union[float, List[float]]] = None      ,							snake_case  :    Optional[Union[float, List[float]]] = None      ,							**snake_case  :    Union[str, Any]      ,							)			->						None:






									'''simple docstring'''

									super().__init__(**snake_case				)
									A         =					size if size is not None else {'height': 224, 'width': 224}
									A         =					get_size_dict(snake_case				)
									A         =					crop_size if crop_size is not None else {'height': 224, 'width': 224}
									A         =					get_size_dict(snake_case      ,							default_to_square=snake_case      ,							param_name='crop_size'				)

									A         =					do_resize
									A         =					do_rescale
									A         =					do_normalize
									A         =					do_center_crop
									A         =					crop_size
									A         =					size
									A         =					resample
									A         =					rescale_factor
									A         =					image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
									A         =					image_std if image_std is not None else IMAGENET_DEFAULT_STD



		def 					A_		( self  :    Union[str, Any]      ,							snake_case  :    np.ndarray      ,							snake_case  :    Dict[str, int]      ,							snake_case  :    PILImageResampling = PILImageResampling.BILINEAR      ,							snake_case  :    Optional[Union[str, ChannelDimension]] = None      ,							**snake_case  :    Dict      ,							)			->						np.ndarray:






									'''simple docstring'''

									A         =					get_size_dict(snake_case				)

									if "shortest_edge" in size:
																A         =					get_resize_output_image_size(snake_case      ,							size=size['shortest_edge']      ,							default_to_square=snake_case				)
																# size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
									elif "height" in size and "width" in size:
																A         =					(size['height'], size['width'])
									else:
																raise ValueError(f"""Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}"""				)
									return resize(snake_case      ,							size=snake_case      ,							resample=snake_case      ,							data_format=snake_case      ,							**snake_case				)



		def 					A_		( self  :    Union[str, Any]      ,							snake_case  :    np.ndarray      ,							snake_case  :    Dict[str, int]      ,							snake_case  :    Optional[Union[str, ChannelDimension]] = None      ,							**snake_case  :    List[Any]      ,							)			->						np.ndarray:






									'''simple docstring'''

									A         =					get_size_dict(snake_case				)
									if "height" not in size or "width" not in size:
																raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}"""				)
									return center_crop(snake_case      ,							size=(size['height'], size['width'])      ,							data_format=snake_case      ,							**snake_case				)



		def 					A_		( self  :    Dict      ,							snake_case  :    np.ndarray      ,							snake_case  :    float      ,							snake_case  :    Optional[Union[str, ChannelDimension]] = None      ,							**snake_case  :    Dict				)			->						np.ndarray:






									'''simple docstring'''

									return rescale(snake_case      ,							scale=snake_case      ,							data_format=snake_case      ,							**snake_case				)



		def 					A_		( self  :    Union[str, Any]      ,							snake_case  :    np.ndarray      ,							snake_case  :    Union[float, List[float]]      ,							snake_case  :    Union[float, List[float]]      ,							snake_case  :    Optional[Union[str, ChannelDimension]] = None      ,							**snake_case  :    Union[str, Any]      ,							)			->						np.ndarray:






									'''simple docstring'''

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



		def 					A_		( self  :    int      ,							snake_case  :    ImageInput      ,							snake_case  :    Optional[bool] = None      ,							snake_case  :    Dict[str, int] = None      ,							snake_case  :    PILImageResampling = None      ,							snake_case  :    bool = None      ,							snake_case  :    int = None      ,							snake_case  :    Optional[bool] = None      ,							snake_case  :    Optional[float] = None      ,							snake_case  :    Optional[bool] = None      ,							snake_case  :    Optional[Union[float, List[float]]] = None      ,							snake_case  :    Optional[Union[float, List[float]]] = None      ,							snake_case  :    Optional[Union[str, TensorType]] = None      ,							snake_case  :    Union[str, ChannelDimension] = ChannelDimension.FIRST      ,							**snake_case  :    List[str]      ,							)			->						BatchFeature:






									'''simple docstring'''

									A         =					do_resize if do_resize is not None else self.do_resize
									A         =					do_rescale if do_rescale is not None else self.do_rescale
									A         =					do_normalize if do_normalize is not None else self.do_normalize
									A         =					do_center_crop if do_center_crop is not None else self.do_center_crop
									A         =					crop_size if crop_size is not None else self.crop_size
									A         =					get_size_dict(snake_case      ,							param_name='crop_size'      ,							default_to_square=snake_case				)
									A         =					resample if resample is not None else self.resample
									A         =					rescale_factor if rescale_factor is not None else self.rescale_factor
									A         =					image_mean if image_mean is not None else self.image_mean
									A         =					image_std if image_std is not None else self.image_std

									A         =					size if size is not None else self.size
									A         =					get_size_dict(snake_case				)

									if not is_batched(snake_case				):
																A         =					[images]

									if not valid_images(snake_case				):
																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:
																raise ValueError('Size must be specified if do_resize is True.'				)

									if do_center_crop and crop_size is None:
																raise ValueError('Crop size 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.'				)

									# All transformations expect numpy arrays.
									A         =					[to_numpy_array(snake_case				) for image in images]

									if do_resize:
																A         =					[self.resize(image=snake_case      ,							size=snake_case      ,							resample=snake_case				) for image in images]

									if do_center_crop:
																A         =					[self.center_crop(image=snake_case      ,							size=snake_case				) for image in images]

									if do_rescale:
																A         =					[self.rescale(image=snake_case      ,							scale=snake_case				) for image in images]

									if do_normalize:
																A         =					[self.normalize(image=snake_case      ,							mean=snake_case      ,							std=snake_case				) for image in images]

									A         =					[to_channel_dimension_format(snake_case      ,							snake_case				) for image in images]

									A         =					{'pixel_values': images}
									return BatchFeature(data=snake_case      ,							tensor_type=snake_case				)



