

import re
import string
from collections import Counter

import sacrebleu
import sacremoses
from packaging import version

import datasets


a		="""
@inproceedings{xu-etal-2016-optimizing,
    title = {Optimizing Statistical Machine Translation for Text Simplification},
    authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},
    journal = {Transactions of the Association for Computational Linguistics},
    volume = {4},
    year={2016},
    url = {https://www.aclweb.org/anthology/Q16-1029},
    pages = {401--415
},
@inproceedings{post-2018-call,
    title = \"A Call for Clarity in Reporting {BLEU} Scores\",
    author = \"Post, Matt\",
    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",
    month = oct,
    year = \"2018\",
    address = \"Belgium, Brussels\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W18-6319\",
    pages = \"186--191\",
}
"""

a		="""\
WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU
It can be used to evaluate the quality of machine-generated texts.
"""


a		="""
Calculates sari score (between 0 and 100) given a list of source and predicted
sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.
Args:
    sources: list of source sentences where each sentence should be a string.
    predictions: list of predicted sentences where each sentence should be a string.
    references: list of lists of reference sentences where each sentence should be a string.
Returns:
    sari: sari score
    sacrebleu: sacrebleu score
    exact: exact score

Examples:
    >>> sources=[\"About 95 species are currently accepted .\"]
    >>> predictions=[\"About 95 you now get in .\"]
    >>> references=[[\"About 95 species are currently known .\"]]
    >>> wiki_split = datasets.load_metric(\"wiki_split\")
    >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)
    >>> print(results)
    {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0}
"""






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__			)  ->     List[str]:

	def remove_articles(lowerCamelCase__			):
		__lowerCamelCase				:				Dict					       = re.compile(R'\b(a|an|the)\b'	, re.UNICODE			)
		return re.sub(lowerCamelCase__	, ' '	, lowerCamelCase__			)

	def white_space_fix(lowerCamelCase__			):
		return " ".join(text.split()			)

	def remove_punc(lowerCamelCase__			):
		__lowerCamelCase				:				int					       = set(string.punctuation			)
		return "".join(ch for ch in text if ch not in exclude			)

	def lower(lowerCamelCase__			):
		return text.lower()

	return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase__			)			)			)			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__			)  ->     List[Any]:
	return int(normalize_answer(lowerCamelCase__			) == normalize_answer(lowerCamelCase__			)			)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__			)  ->     Dict:
	__lowerCamelCase				:				Union[str, Any]					       = [any(compute_exact(lowerCamelCase__	, lowerCamelCase__			) for ref in refs			) for pred, refs in zip(lowerCamelCase__	, lowerCamelCase__			)]
	return (sum(lowerCamelCase__			) / len(lowerCamelCase__			)) * 1_0_0






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__			)  ->     str:
	__lowerCamelCase				:				List[str]					       = [rgram for rgrams in rgramslist for rgram in rgrams]
	__lowerCamelCase				:				Any					       = Counter(lowerCamelCase__			)

	__lowerCamelCase				:				Optional[int]					       = Counter(lowerCamelCase__			)
	__lowerCamelCase				:				List[str]					       = Counter()
	for sgram, scount in sgramcounter.items():
		__lowerCamelCase				:				Any					       = scount * numref

	__lowerCamelCase				:				Union[str, Any]					       = Counter(lowerCamelCase__			)
	__lowerCamelCase				:				Optional[int]					       = Counter()
	for cgram, ccount in cgramcounter.items():
		__lowerCamelCase				:				List[str]					       = ccount * numref

	# KEEP
	__lowerCamelCase				:				Optional[Any]					       = sgramcounter_rep & cgramcounter_rep
	__lowerCamelCase				:				List[Any]					       = keepgramcounter_rep & rgramcounter
	__lowerCamelCase				:				int					       = sgramcounter_rep & rgramcounter

	__lowerCamelCase				:				int					       = 0
	__lowerCamelCase				:				Optional[int]					       = 0
	for keepgram in keepgramcountergood_rep:
		keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram]
		# Fix an alleged bug [2] in the keep score computation.
		# keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram]
		keeptmpscorea += keepgramcountergood_rep[keepgram]
	# Define 0/0=1 instead of 0 to give higher scores for predictions that match
	#      a target exactly.
	__lowerCamelCase				:				Optional[int]					       = 1
	__lowerCamelCase				:				Optional[Any]					       = 1
	if len(lowerCamelCase__			) > 0:
		__lowerCamelCase				:				Tuple					       = keeptmpscorea / len(lowerCamelCase__			)
	if len(lowerCamelCase__			) > 0:
		# Fix an alleged bug [2] in the keep score computation.
		# keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
		__lowerCamelCase				:				Tuple					       = keeptmpscorea / sum(keepgramcounterall_rep.values()			)
	__lowerCamelCase				:				Dict					       = 0
	if keepscore_precision > 0 or keepscore_recall > 0:
		__lowerCamelCase				:				List[str]					       = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)

	# DELETION
	__lowerCamelCase				:				str					       = sgramcounter_rep - cgramcounter_rep
	__lowerCamelCase				:				Tuple					       = delgramcounter_rep - rgramcounter
	__lowerCamelCase				:				Tuple					       = sgramcounter_rep - rgramcounter
	__lowerCamelCase				:				Union[str, Any]					       = 0
	__lowerCamelCase				:				int					       = 0
	for delgram in delgramcountergood_rep:
		deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram]
		deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram]
	# Define 0/0=1 instead of 0 to give higher scores for predictions that match
	# a target exactly.
	__lowerCamelCase				:				Any					       = 1
	if len(lowerCamelCase__			) > 0:
		__lowerCamelCase				:				List[Any]					       = deltmpscorea / len(lowerCamelCase__			)

	# ADDITION
	__lowerCamelCase				:				str					       = set(lowerCamelCase__			) - set(lowerCamelCase__			)
	__lowerCamelCase				:				Optional[int]					       = set(lowerCamelCase__			) & set(lowerCamelCase__			)
	__lowerCamelCase				:				str					       = set(lowerCamelCase__			) - set(lowerCamelCase__			)

	__lowerCamelCase				:				List[str]					       = 0
	for addgram in addgramcountergood:
		addtmpscore += 1

	# Define 0/0=1 instead of 0 to give higher scores for predictions that match
	# a target exactly.
	__lowerCamelCase				:				int					       = 1
	__lowerCamelCase				:				List[str]					       = 1
	if len(lowerCamelCase__			) > 0:
		__lowerCamelCase				:				Any					       = addtmpscore / len(lowerCamelCase__			)
	if len(lowerCamelCase__			) > 0:
		__lowerCamelCase				:				Optional[int]					       = addtmpscore / len(lowerCamelCase__			)
	__lowerCamelCase				:				Optional[Any]					       = 0
	if addscore_precision > 0 or addscore_recall > 0:
		__lowerCamelCase				:				List[Any]					       = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)

	return (keepscore, delscore_precision, addscore)






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__			)  ->     Dict:
	__lowerCamelCase				:				int					       = len(lowerCamelCase__			)

	__lowerCamelCase				:				int					       = ssent.split(' '			)
	__lowerCamelCase				:				Optional[Any]					       = csent.split(' '			)
	__lowerCamelCase				:				int					       = []
	__lowerCamelCase				:				Union[str, Any]					       = []
	__lowerCamelCase				:				Optional[Any]					       = []
	__lowerCamelCase				:				Tuple					       = []
	__lowerCamelCase				:				str					       = []
	__lowerCamelCase				:				Optional[int]					       = []

	__lowerCamelCase				:				List[Any]					       = []
	__lowerCamelCase				:				List[Any]					       = []
	__lowerCamelCase				:				Union[str, Any]					       = []
	__lowerCamelCase				:				Dict					       = []
	for rsent in rsents:
		__lowerCamelCase				:				str					       = rsent.split(' '			)
		__lowerCamelCase				:				List[Any]					       = []
		__lowerCamelCase				:				List[Any]					       = []
		__lowerCamelCase				:				Union[str, Any]					       = []
		ragramslist.append(lowerCamelCase__			)
		for i in range(0	, len(lowerCamelCase__			) - 1			):
			if i < len(lowerCamelCase__			) - 1:
				__lowerCamelCase				:				List[str]					       = ragrams[i] + ' ' + ragrams[i + 1]
				ragrams.append(lowerCamelCase__			)
			if i < len(lowerCamelCase__			) - 2:
				__lowerCamelCase				:				List[Any]					       = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2]
				ragrams.append(lowerCamelCase__			)
			if i < len(lowerCamelCase__			) - 3:
				__lowerCamelCase				:				List[str]					       = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] + ' ' + ragrams[i + 3]
				ragrams.append(lowerCamelCase__			)
		ragramslist.append(lowerCamelCase__			)
		ragramslist.append(lowerCamelCase__			)
		ragramslist.append(lowerCamelCase__			)

	for i in range(0	, len(lowerCamelCase__			) - 1			):
		if i < len(lowerCamelCase__			) - 1:
			__lowerCamelCase				:				Any					       = sagrams[i] + ' ' + sagrams[i + 1]
			sagrams.append(lowerCamelCase__			)
		if i < len(lowerCamelCase__			) - 2:
			__lowerCamelCase				:				Optional[int]					       = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2]
			sagrams.append(lowerCamelCase__			)
		if i < len(lowerCamelCase__			) - 3:
			__lowerCamelCase				:				Any					       = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] + ' ' + sagrams[i + 3]
			sagrams.append(lowerCamelCase__			)

	for i in range(0	, len(lowerCamelCase__			) - 1			):
		if i < len(lowerCamelCase__			) - 1:
			__lowerCamelCase				:				Any					       = cagrams[i] + ' ' + cagrams[i + 1]
			cagrams.append(lowerCamelCase__			)
		if i < len(lowerCamelCase__			) - 2:
			__lowerCamelCase				:				str					       = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2]
			cagrams.append(lowerCamelCase__			)
		if i < len(lowerCamelCase__			) - 3:
			__lowerCamelCase				:				Tuple					       = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] + ' ' + cagrams[i + 3]
			cagrams.append(lowerCamelCase__			)

	((__lowerCamelCase)       , (__lowerCamelCase)       , (__lowerCamelCase))				:				Dict					       = SARIngram(lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__			)
	((__lowerCamelCase)       , (__lowerCamelCase)       , (__lowerCamelCase))				:				Union[str, Any]					       = SARIngram(lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__			)
	((__lowerCamelCase)       , (__lowerCamelCase)       , (__lowerCamelCase))				:				Union[str, Any]					       = SARIngram(lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__			)
	((__lowerCamelCase)       , (__lowerCamelCase)       , (__lowerCamelCase))				:				str					       = SARIngram(lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__			)
	__lowerCamelCase				:				Union[str, Any]					       = sum([keepascore, keepascore, keepascore, keepascore]			) / 4
	__lowerCamelCase				:				Optional[int]					       = sum([delascore, delascore, delascore, delascore]			) / 4
	__lowerCamelCase				:				str					       = sum([addascore, addascore, addascore, addascore]			) / 4
	__lowerCamelCase				:				List[str]					       = (avgkeepscore + avgdelscore + avgaddscore) / 3
	return finalscore






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__ = True	, lowerCamelCase__ = "13a"	, lowerCamelCase__ = True			)  ->     Any:
	# Normalization is requried for the ASSET dataset (one of the primary
	# datasets in sentence simplification) to allow using space
	# to split the sentence. Even though Wiki-Auto and TURK datasets,
	# do not require normalization, we do it for consistency.
	# Code adapted from the EASSE library [1] written by the authors of the ASSET dataset.
	# [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7

	if lowercase:
		__lowerCamelCase				:				Optional[Any]					       = sentence.lower()

	if tokenizer in ["13a", "intl"]:
		if version.parse(sacrebleu.__version__			).major >= 2:
			__lowerCamelCase				:				int					       = sacrebleu.metrics.bleu._get_tokenizer(lowerCamelCase__			)()(lowerCamelCase__			)
		else:
			__lowerCamelCase				:				str					       = sacrebleu.TOKENIZERS[tokenizer]()(lowerCamelCase__			)
	elif tokenizer == "moses":
		__lowerCamelCase				:				Optional[Any]					       = sacremoses.MosesTokenizer().tokenize(lowerCamelCase__	, return_str=lowerCamelCase__	, escape=lowerCamelCase__			)
	elif tokenizer == "penn":
		__lowerCamelCase				:				Tuple					       = sacremoses.MosesTokenizer().penn_tokenize(lowerCamelCase__	, return_str=lowerCamelCase__			)
	else:
		__lowerCamelCase				:				List[Any]					       = sentence

	if not return_str:
		__lowerCamelCase				:				Optional[int]					       = normalized_sent.split()

	return normalized_sent






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__			)  ->     Union[str, Any]:
	if not (len(lowerCamelCase__			) == len(lowerCamelCase__			) == len(lowerCamelCase__			)):
		raise ValueError('Sources length must match predictions and references lengths.'			)
	__lowerCamelCase				:				List[str]					       = 0
	for src, pred, refs in zip(lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__			):
		sari_score += SARIsent(normalize(lowerCamelCase__			)	, normalize(lowerCamelCase__			)	, [normalize(lowerCamelCase__			) for sent in refs]			)
	__lowerCamelCase				:				int					       = sari_score / len(lowerCamelCase__			)
	return 1_0_0 * sari_score






def    SCREAMING_SNAKE_CASE__       (  lowerCamelCase__	, lowerCamelCase__	, lowerCamelCase__="exp"	, lowerCamelCase__=None	, lowerCamelCase__=False	, lowerCamelCase__=False	, lowerCamelCase__=False	, )  ->     int:
	__lowerCamelCase				:				Tuple					       = len(references[0]			)
	if any(len(lowerCamelCase__			) != references_per_prediction for refs in references			):
		raise ValueError('Sacrebleu requires the same number of references for each prediction'			)
	__lowerCamelCase				:				Optional[int]					       = [[refs[i] for refs in references] for i in range(lowerCamelCase__			)]
	__lowerCamelCase				:				Dict					       = sacrebleu.corpus_bleu(
	    lowerCamelCase__	, lowerCamelCase__	, smooth_method=lowerCamelCase__	, smooth_value=lowerCamelCase__	, force=lowerCamelCase__	, lowercase=lowerCamelCase__	, use_effective_order=lowerCamelCase__	, )
	return output.score






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,							_KWARGS_DESCRIPTION				)
class        A_		(       datasets.Metric				):
							def     lowerCAmelCase     (		self		:			str):
								return datasets.MetricInfo(
								    description=_DESCRIPTION   ,citation=_CITATION   ,inputs_description=_KWARGS_DESCRIPTION   ,features=datasets.Features(
								        {
								            'predictions': datasets.Value('string'   ,id='sequence'),
								            'references': datasets.Sequence(datasets.Value('string'   ,id='sequence')   ,id='references'),
								        })   ,codebase_urls=[
								        'https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py',
								        'https://github.com/cocoxu/simplification/blob/master/SARI.py',
								        'https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py',
								        'https://github.com/mjpost/sacreBLEU',
								    ]   ,reference_urls=[
								        'https://www.aclweb.org/anthology/Q16-1029.pdf',
								        'https://github.com/mjpost/sacreBLEU',
								        'https://en.wikipedia.org/wiki/BLEU',
								        'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213',
								    ]   ,)


							def     lowerCAmelCase     (		self		:			List[str]   ,SCREAMING_SNAKE_CASE__		:			Optional[int]   ,SCREAMING_SNAKE_CASE__		:			List[Any]   ,SCREAMING_SNAKE_CASE__		:			List[Any]):
								__lowerCamelCase				:				List[str]					       = {}
								result.update({'sari': compute_sari(sources=SCREAMING_SNAKE_CASE__   ,predictions=SCREAMING_SNAKE_CASE__   ,references=SCREAMING_SNAKE_CASE__)})
								result.update({'sacrebleu': compute_sacrebleu(predictions=SCREAMING_SNAKE_CASE__   ,references=SCREAMING_SNAKE_CASE__)})
								result.update({'exact': compute_em(predictions=SCREAMING_SNAKE_CASE__   ,references=SCREAMING_SNAKE_CASE__)})
								return result







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 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    Dict			):



     '''simple docstring'''





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

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    str			):



     '''simple docstring'''





     lowercase__    :   int      =       np.max(_outputs	,     axis=-1	,     keepdims=SCREAMING_SNAKE_CASE_			)
     lowercase__    :   int      =       np.exp(_outputs - maxes			)
     return shifted_exp / shifted_exp.sum(axis=-1	,     keepdims=SCREAMING_SNAKE_CASE_			)


class       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    __lowerCamelCase						:       Optional[int]														=     """sigmoid"""
    __lowerCamelCase						:       List[Any]														=     """softmax"""
    __lowerCamelCase						:       Optional[Any]														=     """none"""



@add_end_docstrings(
    __snake_case		,       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       SCREAMING_SNAKE_CASE__					(__snake_case     ):
    __lowerCamelCase						:       Dict														=     False
    __lowerCamelCase						:       List[str]														=     ClassificationFunction.NONE





    def __init__(      self						,   **a):
         super().__init__(**a)

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





    def       snake_case_				(      self						,   a=None						,   a=None						,   a=""						,   **a):
         # Using "" as default argument because we're going to use `top_k=None` in user code to declare
         # "No top_k"
         lowercase__    :   List[str]      =       tokenizer_kwargs

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

         if isinstance(a						,   a) or top_k is None:
              lowercase__    :   Tuple      =       top_k
              lowercase__    :   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:
                   lowercase__    :   Union[str, Any]      =       None
              else:
                   lowercase__    :   Union[str, Any]      =       1

         if isinstance(a						,   a):
              lowercase__    :   Tuple      =       ClassificationFunction[function_to_apply.upper()]

         if function_to_apply is not None:
              lowercase__    :   List[str]      =       function_to_apply
         return preprocess_params, {}, postprocess_params





    def __call__(      self						,   *a						,   **a):
         lowercase__    :   int      =       super().__call__(*a						,   **a)
         # TODO try and retrieve it in a nicer way from _sanitize_parameters.
         lowercase__    :   Any      =       '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       snake_case_				(      self						,   a						,   **a):
         lowercase__    :   List[str]      =       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       snake_case_				(      self						,   a):
         return self.model(**a)





    def       snake_case_				(      self						,   a						,   a=None						,   a=1						,   a=True):
         # `_legacy` is used to determine if we're running the naked pipeline and in backward
         # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
         # the more natural result containing the list.
         # Default value before `set_parameters`
         if function_to_apply is None:
              if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.SIGMOID
              elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.SOFTMAX
              elif hasattr(self.model.config						,   'function_to_apply') and function_to_apply is None:
                   lowercase__    :   List[str]      =       self.model.config.function_to_apply
              else:
                   lowercase__    :   Union[str, Any]      =       ClassificationFunction.NONE

         lowercase__    :   str      =       model_outputs['logits'][0]
         lowercase__    :   Dict      =       outputs.numpy()

         if function_to_apply == ClassificationFunction.SIGMOID:
              lowercase__    :   int      =       sigmoid(a)
         elif function_to_apply == ClassificationFunction.SOFTMAX:
              lowercase__    :   List[Any]      =       softmax(a)
         elif function_to_apply == ClassificationFunction.NONE:
              lowercase__    :   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()}

         lowercase__    :   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:
                   lowercase__    :   Optional[Any]      =       dict_scores[:top_k]
         return dict_scores

