
"""simple docstring"""






import pickle
import shutil
import tempfile
import unittest

from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


_lowercase							=				get_tests_dir('''fixtures/test_sentencepiece.model''')

@require_sentencepiece
@require_tokenizers
class 					__a     ( snake_case_					,   unittest.TestCase       ):



							'''simple docstring'''







							_lowerCamelCase					:			List[str]          =   XLMRobertaTokenizer
							_lowerCamelCase					:			Tuple          =   XLMRobertaTokenizerFast
							_lowerCamelCase					:			Any          =   True
							_lowerCamelCase					:			List[str]          =   True
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Any:




										'''simple docstring'''
										super().setUp()

										# We have a SentencePiece fixture for testing
										__lowercase       =       XLMRobertaTokenizer(_lowerCamelCase  ,    keep_accents=_lowerCamelCase       )
										tokenizer.save_pretrained(self.tmpdirname       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Union[str, Any]:




										'''simple docstring'''
										__lowercase       =       "<pad>"
										__lowercase       =       1

										self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase       )  ,    _lowerCamelCase       )
										self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase       )  ,    _lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							List[str]:




										'''simple docstring'''
										__lowercase       =       list(self.get_tokenizer().get_vocab().keys()       )

										self.assertEqual(vocab_keys[0]  ,    "<s>"       )
										self.assertEqual(vocab_keys[1]  ,    "<pad>"       )
										self.assertEqual(vocab_keys[-1]  ,    "<mask>"       )
										self.assertEqual(len(_lowerCamelCase       )  ,    1_002       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							List[Any]:




										'''simple docstring'''
										self.assertEqual(self.get_tokenizer().vocab_size  ,    1_002       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Union[str, Any]:




										'''simple docstring'''
										__lowercase       =       XLMRobertaTokenizer(_lowerCamelCase  ,    keep_accents=_lowerCamelCase       )

										__lowercase       =       tokenizer.tokenize("This is a test"       )
										self.assertListEqual(_lowerCamelCase  ,    ["▁This", "▁is", "▁a", "▁t", "est"]       )

										self.assertListEqual(
										    tokenizer.convert_tokens_to_ids(_lowerCamelCase       )  ,    [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]]  ,    )

										__lowercase       =       tokenizer.tokenize("I was born in 92000, and this is falsé."       )
										self.assertListEqual(
										    _lowerCamelCase  ,    [
										        SPIECE_UNDERLINE + "I",
										        SPIECE_UNDERLINE + "was",
										        SPIECE_UNDERLINE + "b",
										        "or",
										        "n",
										        SPIECE_UNDERLINE + "in",
										        SPIECE_UNDERLINE + "",
										        "9",
										        "2",
										        "0",
										        "0",
										        "0",
										        ",",
										        SPIECE_UNDERLINE + "and",
										        SPIECE_UNDERLINE + "this",
										        SPIECE_UNDERLINE + "is",
										        SPIECE_UNDERLINE + "f",
										        "al",
										        "s",
										        "é",
										        ".",
										    ]  ,    )
										__lowercase       =       tokenizer.convert_tokens_to_ids(_lowerCamelCase       )
										self.assertListEqual(
										    _lowerCamelCase  ,    [
										        value + tokenizer.fairseq_offset
										        for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
										        #                                       ^ unk: 2 + 1 = 3                  unk: 2 + 1 = 3 ^
										    ]  ,    )

										__lowercase       =       tokenizer.convert_ids_to_tokens(_lowerCamelCase       )
										self.assertListEqual(
										    _lowerCamelCase  ,    [
										        SPIECE_UNDERLINE + "I",
										        SPIECE_UNDERLINE + "was",
										        SPIECE_UNDERLINE + "b",
										        "or",
										        "n",
										        SPIECE_UNDERLINE + "in",
										        SPIECE_UNDERLINE + "",
										        "<unk>",
										        "2",
										        "0",
										        "0",
										        "0",
										        ",",
										        SPIECE_UNDERLINE + "and",
										        SPIECE_UNDERLINE + "this",
										        SPIECE_UNDERLINE + "is",
										        SPIECE_UNDERLINE + "f",
										        "al",
										        "s",
										        "<unk>",
										        ".",
										    ]  ,    )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							List[str]:




										'''simple docstring'''
										if not self.test_slow_tokenizer:
													# as we don't have a slow version, we can't compare the outputs between slow and fast versions
													return

										__lowercase       =       (self.rust_tokenizer_class, "hf-internal-testing/tiny-xlm-roberta", {})
										for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
													with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''       ):
																__lowercase       =       self.rust_tokenizer_class.from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )
																__lowercase       =       self.tokenizer_class.from_pretrained(_lowerCamelCase  ,    **_lowerCamelCase       )

																__lowercase       =       tempfile.mkdtemp()

																__lowercase       =       tokenizer_r.save_pretrained(_lowerCamelCase       )
																__lowercase       =       tokenizer_p.save_pretrained(_lowerCamelCase       )

																# Checks it save with the same files + the tokenizer.json file for the fast one
																self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files       )       )
																__lowercase       =       tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f       )
																self.assertSequenceEqual(_lowerCamelCase  ,    _lowerCamelCase       )

																# Checks everything loads correctly in the same way
																__lowercase       =       tokenizer_r.from_pretrained(_lowerCamelCase       )
																__lowercase       =       tokenizer_p.from_pretrained(_lowerCamelCase       )

																# Check special tokens are set accordingly on Rust and Python
																for key in tokenizer_pp.special_tokens_map:
																			self.assertTrue(hasattr(_lowerCamelCase  ,    _lowerCamelCase       )       )
																			# self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key))
																			# self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id"))

																shutil.rmtree(_lowerCamelCase       )

																# Save tokenizer rust, legacy_format=True
																__lowercase       =       tempfile.mkdtemp()

																__lowercase       =       tokenizer_r.save_pretrained(_lowerCamelCase  ,    legacy_format=_lowerCamelCase       )
																__lowercase       =       tokenizer_p.save_pretrained(_lowerCamelCase       )

																# Checks it save with the same files
																self.assertSequenceEqual(_lowerCamelCase  ,    _lowerCamelCase       )

																# Checks everything loads correctly in the same way
																__lowercase       =       tokenizer_r.from_pretrained(_lowerCamelCase       )
																__lowercase       =       tokenizer_p.from_pretrained(_lowerCamelCase       )

																# Check special tokens are set accordingly on Rust and Python
																for key in tokenizer_pp.special_tokens_map:
																			self.assertTrue(hasattr(_lowerCamelCase  ,    _lowerCamelCase       )       )

																shutil.rmtree(_lowerCamelCase       )

																# Save tokenizer rust, legacy_format=False
																__lowercase       =       tempfile.mkdtemp()

																__lowercase       =       tokenizer_r.save_pretrained(_lowerCamelCase  ,    legacy_format=_lowerCamelCase       )
																__lowercase       =       tokenizer_p.save_pretrained(_lowerCamelCase       )

																# Checks it saved the tokenizer.json file
																self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files       )       )

																# Checks everything loads correctly in the same way
																__lowercase       =       tokenizer_r.from_pretrained(_lowerCamelCase       )
																__lowercase       =       tokenizer_p.from_pretrained(_lowerCamelCase       )

																# Check special tokens are set accordingly on Rust and Python
																for key in tokenizer_pp.special_tokens_map:
																			self.assertTrue(hasattr(_lowerCamelCase  ,    _lowerCamelCase       )       )

																shutil.rmtree(_lowerCamelCase       )
							@cached_property
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Optional[Any]:




										'''simple docstring'''
										return XLMRobertaTokenizer.from_pretrained("xlm-roberta-base"       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							int:




										'''simple docstring'''
										with tempfile.NamedTemporaryFile() as f:
													shutil.copyfile(_lowerCamelCase  ,    f.name       )
													__lowercase       =       XLMRobertaTokenizer(f.name  ,    keep_accents=_lowerCamelCase       )
													__lowercase       =       pickle.dumps(_lowerCamelCase       )
										pickle.loads(_lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Union[str, Any]:




										'''simple docstring'''
										if not self.test_rust_tokenizer:
													return

										__lowercase       =       self.get_tokenizer()
										__lowercase       =       self.get_rust_tokenizer()

										__lowercase       =       "I was born in 92000, and this is falsé."

										__lowercase       =       tokenizer.tokenize(_lowerCamelCase       )
										__lowercase       =       rust_tokenizer.tokenize(_lowerCamelCase       )
										self.assertListEqual(_lowerCamelCase  ,    _lowerCamelCase       )

										__lowercase       =       tokenizer.encode(_lowerCamelCase  ,    add_special_tokens=_lowerCamelCase       )
										__lowercase       =       rust_tokenizer.encode(_lowerCamelCase  ,    add_special_tokens=_lowerCamelCase       )
										self.assertListEqual(_lowerCamelCase  ,    _lowerCamelCase       )

										__lowercase       =       self.get_rust_tokenizer()
										__lowercase       =       tokenizer.encode(_lowerCamelCase       )
										__lowercase       =       rust_tokenizer.encode(_lowerCamelCase       )
										self.assertListEqual(_lowerCamelCase  ,    _lowerCamelCase       )
							@slow
							def   SCREAMING_SNAKE_CASE						(     self       )			->							List[Any]:




										'''simple docstring'''
										__lowercase       =       "Hello World!"
										__lowercase       =       [0, 35_378, 6_661, 38, 2]
										# xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base')  # xlmr.large has same tokenizer
										# xlmr.eval()
										# xlmr.encode(symbols)

										self.assertListEqual(_lowerCamelCase  ,    self.big_tokenizer.encode(_lowerCamelCase       )       )
							@slow
							def   SCREAMING_SNAKE_CASE						(     self       )			->							Any:




										'''simple docstring'''
										__lowercase       =       (
										    "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will"
										    " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth"
										)
										__lowercase       =       [
										    0,
										    3_293,
										    83,
										    10,
										    4_552,
										    4_989,
										    7_986,
										    678,
										    10,
										    5_915,
										    111,
										    179_459,
										    124_850,
										    4,
										    6_044,
										    237,
										    12,
										    6,
										    5,
										    6,
										    4,
										    6_780,
										    705,
										    15,
										    1_388,
										    44,
										    378,
										    10_114,
										    711,
										    152,
										    20,
										    6,
										    5,
										    22_376,
										    642,
										    1_221,
										    15_190,
										    34_153,
										    450,
										    5_608,
										    959,
										    1_119,
										    57_702,
										    136,
										    186,
										    47,
										    1_098,
										    29_367,
										    47,
										    # 4426, # What fairseq tokenizes from "<unk>": "_<"
										    # 3678, # What fairseq tokenizes from "<unk>": "unk"
										    # 2740, # What fairseq tokenizes from "<unk>": ">"
										    3,  # What we tokenize from "<unk>": "<unk>"
										    6,  # Residue from the tokenization: an extra sentencepiece underline
										    4,
										    6_044,
										    237,
										    6_284,
										    50_901,
										    528,
										    31,
										    90,
										    34,
										    927,
										    2,
										]
										# xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base')  # xlmr.large has same tokenizer
										# xlmr.eval()
										# xlmr.encode(symbols)

										self.assertListEqual(_lowerCamelCase  ,    self.big_tokenizer.encode(_lowerCamelCase       )       )





							@slow
							def   SCREAMING_SNAKE_CASE						(     self       )			->							int:




										'''simple docstring'''
										# fmt: off
										__lowercase       =       {"input_ids": [[0, 11_062, 82_772, 7, 15, 82_772, 538, 51_529, 237, 17_198, 1_290, 206, 9, 215_175, 1_314, 136, 17_198, 1_290, 206, 9, 56_359, 42, 122_009, 9, 16_466, 16, 87_344, 4_537, 9, 4_717, 78_381, 6, 159_958, 7, 15, 24_480, 618, 4, 527, 22_693, 5_428, 4, 2_777, 24_480, 9_874, 4, 43_523, 594, 4, 803, 18_392, 33_189, 18, 4, 43_523, 24_447, 12_399, 100, 24_955, 83_658, 9_626, 144_057, 15, 839, 22_335, 16, 136, 24_955, 83_658, 83_479, 15, 39_102, 724, 16, 678, 645, 2_789, 1_328, 4_589, 42, 122_009, 115_774, 23, 805, 1_328, 46_876, 7, 136, 53_894, 1_940, 42_227, 41_159, 17_721, 823, 425, 4, 27_512, 98_722, 206, 136, 5_531, 4_970, 919, 17_336, 5, 2], [0, 20_080, 618, 83, 82_775, 47, 479, 9, 1_517, 73, 53_894, 333, 80_581, 110_117, 18_811, 5_256, 1_295, 51, 152_526, 297, 7_986, 390, 124_416, 538, 35_431, 214, 98, 15_044, 25_737, 136, 7_108, 43_701, 23,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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
										# fmt: on

										self.tokenizer_integration_test_util(
										    expected_encoding=_lowerCamelCase  ,    model_name="xlm-roberta-base"  ,    revision="d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3"  ,    )







from typing import List

import jiwer
import jiwer.transforms as tr
from packaging import version

import datasets
from datasets.config import PY_VERSION


if PY_VERSION < version.parse('''3.8'''):
			import importlib_metadata
else:
			import importlib.metadata as importlib_metadata


__A							=''''''


if version.parse(importlib_metadata.version('''jiwer''')) < version.parse('''2.3.0'''):




			class        _SCREAMING_SNAKE_CASE	( tr.AbstractTransform		):



				def __init__(       self		,    lowercase = " "					)							->			List[str]:
								lowerCamelCase_         =     sentence_delimiter



				def        SCREAMING_SNAKE_CASE_(       self		,    lowercase					)							->			Optional[int]:
								return list(lowercase					)



				def        SCREAMING_SNAKE_CASE_(       self		,    lowercase					)							->			List[str]:
								lowerCamelCase_         =     []
								for sent_idx, sentence in enumerate(lowercase					):
												chars.extend(self.process_string(lowercase					)					)
												if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(lowercase					) - 1:
																chars.append(self.sentence_delimiter					)
								return chars



			__A							=tr.Compose(
			    [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
			)
else:
			__A							=tr.Compose(
			    [
			        tr.RemoveMultipleSpaces(),
			        tr.Strip(),
			        tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
			        tr.ReduceToListOfListOfChars(),
			    ]
			)


__A							='''\
@inproceedings{inproceedings,
    author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
    year = {2004},
    month = {01},
    pages = {},
    title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
'''

__A							='''\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.

CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.

Character error rate can be computed as:

CER = (S + D + I) / N = (S + D + I) / (S + D + C)

where

S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).

CER\'s output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
'''

__A							='''
Computes CER score of transcribed segments against references.
Args:
    references: list of references for each speech input.
    predictions: list of transcribtions to score.
    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
    (float): the character error rate

Examples:

    >>> predictions = ["this is the prediction", "there is an other sample"]
    >>> references = ["this is the reference", "there is another one"]
    >>> cer = datasets.load_metric("cer")
    >>> cer_score = cer.compute(predictions=predictions, references=references)
    >>> print(cer_score)
    0.34146341463414637
'''




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



	def        SCREAMING_SNAKE_CASE_(       self					)							->			Union[str, Any]:
					return datasets.MetricInfo(
					    description=_DESCRIPTION		,    citation=_CITATION		,    inputs_description=_KWARGS_DESCRIPTION		,    features=datasets.Features(
					        {
					            "predictions": datasets.Value("string"		,    id="sequence"					),
					            "references": datasets.Value("string"		,    id="sequence"					),
					        }					)		,    codebase_urls=["https://github.com/jitsi/jiwer/"]		,    reference_urls=[
					        "https://en.wikipedia.org/wiki/Word_error_rate",
					        "https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates",
					    ]		,    )



	def        SCREAMING_SNAKE_CASE_(       self		,    lowercase		,    lowercase		,    lowercase=False					)							->			List[str]:
					if concatenate_texts:
									return jiwer.compute_measures(
									    lowercase		,    lowercase		,    truth_transform=lowercase		,    hypothesis_transform=lowercase		,    )["wer"]

					lowerCamelCase_         =     0
					lowerCamelCase_         =     0
					for prediction, reference in zip(lowercase		,    lowercase					):
									lowerCamelCase_         =     jiwer.compute_measures(
									    lowercase		,    lowercase		,    truth_transform=lowercase		,    hypothesis_transform=lowercase		,    )
									incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
									total += measures["substitutions"] + measures["deletions"] + measures["hits"]

					return incorrect / total


