


'''simple docstring'''




import sacrebleu as scb
from packaging import version

import datasets


_lowerCAmelCase	:		List[str]		  =						'\\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'

_lowerCAmelCase	:		List[Any]		  =						'\\nSacreBLEU provides hassle-free computation of shareable, comparable, and reproducible BLEU scores.\nInspired by Rico Sennrich\'s `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text.\nIt also knows all the standard test sets and handles downloading, processing, and tokenization for you.\n\nSee the [README.md] file at https://github.com/mjpost/sacreBLEU for more information.\n'

_lowerCAmelCase	:		Optional[Any]		  =						'\nProduces BLEU scores along with its sufficient statistics\nfrom a source against one or more references.\n\nArgs:\n    predictions (`list` of `str`): list of translations to score. Each translation should be tokenized into a list of tokens.\n    references (`list` of `list` of `str`): A list of lists of references. The contents of the first sub-list are the references for the first prediction, the contents of the second sub-list are for the second prediction, etc. Note that there must be the same number of references for each prediction (i.e. all sub-lists must be of the same length).\n    smooth_method (`str`): The smoothing method to use, defaults to `\'exp\'`. Possible values are:\n        - `\'none\'`: no smoothing\n        - `\'floor\'`: increment zero counts\n        - `\'add-k\'`: increment num/denom by k for n>1\n        - `\'exp\'`: exponential decay\n    smooth_value (`float`): The smoothing value. Only valid when `smooth_method=\'floor\'` (in which case `smooth_value` defaults to `0.1`) or `smooth_method=\'add-k\'` (in which case `smooth_value` defaults to `1`).\n    tokenize (`str`): Tokenization method to use for BLEU. If not provided, defaults to `\'zh\'` for Chinese, `\'ja-mecab\'` for Japanese and `\'13a\'` (mteval) otherwise. Possible values are:\n        - `\'none\'`: No tokenization.\n        - `\'zh\'`: Chinese tokenization.\n        - `\'13a\'`: mimics the `mteval-v13a` script from Moses.\n        - `\'intl\'`: International tokenization, mimics the `mteval-v14` script from Moses\n        - `\'char\'`: Language-agnostic character-level tokenization.\n        - `\'ja-mecab\'`: Japanese tokenization. Uses the [MeCab tokenizer](https://pypi.org/project/mecab-python3).\n    lowercase (`bool`): If `True`, lowercases the input, enabling case-insensitivity. Defaults to `False`.\n    force (`bool`): If `True`, insists that your tokenized input is actually detokenized. Defaults to `False`.\n    use_effective_order (`bool`): If `True`, stops including n-gram orders for which precision is 0. This should be `True`, if sentence-level BLEU will be computed. Defaults to `False`.\n\nReturns:\n    \'score\': BLEU score,\n    \'counts\': Counts,\n    \'totals\': Totals,\n    \'precisions\': Precisions,\n    \'bp\': Brevity penalty,\n    \'sys_len\': predictions length,\n    \'ref_len\': reference length,\n\nExamples:\n\n    Example 1:\n        >>> predictions = ["hello there general kenobi", "foo bar foobar"]\n        >>> references = [["hello there general kenobi", "hello there !"], ["foo bar foobar", "foo bar foobar"]]\n        >>> sacrebleu = datasets.load_metric("sacrebleu")\n        >>> results = sacrebleu.compute(predictions=predictions, references=references)\n        >>> print(list(results.keys()))\n        [\'score\', \'counts\', \'totals\', \'precisions\', \'bp\', \'sys_len\', \'ref_len\']\n        >>> print(round(results["score"], 1))\n        100.0\n\n    Example 2:\n        >>> predictions = ["hello there general kenobi",\n        ...                 "on our way to ankh morpork"]\n        >>> references = [["hello there general kenobi", "hello there !"],\n        ...                 ["goodbye ankh morpork", "ankh morpork"]]\n        >>> sacrebleu = datasets.load_metric("sacrebleu")\n        >>> results = sacrebleu.compute(predictions=predictions,\n        ...                             references=references)\n        >>> print(list(results.keys()))\n        [\'score\', \'counts\', \'totals\', \'precisions\', \'bp\', \'sys_len\', \'ref_len\']\n        >>> print(round(results["score"], 1))\n        39.8\n'



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



	def 					lowercase  (       self     ):
		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='https://github.com/mjpost/sacreBLEU'			,       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']			,       reference_urls=[
		        '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 					lowercase  (       self			,       snake_case__			,       snake_case__			,       snake_case__="exp"			,       snake_case__=None			,       snake_case__=False			,       snake_case__=False			,       snake_case__=None			,       snake_case__=False			,       ):
		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       :     List[Any]   				=			[[refs[i] for refs in references] for i in range(_lowerCamelCase     )]
		lowerCAmelCase       :     int   				=			scb.corpus_bleu(
		    _lowerCamelCase			,       _lowerCamelCase			,       smooth_method=_lowerCamelCase			,       smooth_value=_lowerCamelCase			,       force=_lowerCamelCase			,       lowercase=_lowerCamelCase			,       use_effective_order=_lowerCamelCase			,       **({'tokenize': tokenize} if tokenize else {})			,       )
		lowerCAmelCase       :     Optional[int]   				=			{
		    'score': output.score,
		    'counts': output.counts,
		    'totals': output.totals,
		    'precisions': output.precisions,
		    'bp': output.bp,
		    'sys_len': output.sys_len,
		    'ref_len': output.ref_len,
		}
		return output_dict








"""simple docstring"""



import json
import os
import shutil
import tempfile
import unittest

from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.utils import FEATURE_EXTRACTOR_NAME

from .test_feature_extraction_wavaveca import floats_list

class 			a	(  unittest.TestCase      ):







    def      UpperCamelCase_ (     self			):
      lowercase				       =			'<pad> <s> </s> <unk> | E T A O N I H S R D L U M W C F G Y P B V K \' X J Q Z'.split(' '			)
      lowercase				       =			dict(zip(_lowerCamelCase				,						range(len(_lowerCamelCase			)			)			)			)

      lowercase				       =			{
          'pad_token': '<pad>',
          'unk_token': '<unk>',
          'bos_token': '<s>',
          'eos_token': '</s>',
      }
      lowercase				       =			{
          'feature_size': 1,
          'padding_value': 0.0,
          'sampling_rate': 1_6_0_0_0,
          'return_attention_mask': False,
          'do_normalize': True,
      }

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

      with open(self.feature_extraction_file				,						'w'				,						encoding='utf-8'			) as fp:
        fp.write(json.dumps(_lowerCamelCase			) + '\n'			)







    def      UpperCamelCase_ (     self				,						**_lowerCamelCase			):
      lowercase				       =			self.add_kwargs_tokens_map.copy()
      kwargs.update(_lowerCamelCase			)
      return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname				,						**_lowerCamelCase			)







    def      UpperCamelCase_ (     self				,						**_lowerCamelCase			):
      return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname				,						**_lowerCamelCase			)







    def      UpperCamelCase_ (     self			):
      shutil.rmtree(self.tmpdirname			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.get_tokenizer()
      lowercase				       =			self.get_feature_extractor()

      lowercase				       =			WavaVecaProcessor(tokenizer=_lowerCamelCase				,						feature_extractor=_lowerCamelCase			)

      processor.save_pretrained(self.tmpdirname			)
      lowercase				       =			WavaVecaProcessor.from_pretrained(self.tmpdirname			)

      self.assertEqual(processor.tokenizer.get_vocab()				,						tokenizer.get_vocab()			)
      self.assertIsInstance(processor.tokenizer				,						_lowerCamelCase			)

      self.assertEqual(processor.feature_extractor.to_json_string()				,						feature_extractor.to_json_string()			)
      self.assertIsInstance(processor.feature_extractor				,						_lowerCamelCase			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			WavaVecaProcessor(tokenizer=self.get_tokenizer()				,						feature_extractor=self.get_feature_extractor()			)
      processor.save_pretrained(self.tmpdirname			)

      lowercase				       =			self.get_tokenizer(bos_token='(BOS)'				,						eos_token='(EOS)'			)
      lowercase				       =			self.get_feature_extractor(do_normalize=_lowerCamelCase				,						padding_value=1.0			)

      lowercase				       =			WavaVecaProcessor.from_pretrained(
          self.tmpdirname				,						bos_token='(BOS)'				,						eos_token='(EOS)'				,						do_normalize=_lowerCamelCase				,						padding_value=1.0			)

      self.assertEqual(processor.tokenizer.get_vocab()				,						tokenizer_add_kwargs.get_vocab()			)
      self.assertIsInstance(processor.tokenizer				,						_lowerCamelCase			)

      self.assertEqual(processor.feature_extractor.to_json_string()				,						feature_extractor_add_kwargs.to_json_string()			)
      self.assertIsInstance(processor.feature_extractor				,						_lowerCamelCase			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.get_feature_extractor()
      lowercase				       =			self.get_tokenizer()

      lowercase				       =			WavaVecaProcessor(tokenizer=_lowerCamelCase				,						feature_extractor=_lowerCamelCase			)

      lowercase				       =			floats_list((3, 1_0_0_0)			)

      lowercase				       =			feature_extractor(_lowerCamelCase				,						return_tensors='np'			)
      lowercase				       =			processor(_lowerCamelCase				,						return_tensors='np'			)

      for key in input_feat_extract.keys():
        self.assertAlmostEqual(input_feat_extract[key].sum()				,						input_processor[key].sum()				,						delta=1e-2			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.get_feature_extractor()
      lowercase				       =			self.get_tokenizer()

      lowercase				       =			WavaVecaProcessor(tokenizer=_lowerCamelCase				,						feature_extractor=_lowerCamelCase			)

      lowercase				       =			'This is a test string'

      lowercase				       =			processor(text=_lowerCamelCase			)

      lowercase				       =			tokenizer(_lowerCamelCase			)

      for key in encoded_tok.keys():
        self.assertListEqual(encoded_tok[key]				,						encoded_processor[key]			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.get_feature_extractor()
      lowercase				       =			self.get_tokenizer()

      lowercase				       =			WavaVecaProcessor(tokenizer=_lowerCamelCase				,						feature_extractor=_lowerCamelCase			)

      lowercase				       =			[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

      lowercase				       =			processor.batch_decode(_lowerCamelCase			)
      lowercase				       =			tokenizer.batch_decode(_lowerCamelCase			)

      self.assertListEqual(_lowerCamelCase				,						_lowerCamelCase			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.get_feature_extractor()
      lowercase				       =			self.get_tokenizer()

      lowercase				       =			WavaVecaProcessor(tokenizer=_lowerCamelCase				,						feature_extractor=_lowerCamelCase			)

      self.assertListEqual(
          processor.model_input_names				,						feature_extractor.model_input_names				,						msg='`processor` and `feature_extractor` model input names do not match'				,						)


