




"""simple docstring"""






import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
				import jax.numpy as jnp




class   a__			(       UpperCamelCase_  ):





						def __get__(							self      :	List[str]     ,a__      :	Tuple     ,a__      :	Tuple=None)						->       Optional[Any]:




											"""simple docstring"""







											if obj is None:
																return self
											if self.fget is None:
																raise AttributeError('''unreadable attribute''')
											_lowerCAmelCase:Dict									=  '''__cached_''' + self.fget.__name__
											_lowerCAmelCase:int									=  getattr(a__     ,a__     ,a__)
											if cached is None:
																_lowerCAmelCase:List[str]									=  self.fget(a__)
																setattr(a__     ,a__     ,a__)
											return cached





def 							UpperCAmelCase		(		snake_case			:					Union[str, Any]    ):
					_lowerCAmelCase:str									=  val.lower()
					if val in {"y", "yes", "t", "true", "on", "1"}:
										return 1
					if val in {"n", "no", "f", "false", "off", "0"}:
										return 0
					raise ValueError(F'invalid truth value {val!r}'    )





def 							UpperCAmelCase		(		snake_case			:					Optional[Any]    ):
					if is_torch_fx_proxy(snake_case    ):
										return True
					if is_torch_available():
										import torch

										if isinstance(snake_case      ,       torch.Tensor    ):
															return True
					if is_tf_available():
										import tensorflow as tf

										if isinstance(snake_case      ,       tf.Tensor    ):
															return True

					if is_flax_available():
										import jax.numpy as jnp
										from jax.core import Tracer

										if isinstance(snake_case      ,       (jnp.ndarray, Tracer)    ):
															return True

					return isinstance(snake_case      ,       np.ndarray    )





def 							UpperCAmelCase		(		snake_case			:					int    ):
					return isinstance(snake_case      ,       np.ndarray    )





def 							UpperCAmelCase		(		snake_case			:					Optional[int]    ):
					return _is_numpy(snake_case    )





def 							UpperCAmelCase		(		snake_case			:					Optional[int]    ):
					import torch

					return isinstance(snake_case      ,       torch.Tensor    )





def 							UpperCAmelCase		(		snake_case			:					Optional[Any]    ):
					return False if not is_torch_available() else _is_torch(snake_case    )





def 							UpperCAmelCase		(		snake_case			:					List[Any]    ):
					import torch

					return isinstance(snake_case      ,       torch.device    )





def 							UpperCAmelCase		(		snake_case			:					List[Any]    ):
					return False if not is_torch_available() else _is_torch_device(snake_case    )





def 							UpperCAmelCase		(		snake_case			:					Union[str, Any]    ):
					import torch

					if isinstance(snake_case      ,       snake_case    ):
										if hasattr(snake_case      ,       snake_case    ):
															_lowerCAmelCase:Optional[int]									=  getattr(snake_case      ,       snake_case    )
										else:
															return False
					return isinstance(snake_case      ,       torch.dtype    )





def 							UpperCAmelCase		(		snake_case			:					Union[str, Any]    ):
					return False if not is_torch_available() else _is_torch_dtype(snake_case    )





def 							UpperCAmelCase		(		snake_case			:					Any    ):
					import tensorflow as tf

					return isinstance(snake_case      ,       tf.Tensor    )





def 							UpperCAmelCase		(		snake_case			:					Tuple    ):
					return False if not is_tf_available() else _is_tensorflow(snake_case    )





def 							UpperCAmelCase		(		snake_case			:					Any    ):
					import tensorflow as tf

					# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
					if hasattr(snake_case      ,       '''is_symbolic_tensor'''    ):
										return tf.is_symbolic_tensor(snake_case    )
					return type(snake_case    ) == tf.Tensor





def 							UpperCAmelCase		(		snake_case			:					str    ):
					return False if not is_tf_available() else _is_tf_symbolic_tensor(snake_case    )





def 							UpperCAmelCase		(		snake_case			:					Tuple    ):
					import jax.numpy as jnp  # noqa: F811

					return isinstance(snake_case      ,       jnp.ndarray    )





def 							UpperCAmelCase		(		snake_case			:					Optional[Any]    ):
					return False if not is_flax_available() else _is_jax(snake_case    )





def 							UpperCAmelCase		(		snake_case			:					int    ):
					if isinstance(snake_case      ,       (dict, UserDict)    ):
										return {k: to_py_obj(snake_case    ) for k, v in obj.items()}
					elif isinstance(snake_case      ,       (list, tuple)    ):
										return [to_py_obj(snake_case    ) for o in obj]
					elif is_tf_tensor(snake_case    ):
										return obj.numpy().tolist()
					elif is_torch_tensor(snake_case    ):
										return obj.detach().cpu().tolist()
					elif is_jax_tensor(snake_case    ):
										return np.asarray(snake_case    ).tolist()
					elif isinstance(snake_case      ,       (np.ndarray, np.number)    ):  # tolist also works on 0d np arrays
										return obj.tolist()
					else:
										return obj





def 							UpperCAmelCase		(		snake_case			:					Union[str, Any]    ):
					if isinstance(snake_case      ,       (dict, UserDict)    ):
										return {k: to_numpy(snake_case    ) for k, v in obj.items()}
					elif isinstance(snake_case      ,       (list, tuple)    ):
										return np.array(snake_case    )
					elif is_tf_tensor(snake_case    ):
										return obj.numpy()
					elif is_torch_tensor(snake_case    ):
										return obj.detach().cpu().numpy()
					elif is_jax_tensor(snake_case    ):
										return np.asarray(snake_case    )
					else:
										return obj




class   a__			(       UpperCamelCase_  ):





						def       __UpperCamelCase     (							self      :	Any)						->       Optional[Any]:




											"""simple docstring"""







											_lowerCAmelCase:List[Any]									=  fields(self)

											# Safety and consistency checks
											if not len(a__):
																raise ValueError(F'{self.__class__.__name__} has no fields.')
											if not all(field.default is None for field in class_fields[1:]):
																raise ValueError(F'{self.__class__.__name__} should not have more than one required field.')

											_lowerCAmelCase:Dict									=  getattr(self     ,class_fields[0].name)
											_lowerCAmelCase:Dict									=  all(getattr(self     ,field.name) is None for field in class_fields[1:])

											if other_fields_are_none and not is_tensor(a__):
																if isinstance(a__     ,a__):
																					_lowerCAmelCase:str									=  first_field.items()
																					_lowerCAmelCase:List[str]									=  True
																else:
																					try:
																										_lowerCAmelCase:List[Any]									=  iter(a__)
																										_lowerCAmelCase:Dict									=  True
																					except TypeError:
																										_lowerCAmelCase:int									=  False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
																if first_field_iterator:
																					for idx, element in enumerate(a__):
																										if (
																										    not isinstance(a__     ,(list, tuple))
																										    or not len(a__) == 2
																										    or not isinstance(element[0]     ,a__)
																										):
																															if idx == 0:
																																				# If we do not have an iterator of key/values, set it as attribute
																																				_lowerCAmelCase:Tuple									=  first_field
																															else:
																																				# If we have a mixed iterator, raise an error
																																				raise ValueError(
																																				    F'Cannot set key/value for {element}. It needs to be a tuple (key, value).')
																															break
																										setattr(self     ,element[0]     ,element[1])
																										if element[1] is not None:
																															_lowerCAmelCase:Any									=  element[1]
																elif first_field is not None:
																					_lowerCAmelCase:List[str]									=  first_field
											else:
																for field in class_fields:
																					_lowerCAmelCase:Tuple									=  getattr(self     ,field.name)
																					if v is not None:
																										_lowerCAmelCase:Optional[int]									=  v





						def __delitem__(							self      :	int     ,*a__      :	Dict     ,**a__      :	int)						->       Dict:




											"""simple docstring"""







											raise Exception(F'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.')





						def       __UpperCamelCase     (							self      :	Any     ,*a__      :	List[str]     ,**a__      :	Tuple)						->       Union[str, Any]:




											"""simple docstring"""







											raise Exception(F'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.')





						def       __UpperCamelCase     (							self      :	Dict     ,*a__      :	Dict     ,**a__      :	Tuple)						->       Any:




											"""simple docstring"""







											raise Exception(F'You cannot use ``pop`` on a {self.__class__.__name__} instance.')





						def       __UpperCamelCase     (							self      :	Union[str, Any]     ,*a__      :	List[str]     ,**a__      :	Optional[int])						->       Dict:




											"""simple docstring"""







											raise Exception(F'You cannot use ``update`` on a {self.__class__.__name__} instance.')





						def __getitem__(							self      :	Any     ,a__      :	Tuple)						->       List[Any]:




											"""simple docstring"""







											if isinstance(a__     ,a__):
																_lowerCAmelCase:int									=  dict(self.items())
																return inner_dict[k]
											else:
																return self.to_tuple()[k]





						def __setattr__(							self      :	str     ,a__      :	Optional[Any]     ,a__      :	str)						->       List[Any]:




											"""simple docstring"""







											if name in self.keys() and value is not None:
																# Don't call self.__setitem__ to avoid recursion errors
																super().__setitem__(a__     ,a__)
											super().__setattr__(a__     ,a__)





						def __setitem__(							self      :	Tuple     ,a__      :	Optional[Any]     ,a__      :	Union[str, Any])						->       Tuple:




											"""simple docstring"""







											super().__setitem__(a__     ,a__)
											# Don't call self.__setattr__ to avoid recursion errors
											super().__setattr__(a__     ,a__)







						def       __UpperCamelCase     (							self      :	Optional[int])						->       Tuple[Any]:




											"""simple docstring"""







											return tuple(self[k] for k in self.keys())




class   a__			(       UpperCamelCase_					,	UpperCamelCase_  ):





						@classmethod
						def       __UpperCamelCase     (							cls      :	List[str]     ,a__      :	Any)						->       List[Any]:




											"""simple docstring"""







											raise ValueError(
											    F'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys())}')




class   a__			(       UpperCamelCase_  ):
						snake_case__             = '''longest'''
						snake_case__             = '''max_length'''
						snake_case__             = '''do_not_pad'''




class   a__			(       UpperCamelCase_  ):
						snake_case__             = '''pt'''
						snake_case__             = '''tf'''
						snake_case__             = '''np'''
						snake_case__             = '''jax'''




class   a__			:





						def __init__(							self      :	Optional[Any]     ,a__      :	List[ContextManager])						->       Dict:




											"""simple docstring"""







											_lowerCAmelCase:Any									=  context_managers
											_lowerCAmelCase:Dict									=  ExitStack()





						def __enter__(							self      :	Optional[Any])						->       Optional[int]:




											"""simple docstring"""







											for context_manager in self.context_managers:
																self.stack.enter_context(a__)







						def __exit__(							self      :	int     ,*a__      :	Union[str, Any]     ,**a__      :	Any)						->       str:




											"""simple docstring"""







											self.stack.__exit__(*a__     ,**a__)





def 							UpperCAmelCase		(		snake_case			:					str    ):
					_lowerCAmelCase:List[str]									=  infer_framework(snake_case    )
					if framework == "tf":
										_lowerCAmelCase:Optional[int]									=  inspect.signature(model_class.call    )  # TensorFlow models
					elif framework == "pt":
										_lowerCAmelCase:Optional[Any]									=  inspect.signature(model_class.forward    )  # PyTorch models
					else:
										_lowerCAmelCase:int									=  inspect.signature(model_class.__call__    )  # Flax models

					for p in signature.parameters:
										if p == "return_loss" and signature.parameters[p].default is True:
															return True

					return False





def 							UpperCAmelCase		(		snake_case			:					List[str]    ):
					_lowerCAmelCase:List[Any]									=  model_class.__name__
					_lowerCAmelCase:Optional[Any]									=  infer_framework(snake_case    )
					if framework == "tf":
										_lowerCAmelCase:Optional[int]									=  inspect.signature(model_class.call    )  # TensorFlow models
					elif framework == "pt":
										_lowerCAmelCase:Optional[Any]									=  inspect.signature(model_class.forward    )  # PyTorch models
					else:
										_lowerCAmelCase:Optional[int]									=  inspect.signature(model_class.__call__    )  # Flax models

					if "QuestionAnswering" in model_name:
										return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
					else:
										return [p for p in signature.parameters if "label" in p]





def 							UpperCAmelCase		(		snake_case			:					MutableMapping      ,       snake_case			:					str = ""      ,       snake_case			:					str = "."    ):

					def _flatten_dict(snake_case			:					Dict      ,       snake_case			:					Optional[Any]=""      ,       snake_case			:					List[Any]="."    ):
										for k, v in d.items():
															_lowerCAmelCase:Tuple									=  str(snake_case    ) + delimiter + str(snake_case    ) if parent_key else k
															if v and isinstance(snake_case      ,       snake_case    ):
																				yield from flatten_dict(snake_case      ,       snake_case      ,       delimiter=snake_case    ).items()
															else:
																				yield key, v

					return dict(_flatten_dict(snake_case      ,       snake_case      ,       snake_case    )    )





@contextmanager
def 							UpperCAmelCase		(		snake_case			:					Union[str, Any]      ,       snake_case			:					bool = False    ):
					if use_temp_dir:
										with tempfile.TemporaryDirectory() as tmp_dir:
															yield tmp_dir
					else:
										yield working_dir





def 							UpperCAmelCase		(		snake_case			:					List[str]      ,       snake_case			:					Optional[Any]=None    ):
					if is_numpy_array(snake_case    ):
										return np.transpose(snake_case      ,       axes=snake_case    )
					elif is_torch_tensor(snake_case    ):
										return array.T if axes is None else array.permute(*snake_case    )
					elif is_tf_tensor(snake_case    ):
										import tensorflow as tf

										return tf.transpose(snake_case      ,       perm=snake_case    )
					elif is_jax_tensor(snake_case    ):
										return jnp.transpose(snake_case      ,       axes=snake_case    )
					else:
										raise ValueError(F'Type not supported for transpose: {type(snake_case    )}.'    )





def 							UpperCAmelCase		(		snake_case			:					Optional[Any]      ,       snake_case			:					Tuple    ):
					if is_numpy_array(snake_case    ):
										return np.reshape(snake_case      ,       snake_case    )
					elif is_torch_tensor(snake_case    ):
										return array.reshape(*snake_case    )
					elif is_tf_tensor(snake_case    ):
										import tensorflow as tf

										return tf.reshape(snake_case      ,       snake_case    )
					elif is_jax_tensor(snake_case    ):
										return jnp.reshape(snake_case      ,       snake_case    )
					else:
										raise ValueError(F'Type not supported for reshape: {type(snake_case    )}.'    )





def 							UpperCAmelCase		(		snake_case			:					List[str]      ,       snake_case			:					Any=None    ):
					if is_numpy_array(snake_case    ):
										return np.squeeze(snake_case      ,       axis=snake_case    )
					elif is_torch_tensor(snake_case    ):
										return array.squeeze() if axis is None else array.squeeze(dim=snake_case    )
					elif is_tf_tensor(snake_case    ):
										import tensorflow as tf

										return tf.squeeze(snake_case      ,       axis=snake_case    )
					elif is_jax_tensor(snake_case    ):
										return jnp.squeeze(snake_case      ,       axis=snake_case    )
					else:
										raise ValueError(F'Type not supported for squeeze: {type(snake_case    )}.'    )





def 							UpperCAmelCase		(		snake_case			:					str      ,       snake_case			:					List[str]    ):
					if is_numpy_array(snake_case    ):
										return np.expand_dims(snake_case      ,       snake_case    )
					elif is_torch_tensor(snake_case    ):
										return array.unsqueeze(dim=snake_case    )
					elif is_tf_tensor(snake_case    ):
										import tensorflow as tf

										return tf.expand_dims(snake_case      ,       axis=snake_case    )
					elif is_jax_tensor(snake_case    ):
										return jnp.expand_dims(snake_case      ,       axis=snake_case    )
					else:
										raise ValueError(F'Type not supported for expand_dims: {type(snake_case    )}.'    )





def 							UpperCAmelCase		(		snake_case			:					List[str]    ):
					if is_numpy_array(snake_case    ):
										return np.size(snake_case    )
					elif is_torch_tensor(snake_case    ):
										return array.numel()
					elif is_tf_tensor(snake_case    ):
										import tensorflow as tf

										return tf.size(snake_case    )
					elif is_jax_tensor(snake_case    ):
										return array.size
					else:
										raise ValueError(F'Type not supported for expand_dims: {type(snake_case    )}.'    )





def 							UpperCAmelCase		(		snake_case			:					List[str]      ,       snake_case			:					List[Any]    ):
					for key, value in auto_map.items():
										if isinstance(snake_case      ,       (tuple, list)    ):
															_lowerCAmelCase:Union[str, Any]									=  [F'{repo_id}--{v}' if (v is not None and '''--''' not in v) else v for v in value]
										elif value is not None and "--" not in value:
															_lowerCAmelCase:int									=  F'{repo_id}--{value}'

					return auto_map





def 							UpperCAmelCase		(		snake_case			:					str    ):
					for base_class in inspect.getmro(snake_case    ):
										_lowerCAmelCase:str									=  base_class.__module__
										_lowerCAmelCase:Dict									=  base_class.__name__
										if module.startswith('''tensorflow'''    ) or module.startswith('''keras'''    ) or name == "TFPreTrainedModel":
															return "tf"
										elif module.startswith('''torch'''    ) or name == "PreTrainedModel":
															return "pt"
										elif module.startswith('''flax'''    ) or module.startswith('''jax'''    ) or name == "FlaxPreTrainedModel":
															return "flax"
					else:
										raise TypeError(F'Could not infer framework from class {model_class}.'    )












"""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		(		snake_case			:					Any    ):
					return 1.0 / (1.0 + np.exp(-_outputs    ))





def 							UpperCAmelCase		(		snake_case			:					Optional[Any]    ):
					_lowerCAmelCase:Optional[Any]									=  np.max(_outputs      ,       axis=-1      ,       keepdims=snake_case    )
					_lowerCAmelCase:List[Any]									=  np.exp(_outputs - maxes    )
					return shifted_exp / shifted_exp.sum(axis=-1      ,       keepdims=snake_case    )




class   a__			(       UpperCamelCase_  ):
						snake_case__             = '''sigmoid'''
						snake_case__             = '''softmax'''
						snake_case__             = '''none'''




@add_end_docstrings(
    UpperCamelCase_					,	r'''
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `"default"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `"sigmoid"`: Applies the sigmoid function on the output.
            - `"softmax"`: Applies the softmax function on the output.
            - `"none"`: Does not apply any function on the output.
    '''					,	)
class   a__			(       UpperCamelCase_  ):
						snake_case__             = False
						snake_case__             = ClassificationFunction.NONE





						def __init__(							self      :	str     ,**a__      :	List[str])						->       Optional[int]:




											"""simple docstring"""







											super().__init__(**a__)

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





						def       __UpperCamelCase     (							self      :	int     ,a__      :	Union[str, Any]=None     ,a__      :	Optional[Any]=None     ,a__      :	Dict=""     ,**a__      :	Dict)						->       str:




											"""simple docstring"""







											_lowerCAmelCase:List[Any]									=  tokenizer_kwargs

											_lowerCAmelCase:Union[str, Any]									=  {}
											if hasattr(self.model.config     ,'''return_all_scores''') and return_all_scores is None:
																_lowerCAmelCase:str									=  self.model.config.return_all_scores

											if isinstance(a__     ,a__) or top_k is None:
																_lowerCAmelCase:Union[str, Any]									=  top_k
																_lowerCAmelCase:Any									=  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`.'''     ,a__     ,)
																if return_all_scores:
																					_lowerCAmelCase:Tuple									=  None
																else:
																					_lowerCAmelCase:Union[str, Any]									=  1

											if isinstance(a__     ,a__):
																_lowerCAmelCase:Union[str, Any]									=  ClassificationFunction[function_to_apply.upper()]

											if function_to_apply is not None:
																_lowerCAmelCase:Union[str, Any]									=  function_to_apply
											return preprocess_params, {}, postprocess_params





						def __call__(							self      :	List[str]     ,*a__      :	Union[str, Any]     ,**a__      :	List[Any])						->       List[Any]:




											"""simple docstring"""







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





						def       __UpperCamelCase     (							self      :	Union[str, Any]     ,a__      :	Optional[Any]     ,**a__      :	Optional[int])						->       Dict[str, GenericTensor]:




											"""simple docstring"""







											_lowerCAmelCase:Dict									=  self.framework
											if isinstance(a__     ,a__):
																return self.tokenizer(**a__     ,return_tensors=a__     ,**a__)
											elif isinstance(a__     ,a__) and len(a__) == 1 and isinstance(inputs[0]     ,a__) 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=a__     ,**a__)
											elif isinstance(a__     ,a__):
																# 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(a__     ,return_tensors=a__     ,**a__)





						def       __UpperCamelCase     (							self      :	List[Any]     ,a__      :	List[str])						->       Optional[Any]:




											"""simple docstring"""







											return self.model(**a__)







						def       __UpperCamelCase     (							self      :	Optional[int]     ,a__      :	Optional[Any]     ,a__      :	Any=None     ,a__      :	Optional[Any]=1     ,a__      :	Any=True)						->       Union[str, Any]:




											"""simple docstring"""







											if function_to_apply is None:
																if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
																					_lowerCAmelCase:Union[str, Any]									=  ClassificationFunction.SIGMOID
																elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
																					_lowerCAmelCase:Any									=  ClassificationFunction.SOFTMAX
																elif hasattr(self.model.config     ,'''function_to_apply''') and function_to_apply is None:
																					_lowerCAmelCase:List[Any]									=  self.model.config.function_to_apply
																else:
																					_lowerCAmelCase:List[Any]									=  ClassificationFunction.NONE

											_lowerCAmelCase:List[Any]									=  model_outputs['''logits'''][0]
											_lowerCAmelCase:Optional[Any]									=  outputs.numpy()

											if function_to_apply == ClassificationFunction.SIGMOID:
																_lowerCAmelCase:Dict									=  sigmoid(a__)
											elif function_to_apply == ClassificationFunction.SOFTMAX:
																_lowerCAmelCase:Dict									=  softmax(a__)
											elif function_to_apply == ClassificationFunction.NONE:
																_lowerCAmelCase:Union[str, Any]									=  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()}

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






