
"""simple docstring"""



import re
import string
from collections import Counter

import sacrebleu
import sacremoses
from packaging import version

import datasets


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

UpperCamelCase__          =	'\\nWIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU\nIt can be used to evaluate the quality of machine-generated texts.\n'


UpperCamelCase__          =	'\nCalculates sari score (between 0 and 100) given a list of source and predicted\nsentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.\nArgs:\n    sources: list of source sentences where each sentence should be a string.\n    predictions: list of predicted sentences where each sentence should be a string.\n    references: list of lists of reference sentences where each sentence should be a string.\nReturns:\n    sari: sari score\n    sacrebleu: sacrebleu score\n    exact: exact score\n\nExamples:\n    >>> sources=["About 95 species are currently accepted ."]\n    >>> predictions=["About 95 you now get in ."]\n    >>> references=[["About 95 species are currently known ."]]\n    >>> wiki_split = datasets.load_metric("wiki_split")\n    >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)\n    >>> print(results)\n    {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0}\n'
def 					lowerCamelCase   (     _snake_case ):

    def remove_articles(_snake_case ):
        UpperCAmelCase__	:      str     							=					re.compile(r'\b(a|an|the)\b'    ,re.UNICODE )
        return re.sub(_snake_case    ,' '    ,_snake_case )

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

    def remove_punc(_snake_case ):
        UpperCAmelCase__	:      Dict     							=					set(string.punctuation )
        return "".join(ch for ch in text if ch not in exclude )

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

    return white_space_fix(remove_articles(remove_punc(lower(_snake_case ) ) ) )
def 					lowerCamelCase   (     _snake_case    ,_snake_case ):
    return int(normalize_answer(_snake_case ) == normalize_answer(_snake_case ) )
def 					lowerCamelCase   (     _snake_case    ,_snake_case ):
    UpperCAmelCase__	:      Tuple     							=					[any(compute_exact(_snake_case    ,_snake_case ) for ref in refs ) for pred, refs in zip(_snake_case    ,_snake_case )]
    return (sum(_snake_case ) / len(_snake_case )) * 100
def 					lowerCamelCase   (     _snake_case    ,_snake_case    ,_snake_case    ,_snake_case ):
    UpperCAmelCase__	:      Optional[Any]     							=					[rgram for rgrams in rgramslist for rgram in rgrams]
    UpperCAmelCase__	:      Optional[Any]     							=					Counter(_snake_case )

    UpperCAmelCase__	:      Tuple     							=					Counter(_snake_case )
    UpperCAmelCase__	:      Union[str, Any]     							=					Counter()
    for sgram, scount in sgramcounter.items():
        UpperCAmelCase__	:      str     							=					scount * numref

    UpperCAmelCase__	:      Union[str, Any]     							=					Counter(_snake_case )
    UpperCAmelCase__	:      str     							=					Counter()
    for cgram, ccount in cgramcounter.items():
        UpperCAmelCase__	:      Optional[Any]     							=					ccount * numref

    # KEEP
    UpperCAmelCase__	:      int     							=					sgramcounter_rep & cgramcounter_rep
    UpperCAmelCase__	:      Any     							=					keepgramcounter_rep & rgramcounter
    UpperCAmelCase__	:      Union[str, Any]     							=					sgramcounter_rep & rgramcounter

    UpperCAmelCase__	:      Optional[int]     							=					0
    UpperCAmelCase__	:      Dict     							=					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.
    UpperCAmelCase__	:      Optional[Any]     							=					1
    UpperCAmelCase__	:      Union[str, Any]     							=					1
    if len(_snake_case ) > 0:
        UpperCAmelCase__	:      int     							=					keeptmpscorea / len(_snake_case )
    if len(_snake_case ) > 0:
        # Fix an alleged bug [2] in the keep score computation.
        # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
        UpperCAmelCase__	:      Optional[int]     							=					keeptmpscorea / sum(keepgramcounterall_rep.values() )
    UpperCAmelCase__	:      str     							=					0
    if keepscore_precision > 0 or keepscore_recall > 0:
        UpperCAmelCase__	:      Tuple     							=					2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)

    # DELETION
    UpperCAmelCase__	:      Any     							=					sgramcounter_rep - cgramcounter_rep
    UpperCAmelCase__	:      List[str]     							=					delgramcounter_rep - rgramcounter
    UpperCAmelCase__	:      List[str]     							=					sgramcounter_rep - rgramcounter
    UpperCAmelCase__	:      Union[str, Any]     							=					0
    UpperCAmelCase__	:      Optional[Any]     							=					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.
    UpperCAmelCase__	:      Dict     							=					1
    if len(_snake_case ) > 0:
        UpperCAmelCase__	:      Optional[Any]     							=					deltmpscorea / len(_snake_case )

    # ADDITION
    UpperCAmelCase__	:      List[str]     							=					set(_snake_case ) - set(_snake_case )
    UpperCAmelCase__	:      List[Any]     							=					set(_snake_case ) & set(_snake_case )
    UpperCAmelCase__	:      List[str]     							=					set(_snake_case ) - set(_snake_case )

    UpperCAmelCase__	:      Optional[int]     							=					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.
    UpperCAmelCase__	:      Optional[Any]     							=					1
    UpperCAmelCase__	:      Optional[Any]     							=					1
    if len(_snake_case ) > 0:
        UpperCAmelCase__	:      Optional[Any]     							=					addtmpscore / len(_snake_case )
    if len(_snake_case ) > 0:
        UpperCAmelCase__	:      Dict     							=					addtmpscore / len(_snake_case )
    UpperCAmelCase__	:      Tuple     							=					0
    if addscore_precision > 0 or addscore_recall > 0:
        UpperCAmelCase__	:      Any     							=					2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)

    return (keepscore, delscore_precision, addscore)
def 					lowerCamelCase   (     _snake_case    ,_snake_case    ,_snake_case ):
    UpperCAmelCase__	:      Optional[Any]     							=					len(_snake_case )

    UpperCAmelCase__	:      List[str]     							=					ssent.split(' ' )
    UpperCAmelCase__	:      Optional[Any]     							=					csent.split(' ' )
    UpperCAmelCase__	:      List[Any]     							=					[]
    UpperCAmelCase__	:      int     							=					[]
    UpperCAmelCase__	:      List[str]     							=					[]
    UpperCAmelCase__	:      List[str]     							=					[]
    UpperCAmelCase__	:      Optional[Any]     							=					[]
    UpperCAmelCase__	:      int     							=					[]

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

    for i in range(0    ,len(_snake_case ) - 1 ):
        if i < len(_snake_case ) - 1:
            UpperCAmelCase__	:      Dict     							=					sagrams[i] + ' ' + sagrams[i + 1]
            sagrams.append(_snake_case )
        if i < len(_snake_case ) - 2:
            UpperCAmelCase__	:      Dict     							=					sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2]
            sagrams.append(_snake_case )
        if i < len(_snake_case ) - 3:
            UpperCAmelCase__	:      Dict     							=					sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] + ' ' + sagrams[i + 3]
            sagrams.append(_snake_case )

    for i in range(0    ,len(_snake_case ) - 1 ):
        if i < len(_snake_case ) - 1:
            UpperCAmelCase__	:      Any     							=					cagrams[i] + ' ' + cagrams[i + 1]
            cagrams.append(_snake_case )
        if i < len(_snake_case ) - 2:
            UpperCAmelCase__	:      int     							=					cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2]
            cagrams.append(_snake_case )
        if i < len(_snake_case ) - 3:
            UpperCAmelCase__	:      Dict     							=					cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] + ' ' + cagrams[i + 3]
            cagrams.append(_snake_case )

    ((UpperCAmelCase__)							,							(UpperCAmelCase__)							,							(UpperCAmelCase__))	:      Optional[int]     							=					SARIngram(_snake_case    ,_snake_case    ,_snake_case    ,_snake_case )
    ((UpperCAmelCase__)							,							(UpperCAmelCase__)							,							(UpperCAmelCase__))	:      Tuple     							=					SARIngram(_snake_case    ,_snake_case    ,_snake_case    ,_snake_case )
    ((UpperCAmelCase__)							,							(UpperCAmelCase__)							,							(UpperCAmelCase__))	:      int     							=					SARIngram(_snake_case    ,_snake_case    ,_snake_case    ,_snake_case )
    ((UpperCAmelCase__)							,							(UpperCAmelCase__)							,							(UpperCAmelCase__))	:      Optional[Any]     							=					SARIngram(_snake_case    ,_snake_case    ,_snake_case    ,_snake_case )
    UpperCAmelCase__	:      int     							=					sum([keepascore, keepascore, keepascore, keepascore] ) / 4
    UpperCAmelCase__	:      Any     							=					sum([delascore, delascore, delascore, delascore] ) / 4
    UpperCAmelCase__	:      int     							=					sum([addascore, addascore, addascore, addascore] ) / 4
    UpperCAmelCase__	:      Dict     							=					(avgkeepscore + avgdelscore + avgaddscore) / 3
    return finalscore
def 					lowerCamelCase   (     _snake_case    ,_snake_case = True    ,_snake_case = "13a"    ,_snake_case = True ):
    # 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:
        UpperCAmelCase__	:      Dict     							=					sentence.lower()

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

    if not return_str:
        UpperCAmelCase__	:      Tuple     							=					normalized_sent.split()

    return normalized_sent
def 					lowerCamelCase   (     _snake_case    ,_snake_case    ,_snake_case ):
    if not (len(_snake_case ) == len(_snake_case ) == len(_snake_case )):
        raise ValueError('Sources length must match predictions and references lengths.' )
    UpperCAmelCase__	:      Optional[int]     							=					0
    for src, pred, refs in zip(_snake_case    ,_snake_case    ,_snake_case ):
        sari_score += SARIsent(normalize(_snake_case )    ,normalize(_snake_case )    ,[normalize(_snake_case ) for sent in refs] )
    UpperCAmelCase__	:      Optional[int]     							=					sari_score / len(_snake_case )
    return 100 * sari_score
def 					lowerCamelCase   (     _snake_case    ,_snake_case    ,_snake_case="exp"    ,_snake_case=None    ,_snake_case=False    ,_snake_case=False    ,_snake_case=False    ,):
    UpperCAmelCase__	:      List[str]     							=					len(references[0] )
    if any(len(_snake_case ) != references_per_prediction for refs in references ):
        raise ValueError('Sacrebleu requires the same number of references for each prediction' )
    UpperCAmelCase__	:      Dict     							=					[[refs[i] for refs in references] for i in range(_snake_case )]
    UpperCAmelCase__	:      Any     							=					sacrebleu.corpus_bleu(
        _snake_case    ,_snake_case    ,smooth_method=_snake_case    ,smooth_value=_snake_case    ,force=_snake_case    ,lowercase=_snake_case    ,use_effective_order=_snake_case    ,)
    return output.score





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,		_KWARGS_DESCRIPTION      )
class 				a			(					datasets.Metric      ):



      def  __snake_case							(   self      ):
          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  __snake_case							(   self     ,	UpperCamelCase_     ,	UpperCamelCase_     ,	UpperCamelCase_      ):
          UpperCAmelCase__	:      int     							=					{}
          result.update({'sari': compute_sari(sources=UpperCamelCase_     ,	predictions=UpperCamelCase_     ,	references=UpperCamelCase_      )}      )
          result.update({'sacrebleu': compute_sacrebleu(predictions=UpperCamelCase_     ,	references=UpperCamelCase_      )}      )
          result.update({'exact': compute_em(predictions=UpperCamelCase_     ,	references=UpperCamelCase_      )}      )
          return result



"""simple docstring"""



from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


UpperCamelCase__          =	{
    'configuration_mega': ['MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegaConfig', 'MegaOnnxConfig'],
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    UpperCamelCase__          =	[
        'MEGA_PRETRAINED_MODEL_ARCHIVE_LIST',
        'MegaForCausalLM',
        'MegaForMaskedLM',
        'MegaForMultipleChoice',
        'MegaForQuestionAnswering',
        'MegaForSequenceClassification',
        'MegaForTokenClassification',
        'MegaModel',
        'MegaPreTrainedModel',
    ]

if TYPE_CHECKING:
    from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_mega import (
            MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
            MegaForCausalLM,
            MegaForMaskedLM,
            MegaForMultipleChoice,
            MegaForQuestionAnswering,
            MegaForSequenceClassification,
            MegaForTokenClassification,
            MegaModel,
            MegaPreTrainedModel,
        )

else:
    import sys

    UpperCamelCase__          =	_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)

