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


__lowercase										= ''''''


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


    class      lowerCamelCase_					(       tr.AbstractTransform			):






        '''simple docstring'''






        def __init__(     self			,			__lowercase = " ")	->     Optional[Any]:
            __UpperCamelCase					:Dict        =		sentence_delimiter







        def       UpperCamelCase__       (     self			,			__lowercase)	->     str:
            return list(__lowercase)







        def       UpperCamelCase__       (     self			,			__lowercase)	->     Any:
            __UpperCamelCase					:Union[str, Any]        =		[]
            for sent_idx, sentence in enumerate(__lowercase):
                chars.extend(self.process_string(__lowercase))
                if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(__lowercase) - 1:
                    chars.append(self.sentence_delimiter)
            return chars
    __lowercase										= tr.Compose(
        [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
    )
else:
    __lowercase										= tr.Compose(
        [
            tr.RemoveMultipleSpaces(),
            tr.Strip(),
            tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
            tr.ReduceToListOfListOfChars(),
        ]
    )


__lowercase										= '''\
@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.}
}
'''

__lowercase										= '''\
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.
'''

__lowercase										= '''
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       UpperCamelCase__       (     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       UpperCamelCase__       (     self			,			__lowercase			,			__lowercase			,			__lowercase=False)	->     Optional[Any]:
        if concatenate_texts:
            return jiwer.compute_measures(
                __lowercase			,			__lowercase			,			truth_transform=__lowercase			,			hypothesis_transform=__lowercase			,			)["wer"]

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

        return incorrect / total






from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


__lowercase										= logging.get_logger(__name__)

__lowercase										= {
    '''EleutherAI/gpt-j-6B''': '''https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json''',
    # See all GPT-J models at https://huggingface.co/models?filter=gpt_j
}


class      lowerCamelCase_					(       UpperCAmelCase_			):






    '''simple docstring'''






    a__     :						Optional[Any]      =				"""gptj"""
    a__     :						Tuple      =				{
        """max_position_embeddings""": """n_positions""",
        """hidden_size""": """n_embd""",
        """num_attention_heads""": """n_head""",
        """num_hidden_layers""": """n_layer""",
    }







    def __init__(     self			,			__lowercase=50_400			,			__lowercase=2_048			,			__lowercase=4_096			,			__lowercase=28			,			__lowercase=16			,			__lowercase=64			,			__lowercase=None			,			__lowercase="gelu_new"			,			__lowercase=0.0			,			__lowercase=0.0			,			__lowercase=0.0			,			__lowercase=1E-5			,			__lowercase=0.02			,			__lowercase=True			,			__lowercase=50_256			,			__lowercase=50_256			,			__lowercase=False			,			**__lowercase			,			)	->     Tuple:
        __UpperCamelCase					:Any        =		vocab_size
        __UpperCamelCase					:Optional[int]        =		n_positions
        __UpperCamelCase					:Tuple        =		n_embd
        __UpperCamelCase					:int        =		n_layer
        __UpperCamelCase					:Any        =		n_head
        __UpperCamelCase					:Any        =		n_inner
        __UpperCamelCase					:Dict        =		rotary_dim
        __UpperCamelCase					:Tuple        =		activation_function
        __UpperCamelCase					:Optional[Any]        =		resid_pdrop
        __UpperCamelCase					:Any        =		embd_pdrop
        __UpperCamelCase					:List[str]        =		attn_pdrop
        __UpperCamelCase					:str        =		layer_norm_epsilon
        __UpperCamelCase					:List[Any]        =		initializer_range
        __UpperCamelCase					:Dict        =		use_cache

        __UpperCamelCase					:List[Any]        =		bos_token_id
        __UpperCamelCase					:Tuple        =		eos_token_id

        super().__init__(
            bos_token_id=__lowercase			,			eos_token_id=__lowercase			,			tie_word_embeddings=__lowercase			,			**__lowercase)


class      lowerCamelCase_					(       UpperCAmelCase_			):






    '''simple docstring'''






    def __init__(     self			,			__lowercase			,			__lowercase = "default"			,			__lowercase = None			,			__lowercase = False			,			)	->     Any:
        super().__init__(__lowercase			,			task=__lowercase			,			patching_specs=__lowercase			,			use_past=__lowercase)
        if not getattr(self._config			,			'''pad_token_id'''			,			__lowercase):
            # TODO: how to do that better?
            __UpperCamelCase					:Tuple        =		0







    @property
    def       UpperCamelCase__       (     self)	->     Mapping[str, Mapping[int, str]]:
        __UpperCamelCase					:Tuple        =		OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}})
        if self.use_past:
            self.fill_with_past_key_values_(__lowercase			,			direction='''inputs''')
            __UpperCamelCase					:str        =		{0: '''batch''', 1: '''past_sequence + sequence'''}
        else:
            __UpperCamelCase					:Any        =		{0: '''batch''', 1: '''sequence'''}

        return common_inputs







    @property
    def       UpperCamelCase__       (     self)	->     int:
        return self._config.n_layer







    @property
    def       UpperCamelCase__       (     self)	->     int:
        return self._config.n_head







    def       UpperCamelCase__       (     self			,			__lowercase			,			__lowercase = -1			,			__lowercase = -1			,			__lowercase = False			,			__lowercase = None			,			)	->     Mapping[str, Any]:
        __UpperCamelCase					:Optional[int]        =		super(__lowercase			,			self).generate_dummy_inputs(
            __lowercase			,			batch_size=__lowercase			,			seq_length=__lowercase			,			is_pair=__lowercase			,			framework=__lowercase)

        # We need to order the input in the way they appears in the forward()
        __UpperCamelCase					:int        =		OrderedDict({'''input_ids''': common_inputs['''input_ids''']})

        # Need to add the past_keys
        if self.use_past:
            if not is_torch_available():
                raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''')
            else:
                import torch

                __UpperCamelCase  ,	__UpperCamelCase					:str        =		common_inputs['''input_ids'''].shape
                # Not using the same length for past_key_values
                __UpperCamelCase					:List[str]        =		seqlen + 2
                __UpperCamelCase					:Union[str, Any]        =		(
                    batch,
                    self.num_attention_heads,
                    past_key_values_length,
                    self._config.hidden_size // self.num_attention_heads,
                )
                __UpperCamelCase					:Tuple        =		[
                    (torch.zeros(__lowercase), torch.zeros(__lowercase)) for _ in range(self.num_layers)
                ]

        __UpperCamelCase					:Tuple        =		common_inputs['''attention_mask''']
        if self.use_past:
            __UpperCamelCase					:Tuple        =		ordered_inputs['''attention_mask'''].dtype
            __UpperCamelCase					:Optional[Any]        =		torch.cat(
                [ordered_inputs['''attention_mask'''], torch.ones(__lowercase			,			__lowercase			,			dtype=__lowercase)]			,			dim=1)

        return ordered_inputs







    @property
    def       UpperCamelCase__       (     self)	->     int:
        return 13





