
'''simple docstring'''







from jiwer import compute_measures

import datasets


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

_lowercase :  Optional[int]    							=       "\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n"

_lowercase :  str    							=       "\nCompute WER score of transcribed segments against references.\n\nArgs:\n    references: List of references for each speech input.\n    predictions: List of transcriptions to score.\n    concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n    (float): the word error rate\n\nExamples:\n\n    >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n    >>> references = [\"this is the reference\", \"there is another one\"]\n    >>> wer = datasets.load_metric(\"wer\")\n    >>> wer_score = wer.compute(predictions=predictions, references=references)\n    >>> print(wer_score)\n    0.5\n"






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






					def 	_snake_case    (   self		):


											"""simple docstring"""





											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''',
											    ]				,							)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE=None				,							__SCREAMING_SNAKE_CASE=None				,							__SCREAMING_SNAKE_CASE=False		):


											"""simple docstring"""





											if concatenate_texts:
																	return compute_measures(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)["wer"]
											else:
																	lowercase_	:     Any													=       0
																	lowercase_	:     Any													=       0
																	for prediction, reference in zip(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		):
																							lowercase_	:     List[Any]													=       compute_measures(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)
																							incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
																							total += measures["substitutions"] + measures["deletions"] + measures["hits"]
																	return incorrect / total





'''simple docstring'''







import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging


_lowercase :  str    							=       logging.get_logger(__name__)

_lowercase :  List[Any]    							=       "▁"

_lowercase :  List[Any]    							=       {"vocab_file": "sentencepiece.bpe.model"}

_lowercase :  Optional[int]    							=       {
    "vocab_file": {
        "facebook/mbart-large-en-ro": (
            "https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model"
        ),
        "facebook/mbart-large-cc25": (
            "https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model"
        ),
    }
}

_lowercase :  str    							=       {
    "facebook/mbart-large-en-ro": 1_0_2_4,
    "facebook/mbart-large-cc25": 1_0_2_4,
}

# fmt: off
_lowercase :  List[Any]    							=       ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN"]






class  lowerCAmelCase__   (  lowerCamelCase_     ):
					lowerCAmelCase_        =     VOCAB_FILES_NAMES
					lowerCAmelCase_        =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					lowerCAmelCase_        =     PRETRAINED_VOCAB_FILES_MAP
					lowerCAmelCase_        =     ['''input_ids''', '''attention_mask''']

					lowerCAmelCase_        =     []
					lowerCAmelCase_        =     []






					def __init__(   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE="<s>"				,							__SCREAMING_SNAKE_CASE="</s>"				,							__SCREAMING_SNAKE_CASE="</s>"				,							__SCREAMING_SNAKE_CASE="<s>"				,							__SCREAMING_SNAKE_CASE="<unk>"				,							__SCREAMING_SNAKE_CASE="<pad>"				,							__SCREAMING_SNAKE_CASE="<mask>"				,							__SCREAMING_SNAKE_CASE=None				,							__SCREAMING_SNAKE_CASE=None				,							__SCREAMING_SNAKE_CASE=None				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE=None				,							**__SCREAMING_SNAKE_CASE				,							):


											"""simple docstring"""





											lowercase_	:     Any													=       AddedToken(__SCREAMING_SNAKE_CASE				,							lstrip=__SCREAMING_SNAKE_CASE				,							rstrip=__SCREAMING_SNAKE_CASE		) if isinstance(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		) else mask_token

											lowercase_	:     int													=       {} if sp_model_kwargs is None else sp_model_kwargs

											super().__init__(
											    bos_token=__SCREAMING_SNAKE_CASE				,							eos_token=__SCREAMING_SNAKE_CASE				,							unk_token=__SCREAMING_SNAKE_CASE				,							sep_token=__SCREAMING_SNAKE_CASE				,							cls_token=__SCREAMING_SNAKE_CASE				,							pad_token=__SCREAMING_SNAKE_CASE				,							mask_token=__SCREAMING_SNAKE_CASE				,							tokenizer_file=__SCREAMING_SNAKE_CASE				,							src_lang=__SCREAMING_SNAKE_CASE				,							tgt_lang=__SCREAMING_SNAKE_CASE				,							additional_special_tokens=__SCREAMING_SNAKE_CASE				,							sp_model_kwargs=self.sp_model_kwargs				,							**__SCREAMING_SNAKE_CASE				,							)

											lowercase_	:     Optional[Any]													=       spm.SentencePieceProcessor(**self.sp_model_kwargs		)
											self.sp_model.Load(str(__SCREAMING_SNAKE_CASE		)		)
											lowercase_	:     List[str]													=       vocab_file

											# Original fairseq vocab and spm vocab must be "aligned":
											# Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
											# -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
											# fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
											# spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

											# Mimic fairseq token-to-id alignment for the first 4 token
											lowercase_	:     Tuple													=       {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

											# The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
											lowercase_	:     str													=       1

											lowercase_	:     str													=       len(self.sp_model		)
											lowercase_	:     List[Any]													=       {
											    code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__SCREAMING_SNAKE_CASE		)
											}
											lowercase_	:     Union[str, Any]													=       {v: k for k, v in self.lang_code_to_id.items()}
											lowercase_	:     List[Any]													=       len(self.sp_model		) + len(self.lang_code_to_id		) + self.fairseq_offset

											self.fairseq_tokens_to_ids.update(self.lang_code_to_id		)
											lowercase_	:     Union[str, Any]													=       {v: k for k, v in self.fairseq_tokens_to_ids.items()}
											lowercase_	:     Optional[Any]													=       list(self.lang_code_to_id.keys()		)

											if additional_special_tokens is not None:
																	# Only add those special tokens if they are not already there.
																	self._additional_special_tokens.extend(
																	    [t for t in additional_special_tokens if t not in self._additional_special_tokens]		)

											lowercase_	:     Optional[Any]													=       src_lang if src_lang is not None else '''en_XX'''
											lowercase_	:     str													=       self.lang_code_to_id[self._src_lang]
											lowercase_	:     Optional[Any]													=       tgt_lang
											self.set_src_lang_special_tokens(self._src_lang		)






					def __getstate__(   self		):


											"""simple docstring"""





											lowercase_	:     Optional[int]													=       self.__dict__.copy()
											lowercase_	:     Dict													=       None
											lowercase_	:     Any													=       self.sp_model.serialized_model_proto()
											return state






					def __setstate__(   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Optional[Any]													=       d

											# for backward compatibility
											if not hasattr(self				,							'''sp_model_kwargs'''		):
																	lowercase_	:     Dict													=       {}

											lowercase_	:     Optional[Any]													=       spm.SentencePieceProcessor(**self.sp_model_kwargs		)
											self.sp_model.LoadFromSerializedProto(self.sp_model_proto		)






					@property
					def 	_snake_case    (   self		):


											"""simple docstring"""





											return len(self.sp_model		) + len(self.lang_code_to_id		) + self.fairseq_offset + 1  # Plus 1 for the mask token






					@property
					def 	_snake_case    (   self		):


											"""simple docstring"""





											return self._src_lang






					@src_lang.setter
					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Tuple													=       new_src_lang
											self.set_src_lang_special_tokens(self._src_lang		)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = False		):


											"""simple docstring"""





											if already_has_special_tokens:
																	return super().get_special_tokens_mask(
																	    token_ids_a=__SCREAMING_SNAKE_CASE				,							token_ids_a=__SCREAMING_SNAKE_CASE				,							already_has_special_tokens=__SCREAMING_SNAKE_CASE		)

											lowercase_	:     Optional[Any]													=       [1] * len(self.prefix_tokens		)
											lowercase_	:     Tuple													=       [1] * len(self.suffix_tokens		)
											if token_ids_a is None:
																	return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE		)) + suffix_ones
											return prefix_ones + ([0] * len(__SCREAMING_SNAKE_CASE		)) + ([0] * len(__SCREAMING_SNAKE_CASE		)) + suffix_ones






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = None		):


											"""simple docstring"""





											if token_ids_a is None:
																	return self.prefix_tokens + token_ids_a + self.suffix_tokens
											# We don't expect to process pairs, but leave the pair logic for API consistency
											return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = None		):


											"""simple docstring"""





											lowercase_	:     Optional[int]													=       [self.sep_token_id]
											lowercase_	:     Any													=       [self.cls_token_id]

											if token_ids_a is None:
																	return len(cls + token_ids_a + sep		) * [0]
											return len(cls + token_ids_a + sep + sep + token_ids_a + sep		) * [0]






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							**__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											if src_lang is None or tgt_lang is None:
																	raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model'''		)
											lowercase_	:     Optional[Any]													=       src_lang
											lowercase_	:     Dict													=       self(__SCREAMING_SNAKE_CASE				,							add_special_tokens=__SCREAMING_SNAKE_CASE				,							return_tensors=__SCREAMING_SNAKE_CASE				,							**__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Optional[int]													=       self.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Optional[Any]													=       tgt_lang_id
											return inputs






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     str													=       {self.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE		): i for i in range(self.vocab_size		)}
											vocab.update(self.added_tokens_encoder		)
											return vocab






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											return self.sp_model.encode(__SCREAMING_SNAKE_CASE				,							out_type=__SCREAMING_SNAKE_CASE		)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											if token in self.fairseq_tokens_to_ids:
																	return self.fairseq_tokens_to_ids[token]
											lowercase_	:     Any													=       self.sp_model.PieceToId(__SCREAMING_SNAKE_CASE		)

											# Need to return unknown token if the SP model returned 0
											return spm_id + self.fairseq_offset if spm_id else self.unk_token_id






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											if index in self.fairseq_ids_to_tokens:
																	return self.fairseq_ids_to_tokens[index]
											return self.sp_model.IdToPiece(index - self.fairseq_offset		)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     int													=       ''''''.join(__SCREAMING_SNAKE_CASE		).replace(__SCREAMING_SNAKE_CASE				,							''' '''		).strip()
											return out_string






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = None		):


											"""simple docstring"""





											if not os.path.isdir(__SCREAMING_SNAKE_CASE		):
																	logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''		)
																	return
											lowercase_	:     Tuple													=       os.path.join(
											    __SCREAMING_SNAKE_CASE				,							(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']		)

											if os.path.abspath(self.vocab_file		) != os.path.abspath(__SCREAMING_SNAKE_CASE		) and os.path.isfile(self.vocab_file		):
																	copyfile(self.vocab_file				,							__SCREAMING_SNAKE_CASE		)
											elif not os.path.isfile(self.vocab_file		):
																	with open(__SCREAMING_SNAKE_CASE				,							'''wb'''		) as fi:
																							lowercase_	:     List[str]													=       self.sp_model.serialized_model_proto()
																							fi.write(__SCREAMING_SNAKE_CASE		)

											return (out_vocab_file,)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = "en_XX"				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = "ro_RO"				,							**__SCREAMING_SNAKE_CASE				,							):


											"""simple docstring"""





											lowercase_	:     List[str]													=       src_lang
											lowercase_	:     int													=       tgt_lang
											return super().prepare_seqaseq_batch(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							**__SCREAMING_SNAKE_CASE		)






					def 	_snake_case    (   self		):


											"""simple docstring"""





											return self.set_src_lang_special_tokens(self.src_lang		)






					def 	_snake_case    (   self		):


											"""simple docstring"""





											return self.set_tgt_lang_special_tokens(self.tgt_lang		)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Dict													=       self.lang_code_to_id[src_lang]
											lowercase_	:     Optional[Any]													=       []
											lowercase_	:     List[str]													=       [self.eos_token_id, self.cur_lang_code]






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     List[Any]													=       self.lang_code_to_id[lang]
											lowercase_	:     Dict													=       []
											lowercase_	:     Union[str, Any]													=       [self.eos_token_id, self.cur_lang_code]



