"""simple docstring"""




import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
				from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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






def      UpperCAmelCase    (		UpperCamelCase__ ):






							"""simple docstring"""





							return 1.0 / (1.0 + np.exp(-_outputs ))






def      UpperCAmelCase    (		UpperCamelCase__ ):






							"""simple docstring"""





							A__		   =							np.max(_outputs				,			axis=-1				,			keepdims=SCREAMING_SNAKE_CASE__ )
							A__		   =							np.exp(_outputs - maxes )
							return shifted_exp / shifted_exp.sum(axis=-1				,			keepdims=SCREAMING_SNAKE_CASE__ )
class 			UpperCamelCase__(	UpperCamelCase_       ):
						lowerCAmelCase__     :  Optional[Any]  							=						'sigmoid'
						lowerCAmelCase__     :  Union[str, Any]  							=						'softmax'
						lowerCAmelCase__     :  Union[str, Any]  							=						'none'






@add_end_docstrings(
    UpperCamelCase_						,  r'\n        return_all_scores (`bool`, *optional*, defaults to `False`):\n            Whether to return all prediction scores or just the one of the predicted class.\n        function_to_apply (`str`, *optional*, defaults to `"default"`):\n            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n              has several labels, will apply the softmax function on the output.\n            - `"sigmoid"`: Applies the sigmoid function on the output.\n            - `"softmax"`: Applies the softmax function on the output.\n            - `"none"`: Does not apply any function on the output.\n    '						,  )
class 			UpperCamelCase__(	UpperCamelCase_       ):
						lowerCAmelCase__     :  str  							=						False
						lowerCAmelCase__     :  str  							=						ClassificationFunction.NONE





						def __init__(				self						,**__UpperCAmelCase   )    -> List[Any]:
													super().__init__(**lowercase_   )

													self.check_model_type(
													    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
													    if self.framework == 'tf'
													    else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING   )





						def  snake_case__		(				self						,__UpperCAmelCase=None						,__UpperCAmelCase=None						,__UpperCAmelCase=""						,**__UpperCAmelCase   )    -> List[Any]:
													A__		   =							tokenizer_kwargs

													A__		   =							{}
													if hasattr(self.model.config						,'return_all_scores'   ) and return_all_scores is None:
																				A__		   =							self.model.config.return_all_scores

													if isinstance(lowercase_						,lowercase_   ) or top_k is None:
																				A__		   =							top_k
																				A__		   =							False
													elif return_all_scores is not None:
																				warnings.warn(
																				    '`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'
																				    ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'						,lowercase_						,)
																				if return_all_scores:
																											A__		   =							None
																				else:
																											A__		   =							1

													if isinstance(lowercase_						,lowercase_   ):
																				A__		   =							ClassificationFunction[function_to_apply.upper()]

													if function_to_apply is not None:
																				A__		   =							function_to_apply
													return preprocess_params, {}, postprocess_params





						def __call__(				self						,*__UpperCAmelCase						,**__UpperCAmelCase   )    -> str:
													A__		   =							super().__call__(*lowercase_						,**lowercase_   )
													# TODO try and retrieve it in a nicer way from _sanitize_parameters.
													A__		   =							'top_k' not in kwargs
													if isinstance(args[0]						,lowercase_   ) and _legacy:
																				# This pipeline is odd, and return a list when single item is run
																				return [result]
													else:
																				return result





						def  snake_case__		(				self						,__UpperCAmelCase						,**__UpperCAmelCase   )    -> Dict[str, GenericTensor]:
													A__		   =							self.framework
													if isinstance(lowercase_						,lowercase_   ):
																				return self.tokenizer(**lowercase_						,return_tensors=lowercase_						,**lowercase_   )
													elif isinstance(lowercase_						,lowercase_   ) and len(lowercase_   ) == 1 and isinstance(inputs[0]						,lowercase_   ) and len(inputs[0]   ) == 2:
																				# It used to be valid to use a list of list of list for text pairs, keeping this path for BC
																				return self.tokenizer(
																				    text=inputs[0][0]						,text_pair=inputs[0][1]						,return_tensors=lowercase_						,**lowercase_   )
													elif isinstance(lowercase_						,lowercase_   ):
																				# This is likely an invalid usage of the pipeline attempting to pass text pairs.
																				raise ValueError(
																				    'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'
																				    ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'   )
													return self.tokenizer(lowercase_						,return_tensors=lowercase_						,**lowercase_   )





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Optional[Any]:
													return self.model(**lowercase_   )





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase=None						,__UpperCAmelCase=1						,__UpperCAmelCase=True   )    -> Optional[int]:




													if function_to_apply is None:
																				if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
																											A__		   =							ClassificationFunction.SIGMOID
																				elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
																											A__		   =							ClassificationFunction.SOFTMAX
																				elif hasattr(self.model.config						,'function_to_apply'   ) and function_to_apply is None:
																											A__		   =							self.model.config.function_to_apply
																				else:
																											A__		   =							ClassificationFunction.NONE

													A__		   =							model_outputs['logits'][0]
													A__		   =							outputs.numpy()

													if function_to_apply == ClassificationFunction.SIGMOID:
																				A__		   =							sigmoid(lowercase_   )
													elif function_to_apply == ClassificationFunction.SOFTMAX:
																				A__		   =							softmax(lowercase_   )
													elif function_to_apply == ClassificationFunction.NONE:
																				A__		   =							outputs
													else:
																				raise ValueError(f'''Unrecognized `function_to_apply` argument: {function_to_apply}'''   )

													if top_k == 1 and _legacy:
																				return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

													A__		   =							[
													    {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(lowercase_   )
													]
													if not _legacy:
																				dict_scores.sort(key=lambda __UpperCAmelCase   : x["score"]						,reverse=lowercase_   )
																				if top_k is not None:
																											A__		   =							dict_scores[:top_k]
													return dict_scores









import flax.linen as nn
import jax.numpy as jnp

from .attention_flax import FlaxTransformeraDModel
from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD




class A  (   nn.Module     ):
      UpperCamelCase__							:  int
      UpperCamelCase__							:  int
      UpperCamelCase__							:  float      =0.0
      UpperCamelCase__							:  int      =1
      UpperCamelCase__							:  int      =1
      UpperCamelCase__							:  bool      =True
      UpperCamelCase__							:  bool      =False
      UpperCamelCase__							:  bool      =False
      UpperCamelCase__							:  bool      =False
      UpperCamelCase__							:  jnp.dtype      =jnp.floataa






      def        lowerCamelCase       (					self						:     Any )					->						Any:
             """simple docstring"""




             _lowerCamelCase       :		str		=[]
             _lowerCamelCase       :		Dict		=[]

             for i in range(self.num_layers ):
                    _lowerCamelCase       :		Union[str, Any]		=self.in_channels if i == 0 else self.out_channels

                    _lowerCamelCase       :		Any		=FlaxResnetBlockaD(
                        in_channels=lowercase_			,   out_channels=self.out_channels			,   dropout_prob=self.dropout			,   dtype=self.dtype			,   )
                    resnets.append(lowercase_ )

                    _lowerCamelCase       :		Dict		=FlaxTransformeraDModel(
                        in_channels=self.out_channels			,   n_heads=self.num_attention_heads			,   d_head=self.out_channels // self.num_attention_heads			,   depth=1			,   use_linear_projection=self.use_linear_projection			,   only_cross_attention=self.only_cross_attention			,   use_memory_efficient_attention=self.use_memory_efficient_attention			,   dtype=self.dtype			,   )
                    attentions.append(lowercase_ )

             _lowerCamelCase       :		Optional[int]		=resnets
             _lowerCamelCase       :		Dict		=attentions

             if self.add_downsample:
                    _lowerCamelCase       :		Union[str, Any]		=FlaxDownsampleaD(self.out_channels			,   dtype=self.dtype )






      def __call__(					self						:     Any			,   lowercase_						:     Optional[Any]			,   lowercase_						:     List[Any]			,   lowercase_						:     Union[str, Any]			,   lowercase_						:     List[str]=True )					->						Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase       :		Tuple		=()

             for resnet, attn in zip(self.resnets			,   self.attentions ):
                    _lowerCamelCase       :		Union[str, Any]		=resnet(lowercase_			,   lowercase_			,   deterministic=lowercase_ )
                    _lowerCamelCase       :		Union[str, Any]		=attn(lowercase_			,   lowercase_			,   deterministic=lowercase_ )
                    output_states += (hidden_states,)

             if self.add_downsample:
                    _lowerCamelCase       :		Optional[int]		=self.downsamplers_a(lowercase_ )
                    output_states += (hidden_states,)

             return hidden_states, output_states




class A  (   nn.Module     ):
      UpperCamelCase__							:  int
      UpperCamelCase__							:  int
      UpperCamelCase__							:  float      =0.0
      UpperCamelCase__							:  int      =1
      UpperCamelCase__							:  bool      =True
      UpperCamelCase__							:  jnp.dtype      =jnp.floataa






      def        lowerCamelCase       (					self						:     Optional[int] )					->						int:
             """simple docstring"""




             _lowerCamelCase       :		str		=[]

             for i in range(self.num_layers ):
                    _lowerCamelCase       :		Tuple		=self.in_channels if i == 0 else self.out_channels

                    _lowerCamelCase       :		Any		=FlaxResnetBlockaD(
                        in_channels=lowercase_			,   out_channels=self.out_channels			,   dropout_prob=self.dropout			,   dtype=self.dtype			,   )
                    resnets.append(lowercase_ )
             _lowerCamelCase       :		Union[str, Any]		=resnets

             if self.add_downsample:
                    _lowerCamelCase       :		List[str]		=FlaxDownsampleaD(self.out_channels			,   dtype=self.dtype )






      def __call__(					self						:     Any			,   lowercase_						:     Dict			,   lowercase_						:     Union[str, Any]			,   lowercase_						:     Optional[Any]=True )					->						Dict:
             """simple docstring"""




             _lowerCamelCase       :		Optional[int]		=()

             for resnet in self.resnets:
                    _lowerCamelCase       :		Tuple		=resnet(lowercase_			,   lowercase_			,   deterministic=lowercase_ )
                    output_states += (hidden_states,)

             if self.add_downsample:
                    _lowerCamelCase       :		Tuple		=self.downsamplers_a(lowercase_ )
                    output_states += (hidden_states,)

             return hidden_states, output_states




class A  (   nn.Module     ):
      UpperCamelCase__							:  int
      UpperCamelCase__							:  int
      UpperCamelCase__							:  int
      UpperCamelCase__							:  float      =0.0
      UpperCamelCase__							:  int      =1
      UpperCamelCase__							:  int      =1
      UpperCamelCase__							:  bool      =True
      UpperCamelCase__							:  bool      =False
      UpperCamelCase__							:  bool      =False
      UpperCamelCase__							:  bool      =False
      UpperCamelCase__							:  jnp.dtype      =jnp.floataa






      def        lowerCamelCase       (					self						:     Dict )					->						Tuple:
             """simple docstring"""




             _lowerCamelCase       :		str		=[]
             _lowerCamelCase       :		List[str]		=[]

             for i in range(self.num_layers ):
                    _lowerCamelCase       :		List[str]		=self.in_channels if (i == self.num_layers - 1) else self.out_channels
                    _lowerCamelCase       :		Tuple		=self.prev_output_channel if i == 0 else self.out_channels

                    _lowerCamelCase       :		List[str]		=FlaxResnetBlockaD(
                        in_channels=resnet_in_channels + res_skip_channels			,   out_channels=self.out_channels			,   dropout_prob=self.dropout			,   dtype=self.dtype			,   )
                    resnets.append(lowercase_ )

                    _lowerCamelCase       :		Tuple		=FlaxTransformeraDModel(
                        in_channels=self.out_channels			,   n_heads=self.num_attention_heads			,   d_head=self.out_channels // self.num_attention_heads			,   depth=1			,   use_linear_projection=self.use_linear_projection			,   only_cross_attention=self.only_cross_attention			,   use_memory_efficient_attention=self.use_memory_efficient_attention			,   dtype=self.dtype			,   )
                    attentions.append(lowercase_ )

             _lowerCamelCase       :		int		=resnets
             _lowerCamelCase       :		Dict		=attentions

             if self.add_upsample:
                    _lowerCamelCase       :		str		=FlaxUpsampleaD(self.out_channels			,   dtype=self.dtype )






      def __call__(					self						:     Optional[Any]			,   lowercase_						:     Any			,   lowercase_						:     Any			,   lowercase_						:     List[Any]			,   lowercase_						:     Dict			,   lowercase_						:     Union[str, Any]=True )					->						Optional[int]:
             """simple docstring"""




             for resnet, attn in zip(self.resnets			,   self.attentions ):
                    # pop res hidden states
                    _lowerCamelCase       :		Optional[int]		=res_hidden_states_tuple[-1]
                    _lowerCamelCase       :		Union[str, Any]		=res_hidden_states_tuple[:-1]
                    _lowerCamelCase       :		Any		=jnp.concatenate((hidden_states, res_hidden_states)			,   axis=-1 )

                    _lowerCamelCase       :		Optional[Any]		=resnet(lowercase_			,   lowercase_			,   deterministic=lowercase_ )
                    _lowerCamelCase       :		List[Any]		=attn(lowercase_			,   lowercase_			,   deterministic=lowercase_ )

             if self.add_upsample:
                    _lowerCamelCase       :		Optional[Any]		=self.upsamplers_a(lowercase_ )

             return hidden_states




class A  (   nn.Module     ):
      UpperCamelCase__							:  int
      UpperCamelCase__							:  int
      UpperCamelCase__							:  int
      UpperCamelCase__							:  float      =0.0
      UpperCamelCase__							:  int      =1
      UpperCamelCase__							:  bool      =True
      UpperCamelCase__							:  jnp.dtype      =jnp.floataa






      def        lowerCamelCase       (					self						:     List[Any] )					->						Dict:
             """simple docstring"""




             _lowerCamelCase       :		List[str]		=[]

             for i in range(self.num_layers ):
                    _lowerCamelCase       :		Tuple		=self.in_channels if (i == self.num_layers - 1) else self.out_channels
                    _lowerCamelCase       :		int		=self.prev_output_channel if i == 0 else self.out_channels

                    _lowerCamelCase       :		str		=FlaxResnetBlockaD(
                        in_channels=resnet_in_channels + res_skip_channels			,   out_channels=self.out_channels			,   dropout_prob=self.dropout			,   dtype=self.dtype			,   )
                    resnets.append(lowercase_ )

             _lowerCamelCase       :		str		=resnets

             if self.add_upsample:
                    _lowerCamelCase       :		List[str]		=FlaxUpsampleaD(self.out_channels			,   dtype=self.dtype )






      def __call__(					self						:     List[str]			,   lowercase_						:     str			,   lowercase_						:     Dict			,   lowercase_						:     Union[str, Any]			,   lowercase_						:     Any=True )					->						int:
             """simple docstring"""




             for resnet in self.resnets:
                    # pop res hidden states
                    _lowerCamelCase       :		List[str]		=res_hidden_states_tuple[-1]
                    _lowerCamelCase       :		str		=res_hidden_states_tuple[:-1]
                    _lowerCamelCase       :		List[str]		=jnp.concatenate((hidden_states, res_hidden_states)			,   axis=-1 )

                    _lowerCamelCase       :		Optional[Any]		=resnet(lowercase_			,   lowercase_			,   deterministic=lowercase_ )

             if self.add_upsample:
                    _lowerCamelCase       :		Union[str, Any]		=self.upsamplers_a(lowercase_ )

             return hidden_states




class A  (   nn.Module     ):
      UpperCamelCase__							:  int
      UpperCamelCase__							:  float      =0.0
      UpperCamelCase__							:  int      =1
      UpperCamelCase__							:  int      =1
      UpperCamelCase__							:  bool      =False
      UpperCamelCase__							:  bool      =False
      UpperCamelCase__							:  jnp.dtype      =jnp.floataa






      def        lowerCamelCase       (					self						:     int )					->						Tuple:
             """simple docstring"""




             _lowerCamelCase       :		Optional[Any]		=[
                 FlaxResnetBlockaD(
                     in_channels=self.in_channels			,   out_channels=self.in_channels			,   dropout_prob=self.dropout			,   dtype=self.dtype			,   )
             ]

             _lowerCamelCase       :		Any		=[]

             for _ in range(self.num_layers ):
                    _lowerCamelCase       :		Optional[int]		=FlaxTransformeraDModel(
                        in_channels=self.in_channels			,   n_heads=self.num_attention_heads			,   d_head=self.in_channels // self.num_attention_heads			,   depth=1			,   use_linear_projection=self.use_linear_projection			,   use_memory_efficient_attention=self.use_memory_efficient_attention			,   dtype=self.dtype			,   )
                    attentions.append(lowercase_ )

                    _lowerCamelCase       :		Tuple		=FlaxResnetBlockaD(
                        in_channels=self.in_channels			,   out_channels=self.in_channels			,   dropout_prob=self.dropout			,   dtype=self.dtype			,   )
                    resnets.append(lowercase_ )

             _lowerCamelCase       :		List[Any]		=resnets
             _lowerCamelCase       :		List[str]		=attentions






      def __call__(					self						:     Optional[int]			,   lowercase_						:     List[Any]			,   lowercase_						:     Dict			,   lowercase_						:     Tuple			,   lowercase_						:     List[str]=True )					->						int:
             """simple docstring"""




             _lowerCamelCase       :		Dict		=self.resnets[0](lowercase_			,   lowercase_ )
             for attn, resnet in zip(self.attentions			,   self.resnets[1:] ):
                    _lowerCamelCase       :		Tuple		=attn(lowercase_			,   lowercase_			,   deterministic=lowercase_ )
                    _lowerCamelCase       :		List[str]		=resnet(lowercase_			,   lowercase_			,   deterministic=lowercase_ )

             return hidden_states


