






import shutil
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from transformers import SpeechaTextTokenizer, is_speech_available
from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, require_torchaudio
from transformers.utils import FEATURE_EXTRACTOR_NAME

from .test_feature_extraction_speech_to_text import floats_list


if is_speech_available():
		from transformers import SpeechaTextFeatureExtractor, SpeechaTextProcessor


__magic_name__:  Optional[Any]  	=			get_tests_dir("fixtures/test_sentencepiece.model")





@require_torch
@require_torchaudio
@require_sentencepiece
class  snake_case__      (							unittest.TestCase   ):
	def     __magic_name__       (       self				)							->   Union[str, Any]:
							__magic_name__    :     Optional[int]     		=      tempfile.mkdtemp()

							__magic_name__    :     str     		=      ["""<s>""", """<pad>""", """</s>""", """<unk>""", """▁This""", """▁is""", """▁a""", """▁t""", """est"""]
							__magic_name__    :     Tuple     		=      dict(zip(lowerCAmelCase__    ,     range(len(lowerCAmelCase__				)				)				)				)
							__magic_name__    :     Tuple     		=      Path(self.tmpdirname				)
							save_json(lowerCAmelCase__    ,     save_dir / VOCAB_FILES_NAMES["""vocab_file"""]				)
							if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
													copyfile(lowerCAmelCase__    ,     save_dir / VOCAB_FILES_NAMES["""spm_file"""]				)

							__magic_name__    :     Optional[Any]     		=      SpeechaTextTokenizer.from_pretrained(self.tmpdirname				)
							tokenizer.save_pretrained(self.tmpdirname				)

							__magic_name__    :     Optional[int]     		=      {
							    """feature_size""": 24,
							    """num_mel_bins""": 24,
							    """padding_value""": 0.0,
							    """sampling_rate""": 1_60_00,
							    """return_attention_mask""": False,
							    """do_normalize""": True,
							}
							save_json(lowerCAmelCase__    ,     save_dir / FEATURE_EXTRACTOR_NAME				)
	def     __magic_name__       (       self    ,     **lowerCAmelCase__				)							->   str:
							return SpeechaTextTokenizer.from_pretrained(self.tmpdirname    ,     **lowerCAmelCase__				)
	def     __magic_name__       (       self    ,     **lowerCAmelCase__				)							->   Dict:
							return SpeechaTextFeatureExtractor.from_pretrained(self.tmpdirname    ,     **lowerCAmelCase__				)
	def     __magic_name__       (       self				)							->   Optional[int]:
							shutil.rmtree(self.tmpdirname				)
	def     __magic_name__       (       self				)							->   int:
							__magic_name__    :     Tuple     		=      self.get_tokenizer()
							__magic_name__    :     str     		=      self.get_feature_extractor()

							__magic_name__    :     Optional[int]     		=      SpeechaTextProcessor(tokenizer=lowerCAmelCase__    ,     feature_extractor=lowerCAmelCase__				)

							processor.save_pretrained(self.tmpdirname				)
							__magic_name__    :     Union[str, Any]     		=      SpeechaTextProcessor.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     __magic_name__       (       self				)							->   int:
							__magic_name__    :     int     		=      SpeechaTextProcessor(
							    tokenizer=self.get_tokenizer()    ,     feature_extractor=self.get_feature_extractor()				)
							processor.save_pretrained(self.tmpdirname				)

							__magic_name__    :     Dict     		=      self.get_tokenizer(bos_token="""(BOS)"""    ,     eos_token="""(EOS)"""				)
							__magic_name__    :     int     		=      self.get_feature_extractor(do_normalize=lowerCAmelCase__    ,     padding_value=1.0				)

							__magic_name__    :     Optional[Any]     		=      SpeechaTextProcessor.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     __magic_name__       (       self				)							->   Any:
							__magic_name__    :     Tuple     		=      self.get_feature_extractor()
							__magic_name__    :     int     		=      self.get_tokenizer()

							__magic_name__    :     int     		=      SpeechaTextProcessor(tokenizer=lowerCAmelCase__    ,     feature_extractor=lowerCAmelCase__				)

							__magic_name__    :     Any     		=      floats_list((3, 10_00)				)

							__magic_name__    :     Optional[int]     		=      feature_extractor(lowerCAmelCase__    ,     return_tensors="""np"""				)
							__magic_name__    :     Union[str, Any]     		=      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     __magic_name__       (       self				)							->   Tuple:
							__magic_name__    :     Any     		=      self.get_feature_extractor()
							__magic_name__    :     Optional[Any]     		=      self.get_tokenizer()

							__magic_name__    :     Any     		=      SpeechaTextProcessor(tokenizer=lowerCAmelCase__    ,     feature_extractor=lowerCAmelCase__				)

							__magic_name__    :     Union[str, Any]     		=      """This is a test string"""

							__magic_name__    :     Optional[Any]     		=      processor(text=lowerCAmelCase__				)

							__magic_name__    :     int     		=      tokenizer(lowerCAmelCase__				)

							for key in encoded_tok.keys():
													self.assertListEqual(encoded_tok[key]    ,     encoded_processor[key]				)
	def     __magic_name__       (       self				)							->   Union[str, Any]:
							__magic_name__    :     Optional[Any]     		=      self.get_feature_extractor()
							__magic_name__    :     Dict     		=      self.get_tokenizer()

							__magic_name__    :     Optional[Any]     		=      SpeechaTextProcessor(tokenizer=lowerCAmelCase__    ,     feature_extractor=lowerCAmelCase__				)

							__magic_name__    :     str     		=      [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

							__magic_name__    :     Optional[Any]     		=      processor.batch_decode(lowerCAmelCase__				)
							__magic_name__    :     List[str]     		=      tokenizer.batch_decode(lowerCAmelCase__				)

							self.assertListEqual(lowerCAmelCase__    ,     lowerCAmelCase__				)







	def     __magic_name__       (       self				)							->   Optional[int]:
							__magic_name__    :     str     		=      self.get_feature_extractor()
							__magic_name__    :     str     		=      self.get_tokenizer()

							__magic_name__    :     Optional[Any]     		=      SpeechaTextProcessor(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"""    ,     )








import sacrebleu as scb
from packaging import version

import datasets


__magic_name__:  Optional[int]  	=			"\\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"

__magic_name__:  int  	=			"\\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"

__magic_name__:  List[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  snake_case__      (							datasets.Metric   ):
	def     __magic_name__       (       self				)							->   Optional[int]:
							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     __magic_name__       (       self    ,     lowerCAmelCase__    ,     lowerCAmelCase__    ,     lowerCAmelCase__="exp"    ,     lowerCAmelCase__=None    ,     lowerCAmelCase__=False    ,     lowerCAmelCase__=False    ,     lowerCAmelCase__=None    ,     lowerCAmelCase__=False    ,     )							->   Optional[Any]:
							__magic_name__    :     Optional[int]     		=      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"""				)
							__magic_name__    :     Dict     		=      [[refs[i] for refs in references] for i in range(lowerCAmelCase__				)]
							__magic_name__    :     List[str]     		=      scb.corpus_bleu(
							    lowerCAmelCase__    ,     lowerCAmelCase__    ,     smooth_method=lowerCAmelCase__    ,     smooth_value=lowerCAmelCase__    ,     force=lowerCAmelCase__    ,     lowercase=lowerCAmelCase__    ,     use_effective_order=lowerCAmelCase__    ,     **({"""tokenize""": tokenize} if tokenize else {})    ,     )
							__magic_name__    :     List[str]     		=      {
							    """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
