

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


_a							=							''''''


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




   class  _lowerCAmelCase  (     tr.AbstractTransform       ):







    """simple docstring"""







    def __init__(      self							:      int, UpperCAmelCase__							:      Union[str, Any] = " "     ):
       __lowercase								=						sentence_delimiter


    def  _lowercase			(      self							:      List[Any], UpperCAmelCase__							:      Optional[int]     ):
       return list(_SCREAMING_SNAKE_CASE     )



    def  _lowercase			(      self							:      Optional[Any], UpperCAmelCase__							:      List[Any]     ):
       __lowercase								=						[]
       for sent_idx, sentence in enumerate(_SCREAMING_SNAKE_CASE     ):
          chars.extend(self.process_string(_SCREAMING_SNAKE_CASE     )     )
          if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(_SCREAMING_SNAKE_CASE     ) - 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  _lowerCAmelCase  (     datasets.Metric       ):







 """simple docstring"""







 def  _lowercase			(      self							:      Tuple     ):
    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  _lowercase			(      self							:      List[str], UpperCAmelCase__							:      Union[str, Any], UpperCAmelCase__							:      Tuple, UpperCAmelCase__							:      Optional[int]=False     ):
    if concatenate_texts:
       return jiwer.compute_measures(
           _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE, truth_transform=_SCREAMING_SNAKE_CASE, hypothesis_transform=_SCREAMING_SNAKE_CASE, )["wer"]

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

    return incorrect / total







"""simple docstring"""





import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_funnel import FunnelTokenizer


_a							=							logging.get_logger(__name__)

_a							=							{'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}

_a							=							[
    'small',
    'small-base',
    'medium',
    'medium-base',
    'intermediate',
    'intermediate-base',
    'large',
    'large-base',
    'xlarge',
    'xlarge-base',
]

_a							=							{
    'vocab_file': {
        'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/vocab.txt',
        'funnel-transformer/small-base': 'https://huggingface.co/funnel-transformer/small-base/resolve/main/vocab.txt',
        'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/vocab.txt',
        'funnel-transformer/medium-base': (
            'https://huggingface.co/funnel-transformer/medium-base/resolve/main/vocab.txt'
        ),
        'funnel-transformer/intermediate': (
            'https://huggingface.co/funnel-transformer/intermediate/resolve/main/vocab.txt'
        ),
        'funnel-transformer/intermediate-base': (
            'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/vocab.txt'
        ),
        'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/vocab.txt',
        'funnel-transformer/large-base': 'https://huggingface.co/funnel-transformer/large-base/resolve/main/vocab.txt',
        'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/vocab.txt',
        'funnel-transformer/xlarge-base': (
            'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/vocab.txt'
        ),
    },
    'tokenizer_file': {
        'funnel-transformer/small': 'https://huggingface.co/funnel-transformer/small/resolve/main/tokenizer.json',
        'funnel-transformer/small-base': (
            'https://huggingface.co/funnel-transformer/small-base/resolve/main/tokenizer.json'
        ),
        'funnel-transformer/medium': 'https://huggingface.co/funnel-transformer/medium/resolve/main/tokenizer.json',
        'funnel-transformer/medium-base': (
            'https://huggingface.co/funnel-transformer/medium-base/resolve/main/tokenizer.json'
        ),
        'funnel-transformer/intermediate': (
            'https://huggingface.co/funnel-transformer/intermediate/resolve/main/tokenizer.json'
        ),
        'funnel-transformer/intermediate-base': (
            'https://huggingface.co/funnel-transformer/intermediate-base/resolve/main/tokenizer.json'
        ),
        'funnel-transformer/large': 'https://huggingface.co/funnel-transformer/large/resolve/main/tokenizer.json',
        'funnel-transformer/large-base': (
            'https://huggingface.co/funnel-transformer/large-base/resolve/main/tokenizer.json'
        ),
        'funnel-transformer/xlarge': 'https://huggingface.co/funnel-transformer/xlarge/resolve/main/tokenizer.json',
        'funnel-transformer/xlarge-base': (
            'https://huggingface.co/funnel-transformer/xlarge-base/resolve/main/tokenizer.json'
        ),
    },
}
_a							=							{F"funnel-transformer/{name}": 5_12 for name in _model_names}
_a							=							{F"funnel-transformer/{name}": {'do_lower_case': True} for name in _model_names}




class  _lowerCAmelCase  (     lowercase       ):







 """simple docstring"""







 __UpperCAmelCase     : Optional[Any]       		=     VOCAB_FILES_NAMES
 __UpperCAmelCase     : Tuple       		=     PRETRAINED_VOCAB_FILES_MAP
 __UpperCAmelCase     : Union[str, Any]       		=     PRETRAINED_INIT_CONFIGURATION
 __UpperCAmelCase     : Optional[Any]       		=     FunnelTokenizer
 __UpperCAmelCase     : List[str]       		=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 __UpperCAmelCase     : int       		=     2


 def __init__(      self							:      Dict, UpperCAmelCase__							:      Dict=None, UpperCAmelCase__							:      Optional[int]=None, UpperCAmelCase__							:      Dict=True, UpperCAmelCase__							:      List[str]="<unk>", UpperCAmelCase__							:      Optional[Any]="<sep>", UpperCAmelCase__							:      Optional[Any]="<pad>", UpperCAmelCase__							:      Union[str, Any]="<cls>", UpperCAmelCase__							:      str="<mask>", UpperCAmelCase__							:      Optional[Any]="<s>", UpperCAmelCase__							:      Tuple="</s>", UpperCAmelCase__							:      Union[str, Any]=True, UpperCAmelCase__							:      Optional[int]=True, UpperCAmelCase__							:      Optional[Any]=None, UpperCAmelCase__							:      Dict="##", **UpperCAmelCase__							:      List[str], ):
    super().__init__(
        UpperCAmelCase__, tokenizer_file=UpperCAmelCase__, do_lower_case=UpperCAmelCase__, unk_token=UpperCAmelCase__, sep_token=UpperCAmelCase__, pad_token=UpperCAmelCase__, cls_token=UpperCAmelCase__, mask_token=UpperCAmelCase__, bos_token=UpperCAmelCase__, eos_token=UpperCAmelCase__, clean_text=UpperCAmelCase__, tokenize_chinese_chars=UpperCAmelCase__, strip_accents=UpperCAmelCase__, wordpieces_prefix=UpperCAmelCase__, **UpperCAmelCase__, )

    __lowercase								=						json.loads(self.backend_tokenizer.normalizer.__getstate__()     )
    if (
        normalizer_state.get("lowercase", UpperCAmelCase__     ) != do_lower_case
        or normalizer_state.get("strip_accents", UpperCAmelCase__     ) != strip_accents
        or normalizer_state.get("handle_chinese_chars", UpperCAmelCase__     ) != tokenize_chinese_chars
    ):
       __lowercase								=						getattr(UpperCAmelCase__, normalizer_state.pop("type"     )     )
       __lowercase								=						do_lower_case
       __lowercase								=						strip_accents
       __lowercase								=						tokenize_chinese_chars
       __lowercase								=						normalizer_class(**UpperCAmelCase__     )

    __lowercase								=						do_lower_case


 def  _lowercase			(      self							:      Tuple, UpperCAmelCase__							:      Any, UpperCAmelCase__							:      Any=None     ):
    __lowercase								=						[self.cls_token_id] + token_ids_a + [self.sep_token_id]

    if token_ids_a:
       output += token_ids_a + [self.sep_token_id]

    return output


 def  _lowercase			(      self							:      str, UpperCAmelCase__							:      List[int], UpperCAmelCase__							:      Optional[List[int]] = None     ):
    __lowercase								=						[self.sep_token_id]
    __lowercase								=						[self.cls_token_id]
    if token_ids_a is None:
       return len(cls     ) * [self.cls_token_type_id] + len(token_ids_a + sep     ) * [0]
    return len(cls     ) * [self.cls_token_type_id] + len(token_ids_a + sep     ) * [0] + len(token_ids_a + sep     ) * [1]



 def  _lowercase			(      self							:      Optional[Any], UpperCAmelCase__							:      str, UpperCAmelCase__							:      Optional[str] = None     ):
    __lowercase								=						self._tokenizer.model.save(UpperCAmelCase__, name=UpperCAmelCase__     )
    return tuple(UpperCAmelCase__     )




