




from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_		:					Dict          =  logging.get_logger(__name__)

UpperCAmelCase_		:					Tuple          =  {
    '''alibaba-damo/mgp-str-base''': '''https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json''',
}




class 		__A   (      snake_case_      ):
						UpperCamelCase      =       '''mgp-str'''

						def __init__(		self :Any     ,			__snake_case :Tuple=[32, 1_28]     ,			__snake_case :List[Any]=4     ,			__snake_case :int=3     ,			__snake_case :int=27     ,			__snake_case :Union[str, Any]=38     ,			__snake_case :Dict=5_02_57     ,			__snake_case :Optional[Any]=3_05_22     ,			__snake_case :Optional[Any]=7_68     ,			__snake_case :Optional[int]=12     ,			__snake_case :int=12     ,			__snake_case :List[Any]=4.0     ,			__snake_case :Dict=True     ,			__snake_case :str=False     ,			__snake_case :List[str]=1E-5     ,			__snake_case :str=0.0     ,			__snake_case :Any=0.0     ,			__snake_case :List[str]=0.0     ,			__snake_case :Any=False     ,			__snake_case :List[str]=0.02     ,			**__snake_case :Dict     ,			):
										'''simple docstring'''

										super().__init__(**__snake_case			)

										__magic_name__						:						str										=image_size
										__magic_name__						:						Dict										=patch_size
										__magic_name__						:						List[str]										=num_channels
										__magic_name__						:						Tuple										=max_token_length
										__magic_name__						:						List[Any]										=num_character_labels
										__magic_name__						:						int										=num_bpe_labels
										__magic_name__						:						Any										=num_wordpiece_labels
										__magic_name__						:						List[str]										=hidden_size
										__magic_name__						:						Any										=num_hidden_layers
										__magic_name__						:						Any										=num_attention_heads
										__magic_name__						:						List[str]										=mlp_ratio
										__magic_name__						:						Any										=distilled
										__magic_name__						:						Tuple										=layer_norm_eps
										__magic_name__						:						str										=drop_rate
										__magic_name__						:						Tuple										=qkv_bias
										__magic_name__						:						Union[str, Any]										=attn_drop_rate
										__magic_name__						:						str										=drop_path_rate
										__magic_name__						:						List[str]										=output_aa_attentions
										__magic_name__						:						Tuple										=initializer_range











'''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__							:  Dict    =''''''


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




      class 					UpperCAmelCase	(     tr.AbstractTransform  ):




            def __init__(     self     :					Any     ,     __snake_case     :					str = " "    )							-> Any:
                  _lowerCAmelCase					=				sentence_delimiter




            def 							lowercase__       (     self     :					str     ,     __snake_case     :					str    )							-> Optional[int]:
                  return list(__snake_case    )




            def 							lowercase__       (     self     :					Tuple     ,     __snake_case     :					List[str]    )							-> Union[str, Any]:
                  _lowerCAmelCase					=				[]
                  for sent_idx, sentence in enumerate(__snake_case    ):
                        chars.extend(self.process_string(__snake_case    )    )
                        if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__snake_case    ) - 1:
                              chars.append(self.sentence_delimiter    )
                  return chars




      A__							:  Optional[Any]    =tr.Compose(
          [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
      )
else:
      A__							:  Tuple    =tr.Compose(
          [
              tr.RemoveMultipleSpaces(),
              tr.Strip(),
              tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
              tr.ReduceToListOfListOfChars(),
          ]
      )


A__							:  List[str]    ='''\
@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__							:  Optional[int]    ='''\
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__							:  List[str]    ='''
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 					UpperCAmelCase	(     datasets.Metric  ):




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

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

            return incorrect / total






