import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


UpperCAmelCase_ 							=       """\
@inproceedings{snover-etal-2006-study,
    title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",
    author = \"Snover, Matthew  and
      Dorr, Bonnie  and
      Schwartz, Rich  and
      Micciulla, Linnea  and
      Makhoul, John\",
    booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",
    month = aug # \" 8-12\",
    year = \"2006\",
    address = \"Cambridge, Massachusetts, USA\",
    publisher = \"Association for Machine Translation in the Americas\",
    url = \"https://aclanthology.org/2006.amta-papers.25\",
    pages = \"223--231\",
}
@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\",
}
"""

UpperCAmelCase_ 							=       """\
TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a
hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu
(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found
here: https://github.com/jhclark/tercom.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.
"""

UpperCAmelCase_ 							=       """
Produces TER scores alongside the number of edits and reference length.

Args:
    predictions (list of str): The system stream (a sequence of segments).
    references (list of list of str): A list of one or more reference streams (each a sequence of segments).
    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,
                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.
                                    Only applies if `normalized = True`. Defaults to `False`.
    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.

Returns:
    'score' (float): TER score (num_edits / sum_ref_lengths * 100)
    'num_edits' (int): The cumulative number of edits
    'ref_length' (float): The cumulative average reference length

Examples:
    Example 1:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\",
        ...                     \"What did the TER metric user say to the developer?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],
        ...             [\"Your jokes are...\", \"...TERrible\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 150.0, 'num_edits': 15, 'ref_length': 10.0}

    Example 2:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 62.5, 'num_edits': 5, 'ref_length': 8.0}

    Example 3:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         normalized=True,
        ...                         case_sensitive=True)
        >>> print(results)
        {'score': 57.14285714285714, 'num_edits': 6, 'ref_length': 10.5}

    Example 4:
        >>> predictions = [\"does this sentence match??\",
        ...                     \"what about this sentence?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {'score': 0.0, 'num_edits': 0, 'ref_length': 8.0}

    Example 5:
        >>> predictions = [\"does this sentence match??\",
        ...                    \"what about this sentence?\",
        ...                    \"What did the TER metric user say to the developer?\"]
        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],
        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],
        ...             [\"Your jokes are...\", \"...TERrible\"]]
        >>> ter = datasets.load_metric(\"ter\")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {'score': 100.0, 'num_edits': 10, 'ref_length': 10.0}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,					_KWARGS_DESCRIPTION   )
class      UpperCamelCase_						(					datasets.Metric   ):




					def 		lowerCAmelCase     (						self					)						->							str:
										if version.parse(scb.__version__					) < version.parse('1.4.12'					):
															raise ImportWarning(
															    'To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n'
															    'You can install it with `pip install "sacrebleu>=1.4.12"`.'					)
										return datasets.MetricInfo(
										    description=_DESCRIPTION			,  citation=_CITATION			,  homepage='http://www.cs.umd.edu/~snover/tercom/'			,  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/mjpost/sacreBLEU#ter']			,  reference_urls=[
										        'https://github.com/jhclark/tercom',
										    ]			,  )






					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_			,  lowerCAmelCase_			,  lowerCAmelCase_ = False			,  lowerCAmelCase_ = False			,  lowerCAmelCase_ = False			,  lowerCAmelCase_ = False			,  )						->							Optional[Any]:
										_snake_case													=			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'					)
										_snake_case													=			[[refs[i] for refs in references] for i in range(lowerCAmelCase_					)]

										_snake_case													=			TER(
										    normalized=lowerCAmelCase_			,  no_punct=lowerCAmelCase_			,  asian_support=lowerCAmelCase_			,  case_sensitive=lowerCAmelCase_			,  )
										_snake_case													=			sb_ter.corpus_score(lowerCAmelCase_			,  lowerCAmelCase_					)

										return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}










import json
import os
import unittest

from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast
from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class      UpperCamelCase_						(					_lowerCamelCase							,					unittest.TestCase   ):
					lowerCAmelCase_							=		LEDTokenizer
					lowerCAmelCase_							=		LEDTokenizerFast
					lowerCAmelCase_							=		True




					def 		lowerCAmelCase     (						self					)						->							List[str]:
										super().setUp()
										_snake_case													=			[
										    'l',
										    'o',
										    'w',
										    'e',
										    'r',
										    's',
										    't',
										    'i',
										    'd',
										    'n',
										    '\u0120',
										    '\u0120l',
										    '\u0120n',
										    '\u0120lo',
										    '\u0120low',
										    'er',
										    '\u0120lowest',
										    '\u0120newer',
										    '\u0120wider',
										    '<unk>',
										]
										_snake_case													=			dict(zip(lowerCAmelCase_			,  range(len(lowerCAmelCase_					)					)					)					)
										_snake_case													=			['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
										_snake_case													=			{'unk_token': '<unk>'}

										_snake_case													=			os.path.join(self.tmpdirname			,  VOCAB_FILES_NAMES['vocab_file']					)
										_snake_case													=			os.path.join(self.tmpdirname			,  VOCAB_FILES_NAMES['merges_file']					)
										with open(self.vocab_file			,  'w'			,  encoding='utf-8'					) as fp:
															fp.write(json.dumps(lowerCAmelCase_					) + '\n'					)
										with open(self.merges_file			,  'w'			,  encoding='utf-8'					) as fp:
															fp.write('\n'.join(lowerCAmelCase_					)					)




					def 		lowerCAmelCase     (						self			,  **lowerCAmelCase_					)						->							List[str]:
										kwargs.update(self.special_tokens_map					)
										return self.tokenizer_class.from_pretrained(self.tmpdirname			,  **lowerCAmelCase_					)




					def 		lowerCAmelCase     (						self			,  **lowerCAmelCase_					)						->							str:
										kwargs.update(self.special_tokens_map					)
										return self.rust_tokenizer_class.from_pretrained(self.tmpdirname			,  **lowerCAmelCase_					)




					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_					)						->							Union[str, Any]:
										return "lower newer", "lower newer"




					@cached_property
					def 		lowerCAmelCase     (						self					)						->							Optional[Any]:
										return LEDTokenizer.from_pretrained('allenai/led-base-16384'					)




					@cached_property
					def 		lowerCAmelCase     (						self					)						->							Union[str, Any]:
										return LEDTokenizerFast.from_pretrained('allenai/led-base-16384'					)




					@require_torch
					def 		lowerCAmelCase     (						self					)						->							Union[str, Any]:
										_snake_case													=			['A long paragraph for summarization.', 'Another paragraph for summarization.']
										_snake_case													=			[0, 250, 251, 1_7818, 13, 3_9186, 1938, 4, 2]

										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
															_snake_case													=			tokenizer(lowerCAmelCase_			,  max_length=len(lowerCAmelCase_					)			,  padding=lowerCAmelCase_			,  return_tensors='pt'					)
															self.assertIsInstance(lowerCAmelCase_			,  lowerCAmelCase_					)

															self.assertEqual((2, 9)			,  batch.input_ids.shape					)
															self.assertEqual((2, 9)			,  batch.attention_mask.shape					)
															_snake_case													=			batch.input_ids.tolist()[0]
															self.assertListEqual(lowerCAmelCase_			,  lowerCAmelCase_					)




					@require_torch
					def 		lowerCAmelCase     (						self					)						->							Optional[Any]:
										_snake_case													=			['A long paragraph for summarization.', 'Another paragraph for summarization.']
										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
															_snake_case													=			tokenizer(lowerCAmelCase_			,  padding=lowerCAmelCase_			,  return_tensors='pt'					)
															self.assertIn('input_ids'			,  lowerCAmelCase_					)
															self.assertIn('attention_mask'			,  lowerCAmelCase_					)
															self.assertNotIn('labels'			,  lowerCAmelCase_					)
															self.assertNotIn('decoder_attention_mask'			,  lowerCAmelCase_					)




					@require_torch
					def 		lowerCAmelCase     (						self					)						->							Optional[int]:
										_snake_case													=			[
										    'Summary of the text.',
										    'Another summary.',
										]
										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
															_snake_case													=			tokenizer(text_target=lowerCAmelCase_			,  max_length=32			,  padding='max_length'			,  return_tensors='pt'					)
															self.assertEqual(32			,  targets['input_ids'].shape[1]					)




					@require_torch
					def 		lowerCAmelCase     (						self					)						->							List[str]:
										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
															_snake_case													=			tokenizer(
															    ['I am a small frog' * 1024, 'I am a small frog']			,  padding=lowerCAmelCase_			,  truncation=lowerCAmelCase_			,  return_tensors='pt'					)
															self.assertIsInstance(lowerCAmelCase_			,  lowerCAmelCase_					)
															self.assertEqual(batch.input_ids.shape			,  (2, 5122)					)




					@require_torch
					def 		lowerCAmelCase     (						self					)						->							Union[str, Any]:
										_snake_case													=			['A long paragraph for summarization.']
										_snake_case													=			[
										    'Summary of the text.',
										]
										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
															_snake_case													=			tokenizer(lowerCAmelCase_			,  return_tensors='pt'					)
															_snake_case													=			tokenizer(text_target=lowerCAmelCase_			,  return_tensors='pt'					)
															_snake_case													=			inputs['input_ids']
															_snake_case													=			targets['input_ids']
															self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item()					)
															self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item()					)
															self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item()					)
															self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item()					)




					@require_torch
					def 		lowerCAmelCase     (						self					)						->							List[str]:
										for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
															_snake_case													=			['Summary of the text.', 'Another summary.']
															_snake_case													=			[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]]

															_snake_case													=			tokenizer(lowerCAmelCase_			,  padding=lowerCAmelCase_					)
															_snake_case													=			[[0] * len(lowerCAmelCase_					) for x in encoded_output['input_ids']]
															_snake_case													=			tokenizer.pad(lowerCAmelCase_					)
															self.assertSequenceEqual(outputs['global_attention_mask']			,  lowerCAmelCase_					)




					def 		lowerCAmelCase     (						self					)						->							Tuple:
										pass






					def 		lowerCAmelCase     (						self					)						->							str:
										for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''					):
																				_snake_case													=			self.rust_tokenizer_class.from_pretrained(lowerCAmelCase_			,  **lowerCAmelCase_					)
																				_snake_case													=			self.tokenizer_class.from_pretrained(lowerCAmelCase_			,  **lowerCAmelCase_					)
																				_snake_case													=			'A, <mask> AllenNLP sentence.'
																				_snake_case													=			tokenizer_r.encode_plus(lowerCAmelCase_			,  add_special_tokens=lowerCAmelCase_			,  return_token_type_ids=lowerCAmelCase_					)
																				_snake_case													=			tokenizer_p.encode_plus(lowerCAmelCase_			,  add_special_tokens=lowerCAmelCase_			,  return_token_type_ids=lowerCAmelCase_					)
																				self.assertEqual(sum(tokens_r['token_type_ids']					)			,  sum(tokens_p['token_type_ids']					)					)
																				self.assertEqual(
																				    sum(tokens_r['attention_mask']					) / len(tokens_r['attention_mask']					)			,  sum(tokens_p['attention_mask']					) / len(tokens_p['attention_mask']					)			,  )

																				_snake_case													=			tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids']					)
																				_snake_case													=			tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids']					)
																				self.assertSequenceEqual(tokens_p['input_ids']			,  [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2]					)
																				self.assertSequenceEqual(tokens_r['input_ids']			,  [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2]					)

																				self.assertSequenceEqual(
																				    lowerCAmelCase_			,  ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>']					)
																				self.assertSequenceEqual(
																				    lowerCAmelCase_			,  ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>']					)



