

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


lowerCamelCase           =					''''''


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







       class 						__magic_name__			(							tr.AbstractTransform							):

          '''simple docstring'''




          def __init__(				self,    lowercase_ = " "       )							->    str:






            """simple docstring"""






            a__  =sentence_delimiter



          def  _UpperCAmelCase (				self,    lowercase_       )							->    List[Any]:






            """simple docstring"""






            return list(SCREAMING_SNAKE_CASE__       )



          def  _UpperCAmelCase (				self,    lowercase_       )							->    Union[str, Any]:






            """simple docstring"""






            a__  =[]
            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





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


lowerCamelCase           =					'''\\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'''

lowerCamelCase           =					'''\\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'''

lowerCamelCase           =					'''\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 						__magic_name__			(							datasets.Metric							):

   '''simple docstring'''




   def  _UpperCAmelCase (				self       )							->    str:






     """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  _UpperCAmelCase (				self,    lowercase_,    lowercase_,    lowercase_=False       )							->    int:






     """simple docstring"""






     if concatenate_texts:
       return jiwer.compute_measures(
           SCREAMING_SNAKE_CASE__,    SCREAMING_SNAKE_CASE__,    truth_transform=SCREAMING_SNAKE_CASE__,    hypothesis_transform=SCREAMING_SNAKE_CASE__,    )["wer"]

     a__  =0
     a__  =0
     for prediction, reference in zip(SCREAMING_SNAKE_CASE__,    SCREAMING_SNAKE_CASE__       ):
       a__  =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"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase_								=		logging.get_logger(__name__)

lowerCamelCase_								=		{}






class 					_SCREAMING_SNAKE_CASE(   A  ):
       SCREAMING_SNAKE_CASE_   :      List[Any]							=  '''llama'''
       SCREAMING_SNAKE_CASE_   :      Optional[int]							=  ['''past_key_values''']




       def __init__(						self		,SCREAMING_SNAKE_CASE__=3_20_00		,SCREAMING_SNAKE_CASE__=40_96		,SCREAMING_SNAKE_CASE__=1_10_08		,SCREAMING_SNAKE_CASE__=32		,SCREAMING_SNAKE_CASE__=32		,SCREAMING_SNAKE_CASE__=None		,SCREAMING_SNAKE_CASE__="silu"		,SCREAMING_SNAKE_CASE__=20_48		,SCREAMING_SNAKE_CASE__=0.0_2		,SCREAMING_SNAKE_CASE__=1E-6		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=0		,SCREAMING_SNAKE_CASE__=1		,SCREAMING_SNAKE_CASE__=2		,SCREAMING_SNAKE_CASE__=1		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__=None		,**SCREAMING_SNAKE_CASE__		,)			->      Union[str, Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  vocab_size
             __SCREAMING_SNAKE_CASE   :int						=  max_position_embeddings
             __SCREAMING_SNAKE_CASE   :List[str]						=  hidden_size
             __SCREAMING_SNAKE_CASE   :Tuple						=  intermediate_size
             __SCREAMING_SNAKE_CASE   :List[str]						=  num_hidden_layers
             __SCREAMING_SNAKE_CASE   :List[Any]						=  num_attention_heads

             # for backward compatibility
             if num_key_value_heads is None:
                   __SCREAMING_SNAKE_CASE   :Optional[int]						=  num_attention_heads

             __SCREAMING_SNAKE_CASE   :str						=  num_key_value_heads
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  hidden_act
             __SCREAMING_SNAKE_CASE   :List[str]						=  initializer_range
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  rms_norm_eps
             __SCREAMING_SNAKE_CASE   :Dict						=  pretraining_tp
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  use_cache
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  rope_scaling
             self._rope_scaling_validation()

             super().__init__(
                 pad_token_id=SCREAMING_SNAKE_CASE__		,bos_token_id=SCREAMING_SNAKE_CASE__		,eos_token_id=SCREAMING_SNAKE_CASE__		,tie_word_embeddings=SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__		,)




       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             if self.rope_scaling is None:
                   return

             if not isinstance(self.rope_scaling		,SCREAMING_SNAKE_CASE__							) or len(self.rope_scaling							) != 2:
                   raise ValueError(
                       '''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '''
                       f'''got {self.rope_scaling}'''							)
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  self.rope_scaling.get('''type'''		,SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  self.rope_scaling.get('''factor'''		,SCREAMING_SNAKE_CASE__							)
             if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
                   raise ValueError(
                       f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}'''							)
             if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							) or rope_scaling_factor <= 1.0:
                   raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}'''							)