
import math

import tensorflow as tf
from packaging import version




def 	A_ (							snake_case							:   List[Any] )      ->    Optional[int]:



						'''simple docstring'''

						__UpperCamelCase       =			tf.convert_to_tensor(__UpperCamelCase )
						__UpperCamelCase       =			0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) ,      x.dtype ) ))

						return x * cdf




def 	A_ (							snake_case							:   int )      ->    Union[str, Any]:



						'''simple docstring'''

						__UpperCamelCase       =			tf.convert_to_tensor(__UpperCamelCase )
						__UpperCamelCase       =			tf.cast(math.pi ,      x.dtype )
						__UpperCamelCase       =			tf.cast(0.044715 ,      x.dtype )
						__UpperCamelCase       =			0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(__UpperCamelCase ,      3 )) ))

						return x * cdf




def 	A_ (							snake_case							:   Dict )      ->    str:



						'''simple docstring'''

						__UpperCamelCase       =			tf.convert_to_tensor(__UpperCamelCase )

						return x * tf.tanh(tf.math.softplus(__UpperCamelCase ) )




def 	A_ (							snake_case							:   List[Any] )      ->    List[Any]:



						'''simple docstring'''

						__UpperCamelCase       =			tf.convert_to_tensor(__UpperCamelCase )
						__UpperCamelCase       =			tf.cast(0.044715 ,      x.dtype )
						__UpperCamelCase       =			tf.cast(0.7978845608 ,      x.dtype )

						return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) ))




def 	A_ (							snake_case							:   Dict )      ->    List[str]:



						'''simple docstring'''

						__UpperCamelCase       =			tf.convert_to_tensor(__UpperCamelCase )
						__UpperCamelCase       =			tf.cast(1.702 ,      x.dtype )
						return x * tf.math.sigmoid(coeff * x )




def 	A_ (							snake_case							:   List[Any] )      ->    List[Any]:



						'''simple docstring'''

						return tf.clip_by_value(_gelu(__UpperCamelCase ) ,      -10 ,      10 )




def 	A_ (							snake_case							:   Tuple ,      snake_case							:   Union[str, Any]=-1 )      ->    Any:



						'''simple docstring'''

						__UpperCamelCase  ,							__UpperCamelCase       =			tf.split(__UpperCamelCase ,      2 ,      axis=__UpperCamelCase )
						return a * tf.math.sigmoid(__UpperCamelCase )


if version.parse(tf.version.VERSION) >= version.parse("2.4"):




				def 	A_ (							snake_case							:   List[str] )      ->    Union[str, Any]:



										'''simple docstring'''

										return tf.keras.activations.gelu(__UpperCamelCase ,      approximate=__UpperCamelCase )

				lowercase__							:							Optional[Any]									=			tf.keras.activations.gelu



				lowercase__							:							int									=			approximate_gelu_wrap
else:
				lowercase__							:							List[Any]									=			_gelu
				lowercase__							:							List[str]									=			_gelu_new


lowercase__							:							Any									=			{
    "gelu": gelu,
    "gelu_10": gelu_aa,
    "gelu_fast": gelu_fast,
    "gelu_new": gelu_new,
    "glu": glu,
    "mish": mish,
    "quick_gelu": quick_gelu,
    "relu": tf.keras.activations.relu,
    "sigmoid": tf.keras.activations.sigmoid,
    "silu": tf.keras.activations.swish,
    "swish": tf.keras.activations.swish,
    "tanh": tf.keras.activations.tanh,
}




def 	A_ (							snake_case							:   str )      ->    str:



						'''simple docstring'''

						if activation_string in ACTaFN:
												return ACTaFN[activation_string]
						else:
												raise KeyError(f"function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}" )





from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
				from PIL import Image

				from ..image_utils import load_image

if is_torch_available():
				from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
				from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
				from ..tf_utils import stable_softmax

lowercase__							:							int									=			logging.get_logger(__name__)






@add_end_docstrings(SCREAMING_SNAKE_CASE_    )
class        SCREAMING_SNAKE_CASE__    (							SCREAMING_SNAKE_CASE_    ):

							"""simple docstring"""






							def __init__(  self     ,	**SCREAMING_SNAKE_CASE_			)->   Tuple:





													'''simple docstring'''






													super().__init__(**SCREAMING_SNAKE_CASE_			)

													requires_backends(self     ,	'''vision'''			)
													self.check_model_type(
													    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
													    if self.framework == '''tf'''
													    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING			)



							def __call__(  self     ,	SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_			)->   str:





													'''simple docstring'''






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



							def     A__		(  self     ,	**SCREAMING_SNAKE_CASE_			)->   Tuple:





													'''simple docstring'''






													__UpperCamelCase       =			{}
													if "candidate_labels" in kwargs:
																			__UpperCamelCase       =			kwargs['''candidate_labels''']
													if "hypothesis_template" in kwargs:
																			__UpperCamelCase       =			kwargs['''hypothesis_template''']

													return preprocess_params, {}, {}



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=None     ,	SCREAMING_SNAKE_CASE_="This is a photo of {}."			)->   Optional[int]:





													'''simple docstring'''






													__UpperCamelCase       =			load_image(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			self.image_processor(images=[image]     ,	return_tensors=self.framework			)
													__UpperCamelCase       =			candidate_labels
													__UpperCamelCase       =			[hypothesis_template.format(SCREAMING_SNAKE_CASE_			) for x in candidate_labels]
													__UpperCamelCase       =			self.tokenizer(SCREAMING_SNAKE_CASE_     ,	return_tensors=self.framework     ,	padding=SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			[text_inputs]
													return inputs



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_			)->   Dict:





													'''simple docstring'''






													__UpperCamelCase       =			model_inputs.pop('''candidate_labels'''			)
													__UpperCamelCase       =			model_inputs.pop('''text_inputs'''			)
													if isinstance(text_inputs[0]     ,	SCREAMING_SNAKE_CASE_			):
																			__UpperCamelCase       =			text_inputs[0]
													else:
																			# Batching case.
																			__UpperCamelCase       =			text_inputs[0][0]

													__UpperCamelCase       =			self.model(**SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_			)

													__UpperCamelCase       =			{
													    '''candidate_labels''': candidate_labels,
													    '''logits''': outputs.logits_per_image,
													}
													return model_outputs



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_			)->   int:





													'''simple docstring'''






													__UpperCamelCase       =			model_outputs.pop('''candidate_labels'''			)
													__UpperCamelCase       =			model_outputs['''logits'''][0]
													if self.framework == "pt":
																			__UpperCamelCase       =			logits.softmax(dim=-1			).squeeze(-1			)
																			__UpperCamelCase       =			probs.tolist()
																			if not isinstance(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			):
																									__UpperCamelCase       =			[scores]
													elif self.framework == "tf":
																			__UpperCamelCase       =			stable_softmax(SCREAMING_SNAKE_CASE_     ,	axis=-1			)
																			__UpperCamelCase       =			probs.numpy().tolist()
													else:
																			raise ValueError(F"Unsupported framework: {self.framework}"			)

													__UpperCamelCase       =			[
													    {'''score''': score, '''label''': candidate_label}
													    for score, candidate_label in sorted(zip(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)     ,	key=lambda SCREAMING_SNAKE_CASE_			: -x[0]			)
													]
													return result




