'''simple docstring'''




from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


__lowercase          =  logging.get_logger(__name__)






class 				a__(					lowerCAmelCase__	):


			'''simple docstring'''






			def 							a_       (   self       ,    __lowerCAmelCase):




					"""simple docstring"""


					if isinstance(__lowerCAmelCase       ,    __lowerCAmelCase):
							lowerCAmelCase   					=  [label.strip() for label in labels.split(""",""") if label.strip()]
					return labels







			def __call__(   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase):




					"""simple docstring"""


					if len(__lowerCAmelCase) == 0 or len(__lowerCAmelCase) == 0:
							raise ValueError("""You must include at least one label and at least one sequence.""")
					if hypothesis_template.format(labels[0]) == hypothesis_template:
							raise ValueError(
							    (
							        """The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. """
							        """Make sure the passed template includes formatting syntax such as {{}} where the label should go."""
							    ).format(__lowerCAmelCase))

					if isinstance(__lowerCAmelCase       ,    __lowerCAmelCase):
							lowerCAmelCase   					=  [sequences]

					lowerCAmelCase   					=  []
					for sequence in sequences:
							sequence_pairs.extend([[sequence, hypothesis_template.format(__lowerCAmelCase)] for label in labels])

					return sequence_pairs, sequences







@add_end_docstrings(lowerCAmelCase__	)
class 				a__(					lowerCAmelCase__	):


			'''simple docstring'''






			def __init__(   self       ,    __lowerCAmelCase=ZeroShotClassificationArgumentHandler()       ,    *__lowerCAmelCase       ,    **__lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  args_parser
					super().__init__(*__lowerCAmelCase       ,    **__lowerCAmelCase)
					if self.entailment_id == -1:
							logger.warning(
							    """Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to """
							    """-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.""")



			@property
			def 							a_       (   self):




					"""simple docstring"""


					for label, ind in self.model.config.labelaid.items():
							if label.lower().startswith("""entail"""):
									return ind
					return -1



			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase=True       ,    __lowerCAmelCase=True       ,    __lowerCAmelCase=TruncationStrategy.ONLY_FIRST       ,    **__lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  self.framework
					if self.tokenizer.pad_token is None:
							# Override for tokenizers not supporting padding
							logger.error(
							    """Tokenizer was not supporting padding necessary for zero-shot, attempting to use """
							    """ `pad_token=eos_token`""")
							lowerCAmelCase   					=  self.tokenizer.eos_token
					try:
							lowerCAmelCase   					=  self.tokenizer(
							    __lowerCAmelCase       ,    add_special_tokens=__lowerCAmelCase       ,    return_tensors=__lowerCAmelCase       ,    padding=__lowerCAmelCase       ,    truncation=__lowerCAmelCase       ,    )
					except Exception as e:
							if "too short" in str(__lowerCAmelCase):
									# tokenizers might yell that we want to truncate
									# to a value that is not even reached by the input.
									# In that case we don't want to truncate.
									# It seems there's not a really better way to catch that
									# exception.

									lowerCAmelCase   					=  self.tokenizer(
									    __lowerCAmelCase       ,    add_special_tokens=__lowerCAmelCase       ,    return_tensors=__lowerCAmelCase       ,    padding=__lowerCAmelCase       ,    truncation=TruncationStrategy.DO_NOT_TRUNCATE       ,    )
							else:
									raise e

					return inputs



			def 							a_       (   self       ,    **__lowerCAmelCase):




					"""simple docstring"""


					if kwargs.get("""multi_class"""       ,    __lowerCAmelCase) is not None:
							lowerCAmelCase   					=  kwargs["""multi_class"""]
							logger.warning(
							    """The `multi_class` argument has been deprecated and renamed to `multi_label`. """
							    """`multi_class` will be removed in a future version of Transformers.""")
					lowerCAmelCase   					=  {}
					if "candidate_labels" in kwargs:
							lowerCAmelCase   					=  self._args_parser._parse_labels(kwargs["""candidate_labels"""])
					if "hypothesis_template" in kwargs:
							lowerCAmelCase   					=  kwargs["""hypothesis_template"""]

					lowerCAmelCase   					=  {}
					if "multi_label" in kwargs:
							lowerCAmelCase   					=  kwargs["""multi_label"""]
					return preprocess_params, {}, postprocess_params



			def __call__(   self       ,    __lowerCAmelCase       ,    *__lowerCAmelCase       ,    **__lowerCAmelCase       ,    ):




					"""simple docstring"""


					if len(__lowerCAmelCase) == 0:
							pass
					elif len(__lowerCAmelCase) == 1 and "candidate_labels" not in kwargs:
							lowerCAmelCase   					=  args[0]
					else:
							raise ValueError(f"Unable to understand extra arguments {args}")

					return super().__call__(__lowerCAmelCase       ,    **__lowerCAmelCase)



			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase="This example is {}."):




					"""simple docstring"""


					lowerCAmelCase					,     lowerCAmelCase   					=  self._args_parser(__lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase)

					for i, (candidate_label, sequence_pair) in enumerate(zip(__lowerCAmelCase       ,    __lowerCAmelCase)):
							lowerCAmelCase   					=  self._parse_and_tokenize([sequence_pair])

							yield {
							    "candidate_label": candidate_label,
							    "sequence": sequences[0],
							    "is_last": i == len(__lowerCAmelCase) - 1,
							    **model_input,
							}



			def 							a_       (   self       ,    __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  inputs["""candidate_label"""]
					lowerCAmelCase   					=  inputs["""sequence"""]
					lowerCAmelCase   					=  {k: inputs[k] for k in self.tokenizer.model_input_names}
					lowerCAmelCase   					=  self.model(**__lowerCAmelCase)

					lowerCAmelCase   					=  {
					    """candidate_label""": candidate_label,
					    """sequence""": sequence,
					    """is_last""": inputs["""is_last"""],
					    **outputs,
					}
					return model_outputs







			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase=False):




					"""simple docstring"""


					lowerCAmelCase   					=  [outputs["""candidate_label"""] for outputs in model_outputs]
					lowerCAmelCase   					=  [outputs["""sequence"""] for outputs in model_outputs]
					lowerCAmelCase   					=  np.concatenate([output["""logits"""].numpy() for output in model_outputs])
					lowerCAmelCase   					=  logits.shape[0]
					lowerCAmelCase   					=  len(__lowerCAmelCase)
					lowerCAmelCase   					=  N // n
					lowerCAmelCase   					=  logits.reshape((num_sequences, n, -1))

					if multi_label or len(__lowerCAmelCase) == 1:
							# softmax over the entailment vs. contradiction dim for each label independently
							lowerCAmelCase   					=  self.entailment_id
							lowerCAmelCase   					=  -1 if entailment_id == 0 else 0
							lowerCAmelCase   					=  reshaped_outputs[..., [contradiction_id, entailment_id]]
							lowerCAmelCase   					=  np.exp(__lowerCAmelCase) / np.exp(__lowerCAmelCase).sum(-1       ,    keepdims=__lowerCAmelCase)
							lowerCAmelCase   					=  scores[..., 1]
					else:
							# softmax the "entailment" logits over all candidate labels
							lowerCAmelCase   					=  reshaped_outputs[..., self.entailment_id]
							lowerCAmelCase   					=  np.exp(__lowerCAmelCase) / np.exp(__lowerCAmelCase).sum(-1       ,    keepdims=__lowerCAmelCase)

					lowerCAmelCase   					=  list(reversed(scores[0].argsort()))
					return {
					    "sequence": sequences[0],
					    "labels": [candidate_labels[i] for i in top_inds],
					    "scores": scores[0, top_inds].tolist(),
					}





'''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 				snake_case__							(			_A:					Union[str, Any]      ,   _A:					Tuple      ,   _A:					Any=1e-12 )    ->	str:

		'''simple docstring'''


		lowerCAmelCase   					=  jnp.divide(emb_a.T      ,   jnp.clip(jnp.linalg.norm(_A      ,   axis=1 )      ,   a_min=_A ) ).T
		lowerCAmelCase   					=  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 				a__(					nn.Module	):


			'''simple docstring'''






			UpperCAmelCase_			:     CLIPConfig
			UpperCAmelCase_			:     jnp.dtype      =       jnp.floataa



			def 							a_       (   self):




					"""simple docstring"""


					lowerCAmelCase   					=  FlaxCLIPVisionModule(self.config.vision_config)
					lowerCAmelCase   					=  nn.Dense(self.config.projection_dim       ,    use_bias=__lowerCAmelCase       ,    dtype=self.dtype)

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

					lowerCAmelCase   					=  self.param("""concept_embeds_weights"""       ,    jax.nn.initializers.ones       ,    (17,))
					lowerCAmelCase   					=  self.param("""special_care_embeds_weights"""       ,    jax.nn.initializers.ones       ,    (3,))







			def __call__(   self       ,    __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  self.vision_model(__lowerCAmelCase)[1]
					lowerCAmelCase   					=  self.visual_projection(__lowerCAmelCase)

					lowerCAmelCase   					=  jax_cosine_distance(__lowerCAmelCase       ,    self.special_care_embeds)
					lowerCAmelCase   					=  jax_cosine_distance(__lowerCAmelCase       ,    self.concept_embeds)

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

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

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

					return has_nsfw_concepts







class 				a__(					lowerCAmelCase__	):


			'''simple docstring'''






			UpperCAmelCase_			:     int      =       CLIPConfig
			UpperCAmelCase_			:     Any      =       '''clip_input'''
			UpperCAmelCase_			:     List[str]      =       FlaxStableDiffusionSafetyCheckerModule



			def __init__(   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase = None       ,    __lowerCAmelCase = 0       ,    __lowerCAmelCase = jnp.floataa       ,    __lowerCAmelCase = True       ,    **__lowerCAmelCase       ,    ):




					"""simple docstring"""


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



			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase = None):




					"""simple docstring"""


					lowerCAmelCase   					=  jax.random.normal(__lowerCAmelCase       ,    __lowerCAmelCase)

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

					lowerCAmelCase   					=  self.module.init(__lowerCAmelCase       ,    __lowerCAmelCase)["""params"""]

					return random_params







			def __call__(   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase = None       ,    ):




					"""simple docstring"""


					lowerCAmelCase   					=  jnp.transpose(__lowerCAmelCase       ,    (0, 2, 3, 1))

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




