




"""simple docstring"""






import re
import string
from collections import Counter

import sacrebleu
import sacremoses
from packaging import version

import datasets


lowercase__     						=						"""
@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\",
}
"""

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


lowercase__     						=						"""
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      _snake_case			(				lowercase__		):

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

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

				def remove_punc(lowercase__		):
								_lowerCamelCase     :			Tuple    =    set(string.punctuation		)
								return "".join(ch for ch in text if ch not in exclude		)

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

				return white_space_fix(remove_articles(remove_punc(lower(lowercase__		)		)		)		)







def      _snake_case			(				lowercase__							,    lowercase__		):
				return int(normalize_answer(lowercase__		) == normalize_answer(lowercase__		)		)







def      _snake_case			(				lowercase__							,    lowercase__		):
				_lowerCamelCase     :			Optional[int]    =    [any(compute_exact(lowercase__							,    lowercase__		) for ref in refs		) for pred, refs in zip(lowercase__							,    lowercase__		)]
				return (sum(lowercase__		) / len(lowercase__		)) * 100







def      _snake_case			(				lowercase__							,    lowercase__							,    lowercase__							,    lowercase__		):
				_lowerCamelCase     :			Optional[int]    =    [rgram for rgrams in rgramslist for rgram in rgrams]
				_lowerCamelCase     :			str    =    Counter(lowercase__		)

				_lowerCamelCase     :			Tuple    =    Counter(lowercase__		)
				_lowerCamelCase     :			Any    =    Counter()
				for sgram, scount in sgramcounter.items():
								_lowerCamelCase     :			Optional[Any]    =    scount * numref

				_lowerCamelCase     :			Tuple    =    Counter(lowercase__		)
				_lowerCamelCase     :			List[Any]    =    Counter()
				for cgram, ccount in cgramcounter.items():
								_lowerCamelCase     :			Tuple    =    ccount * numref

				# KEEP
				_lowerCamelCase     :			List[Any]    =    sgramcounter_rep & cgramcounter_rep
				_lowerCamelCase     :			int    =    keepgramcounter_rep & rgramcounter
				_lowerCamelCase     :			str    =    sgramcounter_rep & rgramcounter

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

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

				# ADDITION
				_lowerCamelCase     :			Union[str, Any]    =    set(lowercase__		) - set(lowercase__		)
				_lowerCamelCase     :			Tuple    =    set(lowercase__		) & set(lowercase__		)
				_lowerCamelCase     :			str    =    set(lowercase__		) - set(lowercase__		)

				_lowerCamelCase     :			Union[str, Any]    =    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     :			Union[str, Any]    =    1
				if len(lowercase__		) > 0:
								_lowerCamelCase     :			Any    =    addtmpscore / len(lowercase__		)
				if len(lowercase__		) > 0:
								_lowerCamelCase     :			Any    =    addtmpscore / len(lowercase__		)
				_lowerCamelCase     :			Union[str, Any]    =    0
				if addscore_precision > 0 or addscore_recall > 0:
								_lowerCamelCase     :			Union[str, Any]    =    2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)

				return (keepscore, delscore_precision, addscore)







def      _snake_case			(				lowercase__							,    lowercase__							,    lowercase__		):
				_lowerCamelCase     :			Tuple    =    len(lowercase__		)

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

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

				for i in range(0							,    len(lowercase__		) - 1		):
								if i < len(lowercase__		) - 1:
												_lowerCamelCase     :			List[str]    =    sagrams[i] + ' ' + sagrams[i + 1]
												sagrams.append(lowercase__		)
								if i < len(lowercase__		) - 2:
												_lowerCamelCase     :			List[Any]    =    sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2]
												sagrams.append(lowercase__		)
								if i < len(lowercase__		) - 3:
												_lowerCamelCase     :			List[Any]    =    sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] + ' ' + sagrams[i + 3]
												sagrams.append(lowercase__		)

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

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







def      _snake_case			(				lowercase__							,    lowercase__ = True							,    lowercase__ = "13a"							,    lowercase__ = 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:
								_lowerCamelCase     :			Union[str, Any]    =    sentence.lower()

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

				if not return_str:
								_lowerCamelCase     :			List[Any]    =    normalized_sent.split()

				return normalized_sent







def      _snake_case			(				lowercase__							,    lowercase__							,    lowercase__		):
				if not (len(lowercase__		) == len(lowercase__		) == len(lowercase__		)):
								raise ValueError('Sources length must match predictions and references lengths.'		)
				_lowerCamelCase     :			List[str]    =    0
				for src, pred, refs in zip(lowercase__							,    lowercase__							,    lowercase__		):
								sari_score += SARIsent(normalize(lowercase__		)							,    normalize(lowercase__		)							,    [normalize(lowercase__		) for sent in refs]		)
				_lowerCamelCase     :			List[str]    =    sari_score / len(lowercase__		)
				return 100 * sari_score







def      _snake_case			(				lowercase__							,    lowercase__							,    lowercase__="exp"							,    lowercase__=None							,    lowercase__=False							,    lowercase__=False							,    lowercase__=False							,    ):
				_lowerCamelCase     :			Any    =    len(references[0]		)
				if any(len(lowercase__		) != references_per_prediction for refs in references		):
								raise ValueError('Sacrebleu requires the same number of references for each prediction'		)
				_lowerCamelCase     :			Optional[Any]    =    [[refs[i] for refs in references] for i in range(lowercase__		)]
				_lowerCamelCase     :			Optional[Any]    =    sacrebleu.corpus_bleu(
				    lowercase__							,    lowercase__							,    smooth_method=lowercase__							,    smooth_value=lowercase__							,    force=lowercase__							,    lowercase=lowercase__							,    use_effective_order=lowercase__							,    )
				return output.score






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






			'''simple docstring'''



			def 					A_    (  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 					A_    (  self  ,      lowercase  ,      lowercase  ,      lowercase  ):
							_lowerCamelCase     :			Optional[int]    =    {}
							result.update({'sari': compute_sari(sources=lowercase  ,      predictions=lowercase  ,      references=lowercase  )}  )
							result.update({'sacrebleu': compute_sacrebleu(predictions=lowercase  ,      references=lowercase  )}  )
							result.update({'exact': compute_em(predictions=lowercase  ,      references=lowercase  )}  )
							return result






from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_torch_available():
    import torch

if is_torch_tpu_available(check_device=False):
    import torch_xla.core.xla_model as xm


lowercase      :       List[str]									=  logging.get_logger(__name__)





@dataclass
class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   __A   :				Optional[Any]         =  [
       '''no_inference''',
       '''no_cuda''',
       '''no_tpu''',
       '''no_speed''',
       '''no_memory''',
       '''no_env_print''',
       '''no_multi_process''',
   ]

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







          '''simple docstring'''

          for deprecated_arg in self.deprecated_args:
                 if deprecated_arg in kwargs:
                        a__						:	Union[str, Any] =				deprecated_arg[3:]
                        setattr(self					,  lowercase					,  not kwargs.pop(lowercase))
                        logger.warning(
                            F'{deprecated_arg} is depreciated. Please use --no_{positive_arg} or'
                            F' {positive_arg}={kwargs[positive_arg]}')

          a__						:	Union[str, Any] =				kwargs.pop('torchscript'					,  self.torchscript)
          a__						:	Tuple =				kwargs.pop('torch_xla_tpu_print_metrics'					,  self.torch_xla_tpu_print_metrics)
          a__						:	Tuple =				kwargs.pop('fp16_opt_level'					,  self.fpaa_opt_level)
          super().__init__(**lowercase)

   __A   :				bool         =  field(default=__UpperCAmelCase ,  metadata={'''help''': '''Trace the models using torchscript'''}	)
   __A   :				bool         =  field(default=__UpperCAmelCase ,  metadata={'''help''': '''Print Xla/PyTorch tpu metrics'''}	)
   __A   :				str         =  field(
       default='''O1''' ,  metadata={
           '''help''': (
               '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\']. '''
               '''See details at https://nvidia.github.io/apex/amp.html'''
           )
       } ,  )

   @cached_property
   def 							__lowercase		(					self)			->						Tuple["torch.device", int]:







          '''simple docstring'''

          requires_backends(self					,  ['torch'])
          logger.info('PyTorch: setting up devices')
          if not self.cuda:
                 a__						:	List[str] =				torch.device('cpu')
                 a__						:	Optional[Any] =				0
          elif is_torch_tpu_available():
                 a__						:	List[str] =				xm.xla_device()
                 a__						:	Union[str, Any] =				0
          else:
                 a__						:	List[Any] =				torch.device('cuda' if torch.cuda.is_available() else 'cpu')
                 a__						:	Optional[int] =				torch.cuda.device_count()
          return device, n_gpu

   @property
   def 							__lowercase		(					self)			->						List[str]:







          '''simple docstring'''

          return is_torch_tpu_available() and self.tpu

   @property
   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          requires_backends(self					,  ['torch'])
          # TODO(PVP): currently only single GPU is supported
          return torch.cuda.current_device()

   @property
   def 							__lowercase		(					self)			->						"torch.device":







          '''simple docstring'''

          requires_backends(self					,  ['torch'])
          return self._setup_devices[0]

   @property
   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          requires_backends(self					,  ['torch'])
          return self._setup_devices[1]

   @property
   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          return self.n_gpu > 0


