



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   ):




  def __init__(						self	,				__UpperCAmelCase = " "				):



     '''simple docstring'''
     __lowerCamelCase													=    sentence_delimiter




  def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



     '''simple docstring'''
     return list(__UpperCAmelCase				)




  def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



     '''simple docstring'''
     __lowerCamelCase													=    []
     for sent_idx, sentence in enumerate(__UpperCAmelCase				):
        chars.extend(self.process_string(__UpperCAmelCase				)				)
        if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__UpperCAmelCase				) - 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   ):




 def        lowerCamelCase      (						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''',
            '''https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates''',
        ]	,				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase=False				):



    '''simple docstring'''
    if concatenate_texts:
       return jiwer.compute_measures(
           __UpperCAmelCase	,				__UpperCAmelCase	,				truth_transform=__UpperCAmelCase	,				hypothesis_transform=__UpperCAmelCase	,				)["wer"]

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

    return incorrect / total











from __future__ import annotations

import unittest

from transformers import FunnelConfig, is_tf_available
from transformers.testing_utils import require_tf

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import (
      TFFunnelBaseModel,
      TFFunnelForMaskedLM,
      TFFunnelForMultipleChoice,
      TFFunnelForPreTraining,
      TFFunnelForQuestionAnswering,
      TFFunnelForSequenceClassification,
      TFFunnelForTokenClassification,
      TFFunnelModel,
  )



class  __lowerCAmelCase     :




 def __init__(						self	,				__UpperCAmelCase	,				__UpperCAmelCase=13	,				__UpperCAmelCase=7	,				__UpperCAmelCase=True	,				__UpperCAmelCase=True	,				__UpperCAmelCase=True	,				__UpperCAmelCase=True	,				__UpperCAmelCase=99	,				__UpperCAmelCase=[1, 1, 2]	,				__UpperCAmelCase=1	,				__UpperCAmelCase=32	,				__UpperCAmelCase=4	,				__UpperCAmelCase=8	,				__UpperCAmelCase=37	,				__UpperCAmelCase="gelu_new"	,				__UpperCAmelCase=0.1	,				__UpperCAmelCase=0.1	,				__UpperCAmelCase=0.0	,				__UpperCAmelCase=512	,				__UpperCAmelCase=3	,				__UpperCAmelCase=0.02	,				__UpperCAmelCase=3	,				__UpperCAmelCase=4	,				__UpperCAmelCase=None	,				__UpperCAmelCase=False	,				):



    '''simple docstring'''
    __lowerCamelCase													=    parent
    __lowerCamelCase													=    batch_size
    __lowerCamelCase													=    seq_length
    __lowerCamelCase													=    is_training
    __lowerCamelCase													=    use_input_mask
    __lowerCamelCase													=    use_token_type_ids
    __lowerCamelCase													=    use_labels
    __lowerCamelCase													=    vocab_size
    __lowerCamelCase													=    block_sizes
    __lowerCamelCase													=    num_decoder_layers
    __lowerCamelCase													=    d_model
    __lowerCamelCase													=    n_head
    __lowerCamelCase													=    d_head
    __lowerCamelCase													=    d_inner
    __lowerCamelCase													=    hidden_act
    __lowerCamelCase													=    hidden_dropout
    __lowerCamelCase													=    attention_dropout
    __lowerCamelCase													=    activation_dropout
    __lowerCamelCase													=    max_position_embeddings
    __lowerCamelCase													=    type_vocab_size
    __lowerCamelCase													=    2
    __lowerCamelCase													=    num_labels
    __lowerCamelCase													=    num_choices
    __lowerCamelCase													=    scope
    __lowerCamelCase													=    initializer_std

    # Used in the tests to check the size of the first attention layer
    __lowerCamelCase													=    n_head
    # Used in the tests to check the size of the first hidden state
    __lowerCamelCase													=    self.d_model
    # Used in the tests to check the number of output hidden states/attentions
    __lowerCamelCase													=    sum(self.block_sizes				) + (0 if base else self.num_decoder_layers)
    # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
    # the last hidden state of the first block (which is the first hidden state of the decoder).
    if not base:
       __lowerCamelCase													=    self.num_hidden_layers + 2




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    ids_tensor([self.batch_size, self.seq_length]	,				self.vocab_size				)

    __lowerCamelCase													=    None
    if self.use_input_mask:
       __lowerCamelCase													=    random_attention_mask([self.batch_size, self.seq_length]				)

    __lowerCamelCase													=    None
    if self.use_token_type_ids:
       __lowerCamelCase													=    ids_tensor([self.batch_size, self.seq_length]	,				self.type_vocab_size				)

    __lowerCamelCase													=    None
    __lowerCamelCase													=    None
    __lowerCamelCase													=    None
    if self.use_labels:
       __lowerCamelCase													=    ids_tensor([self.batch_size]	,				self.type_sequence_label_size				)
       __lowerCamelCase													=    ids_tensor([self.batch_size, self.seq_length]	,				self.num_labels				)
       __lowerCamelCase													=    ids_tensor([self.batch_size]	,				self.num_choices				)

    __lowerCamelCase													=    FunnelConfig(
        vocab_size=self.vocab_size	,				block_sizes=self.block_sizes	,				num_decoder_layers=self.num_decoder_layers	,				d_model=self.d_model	,				n_head=self.n_head	,				d_head=self.d_head	,				d_inner=self.d_inner	,				hidden_act=self.hidden_act	,				hidden_dropout=self.hidden_dropout	,				attention_dropout=self.attention_dropout	,				activation_dropout=self.activation_dropout	,				max_position_embeddings=self.max_position_embeddings	,				type_vocab_size=self.type_vocab_size	,				initializer_std=self.initializer_std	,				)

    return (
        config,
        input_ids,
        token_type_ids,
        input_mask,
        sequence_labels,
        token_labels,
        choice_labels,
    )




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelModel(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)

    __lowerCamelCase													=    [input_ids, input_mask]
    __lowerCamelCase													=    model(__UpperCAmelCase				)

    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.last_hidden_state.shape	,				(self.batch_size, self.seq_length, self.d_model)				)

    __lowerCamelCase													=    False
    __lowerCamelCase													=    TFFunnelModel(config=__UpperCAmelCase				)
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.last_hidden_state.shape	,				(self.batch_size, self.seq_length, self.d_model)				)

    __lowerCamelCase													=    False
    __lowerCamelCase													=    TFFunnelModel(config=__UpperCAmelCase				)
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.last_hidden_state.shape	,				(self.batch_size, self.seq_length, self.d_model)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelBaseModel(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)

    __lowerCamelCase													=    [input_ids, input_mask]
    __lowerCamelCase													=    model(__UpperCAmelCase				)

    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.last_hidden_state.shape	,				(self.batch_size, 2, self.d_model)				)

    __lowerCamelCase													=    False
    __lowerCamelCase													=    TFFunnelBaseModel(config=__UpperCAmelCase				)
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.last_hidden_state.shape	,				(self.batch_size, 3, self.d_model)				)

    __lowerCamelCase													=    False
    __lowerCamelCase													=    TFFunnelBaseModel(config=__UpperCAmelCase				)
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.last_hidden_state.shape	,				(self.batch_size, 2, self.d_model)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelForPreTraining(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.seq_length)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelForMaskedLM(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.seq_length, self.vocab_size)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    self.num_labels
    __lowerCamelCase													=    TFFunnelForSequenceClassification(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.num_labels)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    self.num_choices
    __lowerCamelCase													=    TFFunnelForMultipleChoice(config=__UpperCAmelCase				)
    __lowerCamelCase													=    tf.tile(tf.expand_dims(__UpperCAmelCase	,				1				)	,				(1, self.num_choices, 1)				)
    __lowerCamelCase													=    tf.tile(tf.expand_dims(__UpperCAmelCase	,				1				)	,				(1, self.num_choices, 1)				)
    __lowerCamelCase													=    tf.tile(tf.expand_dims(__UpperCAmelCase	,				1				)	,				(1, self.num_choices, 1)				)
    __lowerCamelCase													=    {
        '''input_ids''': multiple_choice_inputs_ids,
        '''attention_mask''': multiple_choice_input_mask,
        '''token_type_ids''': multiple_choice_token_type_ids,
    }
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.num_choices)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    self.num_labels
    __lowerCamelCase													=    TFFunnelForTokenClassification(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.seq_length, self.num_labels)				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase	,				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelForQuestionAnswering(config=__UpperCAmelCase				)
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
    __lowerCamelCase													=    model(__UpperCAmelCase				)
    self.parent.assertEqual(result.start_logits.shape	,				(self.batch_size, self.seq_length)				)
    self.parent.assertEqual(result.end_logits.shape	,				(self.batch_size, self.seq_length)				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.prepare_config_and_inputs()
    (
        (
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,(
        __lowerCamelCase
    )							,
    )													=    config_and_inputs
    __lowerCamelCase													=    {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
    return config, inputs_dict



@require_tf
class  __lowerCAmelCase     (	lowerCAmelCase__  ,	lowerCAmelCase__  ,	unittest.TestCase   ):
 lowerCAmelCase__       					=  (
     (
         TFFunnelModel,
         TFFunnelForMaskedLM,
         TFFunnelForPreTraining,
         TFFunnelForQuestionAnswering,
         TFFunnelForTokenClassification,
     )
     if is_tf_available()
     else ()
 )
 lowerCAmelCase__       					=  (
     {
         """feature-extraction""": (TFFunnelBaseModel, TFFunnelModel),
         """fill-mask""": TFFunnelForMaskedLM,
         """question-answering""": TFFunnelForQuestionAnswering,
         """text-classification""": TFFunnelForSequenceClassification,
         """token-classification""": TFFunnelForTokenClassification,
         """zero-shot""": TFFunnelForSequenceClassification,
     }
     if is_tf_available()
     else {}
 )
 lowerCAmelCase__       					=  False
 lowerCAmelCase__       					=  False




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelModelTester(self				)
    __lowerCamelCase													=    ConfigTester(self	,				config_class=__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    self.config_tester.run_common_tests()




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_pretraining(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_masked_lm(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_question_answering(*__UpperCAmelCase				)



@require_tf
class  __lowerCAmelCase     (	lowerCAmelCase__  ,	unittest.TestCase   ):
 lowerCAmelCase__       					=  (
     (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
 )
 lowerCAmelCase__       					=  False
 lowerCAmelCase__       					=  False




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    TFFunnelModelTester(self	,				base=__UpperCAmelCase				)
    __lowerCamelCase													=    ConfigTester(self	,				config_class=__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    self.config_tester.run_common_tests()




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_base_model(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_sequence_classification(*__UpperCAmelCase				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_multiple_choice(*__UpperCAmelCase				)






