






'''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


UpperCamelCase							=logging.get_logger(__name__)

UpperCamelCase							="▁"

UpperCamelCase							={"vocab_file": "sentencepiece.bpe.model"}

UpperCamelCase							={
    "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"
        ),
    }
}

UpperCamelCase							={
    "facebook/mbart-large-en-ro": 1024,
    "facebook/mbart-large-cc25": 1024,
}

# fmt: off
UpperCamelCase							=["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     A    (      SCREAMING_SNAKE_CASE__						):






 """simple docstring"""





 __a			:						int      =						VOCAB_FILES_NAMES
 __a			:						List[str]      =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __a			:						Optional[Any]      =						PRETRAINED_VOCAB_FILES_MAP
 __a			:						Dict      =						['''input_ids''', '''attention_mask''']

 __a			:						List[int]      =						[]
 __a			:						List[int]      =						[]
 def __init__(							self			,     __lowerCAmelCase			,     __lowerCAmelCase="<s>"			,     __lowerCAmelCase="</s>"			,     __lowerCAmelCase="</s>"			,     __lowerCAmelCase="<s>"			,     __lowerCAmelCase="<unk>"			,     __lowerCAmelCase="<pad>"			,     __lowerCAmelCase="<mask>"			,     __lowerCAmelCase=None			,     __lowerCAmelCase=None			,     __lowerCAmelCase=None			,     __lowerCAmelCase = None			,     __lowerCAmelCase=None			,     **__lowerCAmelCase			,     ):
       # Mask token behave like a normal word, i.e. include the space before it
       UpperCamelCase_				:   Union[str, Any]					    =							AddedToken(__lowerCAmelCase			,     lstrip=__lowerCAmelCase			,     rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase			,     __lowerCAmelCase ) else mask_token

       UpperCamelCase_				:   Optional[int]					    =							{} if sp_model_kwargs is None else sp_model_kwargs

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

       UpperCamelCase_				:   Tuple					    =							spm.SentencePieceProcessor(**self.sp_model_kwargs )
       self.sp_model.Load(str(__lowerCAmelCase ) )
       UpperCamelCase_				:   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
       UpperCamelCase_				:   Any					    =							{"""<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
       UpperCamelCase_				:   Optional[int]					    =							1

       UpperCamelCase_				:   Tuple					    =							len(self.sp_model )
       UpperCamelCase_				:   int					    =							{
           code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__lowerCAmelCase )
       }
       UpperCamelCase_				:   List[str]					    =							{v: k for k, v in self.lang_code_to_id.items()}
       UpperCamelCase_				:   Union[str, 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 )
       UpperCamelCase_				:   int					    =							{v: k for k, v in self.fairseq_tokens_to_ids.items()}
       UpperCamelCase_				:   int					    =							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] )

       UpperCamelCase_				:   Union[str, Any]					    =							src_lang if src_lang is not None else """en_XX"""
       UpperCamelCase_				:   List[str]					    =							self.lang_code_to_id[self._src_lang]
       UpperCamelCase_				:   List[Any]					    =							tgt_lang
       self.set_src_lang_special_tokens(self._src_lang )
 def __getstate__(							self ):
       UpperCamelCase_				:   Optional[Any]					    =							self.__dict__.copy()
       UpperCamelCase_				:   Dict					    =							None
       UpperCamelCase_				:   List[Any]					    =							self.sp_model.serialized_model_proto()
       return state
 def __setstate__(							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   int					    =							d

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

       UpperCamelCase_				:   Any					    =							spm.SentencePieceProcessor(**self.sp_model_kwargs )
       self.sp_model.LoadFromSerializedProto(self.sp_model_proto )
 @property
 def   _UpperCAmelCase       (							self ):
       return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1  # Plus 1 for the mask token
 @property
 def   _UpperCAmelCase       (							self ):
       return self._src_lang
 @src_lang.setter
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   List[str]					    =							new_src_lang
       self.set_src_lang_special_tokens(self._src_lang )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase = None			,     __lowerCAmelCase = False ):

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

       UpperCamelCase_				:   List[Any]					    =							[1] * len(self.prefix_tokens )
       UpperCamelCase_				:   List[str]					    =							[1] * len(self.suffix_tokens )
       if token_ids_a is None:
             return prefix_ones + ([0] * len(__lowerCAmelCase )) + suffix_ones
       return prefix_ones + ([0] * len(__lowerCAmelCase )) + ([0] * len(__lowerCAmelCase )) + suffix_ones
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase = None ):
       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   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase = None ):
       UpperCamelCase_				:   Optional[int]					    =							[self.sep_token_id]
       UpperCamelCase_				:   str					    =							[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   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     **__lowerCAmelCase ):
       if src_lang is None or tgt_lang is None:
             raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" )
       UpperCamelCase_				:   Tuple					    =							src_lang
       UpperCamelCase_				:   List[str]					    =							self(__lowerCAmelCase			,     add_special_tokens=__lowerCAmelCase			,     return_tensors=__lowerCAmelCase			,     **__lowerCAmelCase )
       UpperCamelCase_				:   Union[str, Any]					    =							self.convert_tokens_to_ids(__lowerCAmelCase )
       UpperCamelCase_				:   Dict					    =							tgt_lang_id
       return inputs
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Tuple					    =							{self.convert_ids_to_tokens(__lowerCAmelCase ): i for i in range(self.vocab_size )}
       vocab.update(self.added_tokens_encoder )
       return vocab
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       return self.sp_model.encode(__lowerCAmelCase			,     out_type=__lowerCAmelCase )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       if token in self.fairseq_tokens_to_ids:
             return self.fairseq_tokens_to_ids[token]
       UpperCamelCase_				:   Optional[Any]					    =							self.sp_model.PieceToId(__lowerCAmelCase )

       # 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   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       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   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   Optional[Any]					    =							"""""".join(__lowerCAmelCase ).replace(__lowerCAmelCase			,     """ """ ).strip()
       return out_string
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase = None ):
       if not os.path.isdir(__lowerCAmelCase ):
             logger.error(F"Vocabulary path ({save_directory}) should be a directory" )
             return
       UpperCamelCase_				:   List[str]					    =							os.path.join(
           __lowerCAmelCase			,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )

       if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCAmelCase ) and os.path.isfile(self.vocab_file ):
             copyfile(self.vocab_file			,     __lowerCAmelCase )
       elif not os.path.isfile(self.vocab_file ):
             with open(__lowerCAmelCase			,     """wb""" ) as fi:
                   UpperCamelCase_				:   Dict					    =							self.sp_model.serialized_model_proto()
                   fi.write(__lowerCAmelCase )

       return (out_vocab_file,)
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase = "en_XX"			,     __lowerCAmelCase = None			,     __lowerCAmelCase = "ro_RO"			,     **__lowerCAmelCase			,     ):
       UpperCamelCase_				:   Union[str, Any]					    =							src_lang
       UpperCamelCase_				:   List[Any]					    =							tgt_lang
       return super().prepare_seqaseq_batch(__lowerCAmelCase			,     __lowerCAmelCase			,     **__lowerCAmelCase )
 def   _UpperCAmelCase       (							self ):
       return self.set_src_lang_special_tokens(self.src_lang )
 def   _UpperCAmelCase       (							self ):
       return self.set_tgt_lang_special_tokens(self.tgt_lang )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   Any					    =							self.lang_code_to_id[src_lang]
       UpperCamelCase_				:   str					    =							[]
       UpperCamelCase_				:   Tuple					    =							[self.eos_token_id, self.cur_lang_code]





 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   str					    =							self.lang_code_to_id[lang]
       UpperCamelCase_				:   Any					    =							[]
       UpperCamelCase_				:   List[Any]					    =							[self.eos_token_id, self.cur_lang_code]














'''simple docstring'''

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


UpperCamelCase							=""


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




      class     A    (      tr.AbstractTransform						):






       """simple docstring"""





       def __init__(							self			,     __lowerCAmelCase = " " ):
             UpperCamelCase_				:   str					    =							sentence_delimiter
       def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
             return list(__lowerCAmelCase )





       def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
             UpperCamelCase_				:   List[Any]					    =							[]
             for sent_idx, sentence in enumerate(__lowerCAmelCase ):
                   chars.extend(self.process_string(__lowerCAmelCase ) )
                   if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__lowerCAmelCase ) - 1:
                         chars.append(self.sentence_delimiter )
             return chars






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


UpperCamelCase							="\\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"

UpperCamelCase							="\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (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 characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER'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\nperformance of the ASR system with a CER of 0 being a perfect score.\n"

UpperCamelCase							="\nComputes CER score of transcribed segments against references.\nArgs:\n    references: list of references for each speech input.\n    predictions: list of transcribtions to score.\n    concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n    (float): the character 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    >>> cer = datasets.load_metric(\"cer\")\n    >>> cer_score = cer.compute(predictions=predictions, references=references)\n    >>> print(cer_score)\n    0.34146341463414637\n"




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






 """simple docstring"""





 def   _UpperCAmelCase       (							self ):
       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   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase=False ):
       if concatenate_texts:
             return jiwer.compute_measures(
                 __lowerCAmelCase			,     __lowerCAmelCase			,     truth_transform=__lowerCAmelCase			,     hypothesis_transform=__lowerCAmelCase			,     )["wer"]

       UpperCamelCase_				:   Optional[Any]					    =							0
       UpperCamelCase_				:   str					    =							0
       for prediction, reference in zip(__lowerCAmelCase			,     __lowerCAmelCase ):
             UpperCamelCase_				:   Optional[int]					    =							jiwer.compute_measures(
                 __lowerCAmelCase			,     __lowerCAmelCase			,     truth_transform=__lowerCAmelCase			,     hypothesis_transform=__lowerCAmelCase			,     )
             incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
             total += measures["substitutions"] + measures["deletions"] + measures["hits"]

       return incorrect / total






