





'''simple docstring'''

from copy import deepcopy
from typing import Optional, Union

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_tf_available, is_torch_available


if is_torch_available():
      import torch

if is_tf_available():
      import tensorflow as tf


class 					a_     (				snake_case_       ):

    '''simple docstring'''
    UpperCamelCase     = ['''image_processor''']
    UpperCamelCase     = '''SamImageProcessor'''


    def __init__(		self ,		A       )		->   Any:
        super().__init__(A       )
        _SCREAMING_SNAKE_CASE									=			self.image_processor
        _SCREAMING_SNAKE_CASE									=			-10
        _SCREAMING_SNAKE_CASE									=			self.image_processor.size["""longest_edge"""]


    def __call__(		self ,		A=None ,		A=None ,		A=None ,		A=None ,		A = None ,		**A ,		)		->   BatchEncoding:
        _SCREAMING_SNAKE_CASE									=			self.image_processor(
            A ,		return_tensors=A ,		**A ,		)

        # pop arguments that are not used in the foward but used nevertheless
        _SCREAMING_SNAKE_CASE									=			encoding_image_processor["""original_sizes"""]

        if hasattr(A ,		"""numpy"""       ):  # Checks if Torch or TF tensor
            _SCREAMING_SNAKE_CASE									=			original_sizes.numpy()

        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			self._check_and_preprocess_points(
            input_points=A ,		input_labels=A ,		input_boxes=A ,		)

        _SCREAMING_SNAKE_CASE									=			self._normalize_and_convert(
            A ,		A ,		input_points=A ,		input_labels=A ,		input_boxes=A ,		return_tensors=A ,		)

        return encoding_image_processor


    def 			snake_case_(		self ,		A ,		A ,		A=None ,		A=None ,		A=None ,		A="pt" ,		)		->   int:
        if input_points is not None:
            if len(A       ) != len(A       ):
                _SCREAMING_SNAKE_CASE									=			[
                    self._normalize_coordinates(self.target_size ,		A ,		original_sizes[0]       ) for point in input_points
                ]
            else:
                _SCREAMING_SNAKE_CASE									=			[
                    self._normalize_coordinates(self.target_size ,		A ,		A       )
                    for point, original_size in zip(A ,		A       )
                ]
            # check that all arrays have the same shape
            if not all(point.shape == input_points[0].shape for point in input_points       ):
                if input_labels is not None:
                    _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			self._pad_points_and_labels(A ,		A       )

            _SCREAMING_SNAKE_CASE									=			np.array(A       )

        if input_labels is not None:
            _SCREAMING_SNAKE_CASE									=			np.array(A       )

        if input_boxes is not None:
            if len(A       ) != len(A       ):
                _SCREAMING_SNAKE_CASE									=			[
                    self._normalize_coordinates(self.target_size ,		A ,		original_sizes[0] ,		is_bounding_box=A       )
                    for box in input_boxes
                ]
            else:
                _SCREAMING_SNAKE_CASE									=			[
                    self._normalize_coordinates(self.target_size ,		A ,		A ,		is_bounding_box=A       )
                    for box, original_size in zip(A ,		A       )
                ]
            _SCREAMING_SNAKE_CASE									=			np.array(A       )

        if input_boxes is not None:
            if return_tensors == "pt":
                _SCREAMING_SNAKE_CASE									=			torch.from_numpy(A       )
                # boxes batch size of 1 by default
                _SCREAMING_SNAKE_CASE									=			input_boxes.unsqueeze(1       ) if len(input_boxes.shape       ) != 3 else input_boxes
            elif return_tensors == "tf":
                _SCREAMING_SNAKE_CASE									=			tf.convert_to_tensor(A       )
                # boxes batch size of 1 by default
                _SCREAMING_SNAKE_CASE									=			tf.expand_dims(A ,		1       ) if len(input_boxes.shape       ) != 3 else input_boxes
            encoding_image_processor.update({"""input_boxes""": input_boxes}       )
        if input_points is not None:
            if return_tensors == "pt":
                _SCREAMING_SNAKE_CASE									=			torch.from_numpy(A       )
                # point batch size of 1 by default
                _SCREAMING_SNAKE_CASE									=			input_points.unsqueeze(1       ) if len(input_points.shape       ) != 4 else input_points
            elif return_tensors == "tf":
                _SCREAMING_SNAKE_CASE									=			tf.convert_to_tensor(A       )
                # point batch size of 1 by default
                _SCREAMING_SNAKE_CASE									=			tf.expand_dims(A ,		1       ) if len(input_points.shape       ) != 4 else input_points
            encoding_image_processor.update({"""input_points""": input_points}       )
        if input_labels is not None:
            if return_tensors == "pt":
                _SCREAMING_SNAKE_CASE									=			torch.from_numpy(A       )
                # point batch size of 1 by default
                _SCREAMING_SNAKE_CASE									=			input_labels.unsqueeze(1       ) if len(input_labels.shape       ) != 3 else input_labels
            elif return_tensors == "tf":
                _SCREAMING_SNAKE_CASE									=			tf.convert_to_tensor(A       )
                # point batch size of 1 by default
                _SCREAMING_SNAKE_CASE									=			tf.expand_dims(A ,		1       ) if len(input_labels.shape       ) != 3 else input_labels
            encoding_image_processor.update({"""input_labels""": input_labels}       )

        return encoding_image_processor


    def 			snake_case_(		self ,		A ,		A       )		->   Dict:
        _SCREAMING_SNAKE_CASE									=			max([point.shape[0] for point in input_points]       )
        _SCREAMING_SNAKE_CASE									=			[]
        for i, point in enumerate(A       ):
            if point.shape[0] != expected_nb_points:
                _SCREAMING_SNAKE_CASE									=			np.concatenate(
                    [point, np.zeros((expected_nb_points - point.shape[0], 2)       ) + self.point_pad_value] ,		axis=0       )
                _SCREAMING_SNAKE_CASE									=			np.append(input_labels[i] ,		[self.point_pad_value]       )
            processed_input_points.append(A       )
        _SCREAMING_SNAKE_CASE									=			processed_input_points
        return input_points, input_labels


    def 			snake_case_(		self ,		A ,		A ,		A ,		A=False       )		->   np.ndarray:
        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			original_size
        _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE									=			self.image_processor._get_preprocess_shape(A ,		longest_edge=A       )
        _SCREAMING_SNAKE_CASE									=			deepcopy(A       ).astype(A       )

        if is_bounding_box:
            _SCREAMING_SNAKE_CASE									=			coords.reshape(-1 ,		2 ,		2       )

        _SCREAMING_SNAKE_CASE									=			coords[..., 0] * (new_w / old_w)
        _SCREAMING_SNAKE_CASE									=			coords[..., 1] * (new_h / old_h)

        if is_bounding_box:
            _SCREAMING_SNAKE_CASE									=			coords.reshape(-1 ,		4       )

        return coords


    def 			snake_case_(		self ,		A=None ,		A=None ,		A=None ,		)		->   List[str]:
        if input_points is not None:
            if hasattr(A ,		"""numpy"""       ):  # Checks for TF or Torch tensor
                _SCREAMING_SNAKE_CASE									=			input_points.numpy().tolist()

            if not isinstance(A ,		A       ) or not isinstance(input_points[0] ,		A       ):
                raise ValueError("""Input points must be a list of list of floating points."""       )
            _SCREAMING_SNAKE_CASE									=			[np.array(A       ) for input_point in input_points]
        else:
            _SCREAMING_SNAKE_CASE									=			None

        if input_labels is not None:
            if hasattr(A ,		"""numpy"""       ):
                _SCREAMING_SNAKE_CASE									=			input_labels.numpy().tolist()

            if not isinstance(A ,		A       ) or not isinstance(input_labels[0] ,		A       ):
                raise ValueError("""Input labels must be a list of list integers."""       )
            _SCREAMING_SNAKE_CASE									=			[np.array(A       ) for label in input_labels]
        else:
            _SCREAMING_SNAKE_CASE									=			None

        if input_boxes is not None:
            if hasattr(A ,		"""numpy"""       ):
                _SCREAMING_SNAKE_CASE									=			input_boxes.numpy().tolist()

            if (
                not isinstance(A ,		A       )
                or not isinstance(input_boxes[0] ,		A       )
                or not isinstance(input_boxes[0][0] ,		A       )
            ):
                raise ValueError("""Input boxes must be a list of list of list of floating points."""       )
            _SCREAMING_SNAKE_CASE									=			[np.array(A       ).astype(np.floataa       ) for box in input_boxes]
        else:
            _SCREAMING_SNAKE_CASE									=			None

        return input_points, input_labels, input_boxes


    @property
    def 			snake_case_(		self       )		->   Optional[Any]:
        _SCREAMING_SNAKE_CASE									=			self.image_processor.model_input_names
        return list(dict.fromkeys(A       )       )





    def 			snake_case_(		self ,		*A ,		**A       )		->   str:
        return self.image_processor.post_process_masks(*A ,		**A       )








'''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				(   A__    ,						A__    ,						A__=1e-1_2    )       ->	Dict:






   """simple docstring"""
   UpperCamelCase					=  jnp.divide(emb_a.T    ,						jnp.clip(jnp.linalg.norm(A__    ,						axis=1    )    ,						a_min=A__    )    ).T
   UpperCamelCase					=  jnp.divide(emb_a.T    ,						jnp.clip(jnp.linalg.norm(A__    ,						axis=1    )    ,						a_min=A__    )    ).T
   return jnp.matmul(A__    ,						norm_emb_a.T    )

class  SCREAMING_SNAKE_CASE (  nn.Module		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  42
    _SCREAMING_SNAKE_CASE	  =  jnp.floataa






    def  A       (  self      :					List[Any] ):


       """simple docstring"""







       UpperCamelCase					=  FlaxCLIPVisionModule(self.config.vision_config )
       UpperCamelCase					=  nn.Dense(self.config.projection_dim  ,						use_bias=UpperCamelCase__  ,						dtype=self.dtype )

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

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






    def __call__(  self      :					str  ,						UpperCamelCase__      :					List[str] ):


       """simple docstring"""







       UpperCamelCase					=  self.vision_model(UpperCamelCase__ )[1]
       UpperCamelCase					=  self.visual_projection(UpperCamelCase__ )

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

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

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

       return has_nsfw_concepts

class  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  CLIPConfig
    _SCREAMING_SNAKE_CASE	  =  """clip_input"""
    _SCREAMING_SNAKE_CASE	  =  FlaxStableDiffusionSafetyCheckerModule






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


       """simple docstring"""







       if input_shape is None:
          UpperCamelCase					=  (1, 2_2_4, 2_2_4, 3)
       UpperCamelCase					=  self.module_class(config=UpperCamelCase__  ,						dtype=UpperCamelCase__  ,						**UpperCamelCase__ )
       super().__init__(UpperCamelCase__  ,						UpperCamelCase__  ,						input_shape=UpperCamelCase__  ,						seed=UpperCamelCase__  ,						dtype=UpperCamelCase__  ,						_do_init=_do_init )






    def  A       (  self      :					int  ,						UpperCamelCase__      :					jax.random.KeyArray  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					FrozenDict = None ):


       """simple docstring"""







       UpperCamelCase					=  jax.random.normal(UpperCamelCase__  ,						UpperCamelCase__ )

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

       UpperCamelCase					=  self.module.init(UpperCamelCase__  ,						UpperCamelCase__ )['params']

       return random_params






    def __call__(  self      :					List[Any]  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					dict = None  ,						):


       """simple docstring"""







       UpperCamelCase					=  jnp.transpose(UpperCamelCase__  ,						(0, 2, 3, 1) )

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

