






import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
					from apex import amp

if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'):
					lowerCAmelCase_     =			True
					from torch.cuda.amp import autocast


lowerCAmelCase_     =			logging.getLogger(__name__)
@dataclass
class   UpperCamelCase			:







		"""simple docstring"""



		snake_case			 = field(
		    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}			)
		snake_case			 = field(
		    default=snake_case__      ,							metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}      ,							)
		snake_case			 = field(
		    default=snake_case__      ,							metadata={"help": "Whether to freeze the feature extractor layers of the model."}			)
		snake_case			 = field(
		    default=snake_case__      ,							metadata={"help": "Whether to log verbose messages or not."}      ,							)







def   snake_case		(				UpperCAmelCase						:							ModelArguments,    UpperCAmelCase						:							TrainingArguments ):
				logging.basicConfig(
				    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',    datefmt='%m/%d/%Y %H:%M:%S',    handlers=[logging.StreamHandler(sys.stdout )],    )
				A									=   logging.WARNING
				if model_args.verbose_logging:
								A									=   logging.DEBUG
				elif trainer_utils.is_main_process(training_args.local_rank ):
								A									=   logging.INFO
				logger.setLevel(UpperCAmelCase )
@dataclass
class   UpperCamelCase			:







		"""simple docstring"""



		snake_case			 = field(
		    default=snake_case__      ,							metadata={"help": "The name of the dataset to use (via the datasets library)."}			)
		snake_case			 = field(
		    default=snake_case__      ,							metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}			)
		snake_case			 = field(
		    default="train"      ,							metadata={
		        "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
		    }      ,							)
		snake_case			 = field(
		    default="validation"      ,							metadata={
		        "help": (
		            "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"
		        )
		    }      ,							)
		snake_case			 = field(
		    default="text"      ,							metadata={"help": "Column in the dataset that contains label (target text). Defaults to 'text'"}      ,							)
		snake_case			 = field(
		    default="file"      ,							metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"}      ,							)
		snake_case			 = field(
		    default=snake_case__      ,							metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."}      ,							)
		snake_case			 = field(
		    default=snake_case__      ,							metadata={"help": "Filters out examples longer than specified. Defaults to no filtering."}      ,							)
		snake_case			 = field(
		    default="librispeech"      ,							metadata={
		        "help": (
		            "Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"
		            " 'buckwalter'."
		        )
		    }      ,							)
		snake_case			 = field(
		    default=snake_case__      ,							metadata={"help": "Overwrite the cached preprocessed datasets or not."}			)
		snake_case			 = field(
		    default=snake_case__      ,							metadata={"help": "The number of processes to use for the preprocessing."}      ,							)


@dataclass
class   UpperCamelCase			:







		"""simple docstring"""



		snake_case			 = False
		snake_case			 = None
		snake_case			 = "|"
		snake_case			 = field(default_factory=snake_case__			)
		snake_case			 = field(default_factory=snake_case__			)
		snake_case			 = None
		@classmethod
		def    A(	cls		:							List[Any]    ,_SCREAMING_SNAKE_CASE		:							str		)     -> List[str]:


						'''simple docstring'''
						if name == "librispeech":
										return cls()
						if name == "timit":
										return cls(
										    do_lower_case=_SCREAMING_SNAKE_CASE    ,translation_table=str.maketrans({'-': ' '}		)    ,)
						if name == "buckwalter":
										A									=   {
										    '-': ' ',  # sometimes used to represent pauses
										    '^': 'v',  # fixing "tha" in arabic_speech_corpus dataset
										}
										return cls(
										    vocab_file=pathlib.Path(_SCREAMING_SNAKE_CASE		).parent.joinpath('vocab/buckwalter.json'		)    ,word_delimiter_token='/'    ,translation_table=str.maketrans(_SCREAMING_SNAKE_CASE		)    ,words_to_remove={'sil'}    ,untransliterator=arabic.buckwalter.untransliterate    ,)
						raise ValueError(f'Unsupported orthography: \'{name}\'.'		)
		def    A(	self		:							Dict    ,_SCREAMING_SNAKE_CASE		:							str		)     -> str:


						'''simple docstring'''
						# TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
						if len(self.translation_table		) > 0:
										A									=   text.translate(self.translation_table		)
						if len(self.words_to_remove		) == 0:
										A									=   ' '.join(text.split()		)  # clean up whitespaces
						else:
										A									=   ' '.join(w for w in text.split() if w not in self.words_to_remove		)  # and clean up whilespaces
						return text







		def    A(	self		:							Union[str, Any]    ,_SCREAMING_SNAKE_CASE		:							ModelArguments		)     -> WavaVecaProcessor:


						'''simple docstring'''
						A									=   WavaVecaFeatureExtractor.from_pretrained(
						    model_args.model_name_or_path    ,cache_dir=model_args.cache_dir		)
						if self.vocab_file:
										A									=   WavaVecaCTCTokenizer(
										    self.vocab_file    ,cache_dir=model_args.cache_dir    ,do_lower_case=self.do_lower_case    ,word_delimiter_token=self.word_delimiter_token    ,)
						else:
										A									=   WavaVecaCTCTokenizer.from_pretrained(
										    model_args.model_name_or_path    ,cache_dir=model_args.cache_dir    ,do_lower_case=self.do_lower_case    ,word_delimiter_token=self.word_delimiter_token    ,)
						return WavaVecaProcessor(_SCREAMING_SNAKE_CASE    ,_SCREAMING_SNAKE_CASE		)


@dataclass
class   UpperCamelCase			:







		"""simple docstring"""



		snake_case			 = 42
		snake_case			 = True
		snake_case			 = None
		snake_case			 = None
		snake_case			 = None
		snake_case			 = None
		def __call__(	self		:							List[str]    ,_SCREAMING_SNAKE_CASE		:							List[Dict[str, Union[List[int], torch.Tensor]]]		)     -> Dict[str, torch.Tensor]:


						'''simple docstring'''
						# split inputs and labels since they have to be of different lenghts and need
						# different padding methods
						A									=   [{'input_values': feature['input_values']} for feature in features]
						A									=   [{'input_ids': feature['labels']} for feature in features]

						A									=   self.processor.pad(
						    _SCREAMING_SNAKE_CASE    ,padding=self.padding    ,max_length=self.max_length    ,pad_to_multiple_of=self.pad_to_multiple_of    ,return_tensors='pt'    ,)
						A									=   self.processor.pad(
						    labels=_SCREAMING_SNAKE_CASE    ,padding=self.padding    ,max_length=self.max_length_labels    ,pad_to_multiple_of=self.pad_to_multiple_of_labels    ,return_tensors='pt'    ,)

						# replace padding with -100 to ignore loss correctly
						A									=   labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1		)    ,-1_0_0		)

						A									=   labels

						return batch


class   UpperCamelCase			(					snake_case__			):







		"""simple docstring"""



		def    A(	self		:							Union[str, Any]    ,_SCREAMING_SNAKE_CASE		:							nn.Module    ,_SCREAMING_SNAKE_CASE		:							Dict[str, Union[torch.Tensor, Any]]		)     -> torch.Tensor:


						'''simple docstring'''
						model.train()
						A									=   self._prepare_inputs(_SCREAMING_SNAKE_CASE		)

						if self.use_amp:
										with autocast():
														A									=   self.compute_loss(_SCREAMING_SNAKE_CASE    ,_SCREAMING_SNAKE_CASE		)
						else:
										A									=   self.compute_loss(_SCREAMING_SNAKE_CASE    ,_SCREAMING_SNAKE_CASE		)

						if self.args.n_gpu > 1:
										if model.module.config.ctc_loss_reduction == "mean":
														A									=   loss.mean()
										elif model.module.config.ctc_loss_reduction == "sum":
														A									=   loss.sum() / (inputs['labels'] >= 0).sum()
										else:
														raise ValueError(f'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'		)

						if self.args.gradient_accumulation_steps > 1:
										A									=   loss / self.args.gradient_accumulation_steps

						if self.use_amp:
										self.scaler.scale(_SCREAMING_SNAKE_CASE		).backward()
						elif self.use_apex:
										with amp.scale_loss(_SCREAMING_SNAKE_CASE    ,self.optimizer		) as scaled_loss:
														scaled_loss.backward()
						elif self.deepspeed:
										self.deepspeed.backward(_SCREAMING_SNAKE_CASE		)
						else:
										loss.backward()

						return loss.detach()







def   snake_case		(				):
				# See all possible arguments in src/transformers/training_args.py
				# or by passing the --help flag to this script.
				# We now keep distinct sets of args, for a cleaner separation of concerns.

				A									=   HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )

				A			,		A			,		A									=   parser.parse_args_into_dataclasses()
				configure_logger(UpperCAmelCase,    UpperCAmelCase )

				A									=   Orthography.from_name(data_args.orthography.lower() )
				A									=   orthography.create_processor(UpperCAmelCase )
				A									=   WavaVecaForCTC.from_pretrained(
				    model_args.model_name_or_path,    cache_dir=model_args.cache_dir,    gradient_checkpointing=training_args.gradient_checkpointing,    vocab_size=len(processor.tokenizer ),    )

				A									=   datasets.load_dataset(
				    data_args.dataset_name,    data_args.dataset_config_name,    split=data_args.train_split_name )
				A									=   datasets.load_dataset(
				    data_args.dataset_name,    data_args.dataset_config_name,    split=data_args.validation_split_name )

				A									=   datasets.load_metric('wer' )
				A									=   processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
				A									=   ''.join(t for t in processor.tokenizer.get_vocab().keys() if len(UpperCAmelCase ) == 1 )
				A									=   re.compile(  # remove characters not in vocabulary
				    rf'[^\s{re.escape(UpperCAmelCase )}]',    flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0,    )
				A									=   []

				def prepare_example(UpperCAmelCase						:							int ):  # TODO(elgeish) make use of multiprocessing?
								A			,		A									=   librosa.load(example[data_args.speech_file_column],    sr=UpperCAmelCase )
								if data_args.max_duration_in_seconds is not None:
												A									=   len(example['speech'] ) / example['sampling_rate']
								# Normalize and clean up text; order matters!
								A									=   orthography.preprocess_for_training(example[data_args.target_text_column] )
								A									=   vocabulary_text_cleaner.sub('',    UpperCAmelCase )
								if updated_text != example[data_args.target_text_column]:
												text_updates.append((example[data_args.target_text_column], updated_text) )
												A									=   updated_text
								return example

				A									=   train_dataset.map(UpperCAmelCase,    remove_columns=[data_args.speech_file_column] )
				A									=   val_dataset.map(UpperCAmelCase,    remove_columns=[data_args.speech_file_column] )

				if data_args.max_duration_in_seconds is not None:

								def filter_by_max_duration(UpperCAmelCase						:							str ):
												return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

								A									=   len(UpperCAmelCase )
								A									=   len(UpperCAmelCase )
								A									=   train_dataset.filter(UpperCAmelCase,    remove_columns=['duration_in_seconds'] )
								A									=   val_dataset.filter(UpperCAmelCase,    remove_columns=['duration_in_seconds'] )
								if len(UpperCAmelCase ) > old_train_size:
												logger.warning(
												    f'Filtered out {len(UpperCAmelCase ) - old_train_size} train example(s) longer than'
												    f' {data_args.max_duration_in_seconds} second(s).' )
								if len(UpperCAmelCase ) > old_val_size:
												logger.warning(
												    f'Filtered out {len(UpperCAmelCase ) - old_val_size} validation example(s) longer than'
												    f' {data_args.max_duration_in_seconds} second(s).' )
				logger.info(f'Split sizes: {len(UpperCAmelCase )} train and {len(UpperCAmelCase )} validation.' )

				logger.warning(f'Updated {len(UpperCAmelCase )} transcript(s) using \'{data_args.orthography}\' orthography rules.' )
				if logger.isEnabledFor(logging.DEBUG ):
								for original_text, updated_text in text_updates:
												logger.debug(f'Updated text: "{original_text}" -> "{updated_text}"' )
				A									=   None

				def prepare_dataset(UpperCAmelCase						:							str ):
								# check that all files have the correct sampling rate
								assert (
								    len(set(batch['sampling_rate'] ) ) == 1
								), f'Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'

								A									=   processor(
								    audio=batch['speech'],    text=batch[data_args.target_text_column],    sampling_rate=batch['sampling_rate'][0] )
								batch.update(UpperCAmelCase )
								return batch

				A									=   train_dataset.map(
				    UpperCAmelCase,    batch_size=training_args.per_device_train_batch_size,    batched=UpperCAmelCase,    num_proc=data_args.preprocessing_num_workers,    )
				A									=   val_dataset.map(
				    UpperCAmelCase,    batch_size=training_args.per_device_train_batch_size,    batched=UpperCAmelCase,    num_proc=data_args.preprocessing_num_workers,    )

				A									=   DataCollatorCTCWithPadding(processor=UpperCAmelCase,    padding=UpperCAmelCase )

				def compute_metrics(UpperCAmelCase						:							Union[str, Any] ):
								A									=   pred.predictions
								A									=   np.argmax(UpperCAmelCase,    axis=-1 )

								A									=   processor.tokenizer.pad_token_id

								A									=   processor.batch_decode(UpperCAmelCase )
								# we do not want to group tokens when computing the metrics
								A									=   processor.batch_decode(pred.label_ids,    group_tokens=UpperCAmelCase )
								if logger.isEnabledFor(logging.DEBUG ):
												for reference, predicted in zip(UpperCAmelCase,    UpperCAmelCase ):
																logger.debug(f'reference: "{reference}"' )
																logger.debug(f'predicted: "{predicted}"' )
																if orthography.untransliterator is not None:
																				logger.debug(f'reference (untransliterated): "{orthography.untransliterator(UpperCAmelCase )}"' )
																				logger.debug(f'predicted (untransliterated): "{orthography.untransliterator(UpperCAmelCase )}"' )

								A									=   wer_metric.compute(predictions=UpperCAmelCase,    references=UpperCAmelCase )

								return {"wer": wer}

				if model_args.freeze_feature_extractor:
								model.freeze_feature_extractor()

				A									=   CTCTrainer(
				    model=UpperCAmelCase,    data_collator=UpperCAmelCase,    args=UpperCAmelCase,    compute_metrics=UpperCAmelCase,    train_dataset=UpperCAmelCase,    eval_dataset=UpperCAmelCase,    tokenizer=processor.feature_extractor,    )

				trainer.train()


if __name__ == "__main__":
					main()













from typing import List

from packaging import version
from sklearn.metrics import fa_score

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


# TODO(Patrick/Anton)
lowerCAmelCase_     =			'\\n'

lowerCAmelCase_     =			'\\n    XTREME-S is a benchmark to evaluate universal cross-lingual speech representations in many languages.\n    XTREME-S covers four task families: speech recognition, classification, speech-to-text translation and retrieval.\n'

lowerCAmelCase_     =			'\nCompute XTREME-S evaluation metric associated to each XTREME-S dataset.\nArgs:\n    predictions: list of predictions to score.\n        Each translation should be tokenized into a list of tokens.\n    references: list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    bleu_kwargs: optional dict of keywords to be passed when computing \'bleu\'.\n        Keywords include Dict can be one of \'smooth_method\', \'smooth_value\', \'force\', \'lowercase\',\n        \'tokenize\', \'use_effective_order\'.\n    wer_kwargs: optional dict of keywords to be passed when computing \'wer\' and \'cer\'.\n        Keywords include \'concatenate_texts\'.\nReturns: depending on the XTREME-S task, one or several of:\n    "accuracy": Accuracy - for \'fleurs-lang_id\', \'minds14\'\n    "f1": F1 score - for \'minds14\'\n    "wer": Word error rate - for \'mls\', \'fleurs-asr\', \'voxpopuli\', \'babel\'\n    "cer": Character error rate - for \'mls\', \'fleurs-asr\', \'voxpopuli\', \'babel\'\n    "bleu": BLEU score according to the `sacrebleu` metric - for \'covost2\'\nExamples:\n\n    >>> xtreme_s_metric = datasets.load_metric(\'xtreme_s\', \'mls\')  # \'mls\', \'voxpopuli\', \'fleurs-asr\' or \'babel\'\n    >>> references = ["it is sunny here", "paper and pen are essentials"]\n    >>> predictions = ["it\'s sunny", "paper pen are essential"]\n    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)\n    >>> print({k: round(v, 2) for k, v in results.items()})\n    {\'wer\': 0.56, \'cer\': 0.27}\n\n    >>> xtreme_s_metric = datasets.load_metric(\'xtreme_s\', \'covost2\')\n    >>> references = ["bonjour paris", "il est necessaire de faire du sport de temps en temp"]\n    >>> predictions = ["bonjour paris", "il est important de faire du sport souvent"]\n    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)\n    >>> print({k: round(v, 2) for k, v in results.items()})\n    {\'bleu\': 31.65}\n\n    >>> xtreme_s_metric = datasets.load_metric(\'xtreme_s\', \'fleurs-lang_id\')\n    >>> references = [0, 1, 0, 0, 1]\n    >>> predictions = [0, 1, 1, 0, 0]\n    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)\n    >>> print({k: round(v, 2) for k, v in results.items()})\n    {\'accuracy\': 0.6}\n\n    >>> xtreme_s_metric = datasets.load_metric(\'xtreme_s\', \'minds14\')\n    >>> references = [0, 1, 0, 0, 1]\n    >>> predictions = [0, 1, 1, 0, 0]\n    >>> results = xtreme_s_metric.compute(predictions=predictions, references=references)\n    >>> print({k: round(v, 2) for k, v in results.items()})\n    {\'f1\': 0.58, \'accuracy\': 0.6}\n'

lowerCAmelCase_     =			['fleurs-asr', 'mls', 'voxpopuli', 'babel', 'covost2', 'fleurs-lang_id', 'minds14']
lowerCAmelCase_     =			''

try:
					from jiwer import transforms as tr

					lowerCAmelCase_     =			True
except ImportError:
					lowerCAmelCase_     =			False

if _jiwer_available and version.parse(importlib_metadata.version('jiwer')) < version.parse('2.3.0'):
					class   UpperCamelCase			(					tr.AbstractTransform			):







							"""simple docstring"""



							def __init__(	self		:							Any    ,_SCREAMING_SNAKE_CASE		:							str = " "		)     -> Dict:


											'''simple docstring'''
											A									=   sentence_delimiter
							def    A(	self		:							Optional[int]    ,_SCREAMING_SNAKE_CASE		:							str		)     -> int:


											'''simple docstring'''
											return list(_SCREAMING_SNAKE_CASE		)







							def    A(	self		:							Optional[Any]    ,_SCREAMING_SNAKE_CASE		:							List[str]		)     -> Tuple:


											'''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)]
					)
elif _jiwer_available:
					lowerCAmelCase_     =			tr.Compose(
					    [
					        tr.RemoveMultipleSpaces(),
					        tr.Strip(),
					        tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
					        tr.ReduceToListOfListOfChars(),
					    ]
					)
else:
					lowerCAmelCase_     =			None







def   snake_case		(				UpperCAmelCase						:							List[str],    UpperCAmelCase						:							Tuple ):
				return float((preds == labels).mean() )







def   snake_case		(				UpperCAmelCase						:							int,    UpperCAmelCase						:							Tuple ):
				return {
				    "f1": float(fa_score(y_true=UpperCAmelCase,    y_pred=UpperCAmelCase,    average='macro' ) ),
				    "accuracy": simple_accuracy(UpperCAmelCase,    UpperCAmelCase ),
				}







def   snake_case		(				UpperCAmelCase						:							Tuple,    UpperCAmelCase						:							List[str],    UpperCAmelCase						:							List[Any]="exp",    UpperCAmelCase						:							List[Any]=None,    UpperCAmelCase						:							int=False,    UpperCAmelCase						:							Dict=False,    UpperCAmelCase						:							List[Any]=None,    UpperCAmelCase						:							str=False,    ):
				# xtreme-s can only have one label
				A									=   [[label] for label in labels]
				A									=   list(UpperCAmelCase )
				try:
								import sacrebleu as scb
				except ImportError:
								raise ValueError(
								    'sacrebleu has to be installed in order to apply the bleu metric for covost2.'
								    'You can install it via `pip install sacrebleu`.' )

				if version.parse(scb.__version__ ) < version.parse('1.4.12' ):
								raise ImportWarning(
								    'To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n'
								    'You can install it with `pip install "sacrebleu>=1.4.12"`.' )

				A									=   len(labels[0] )
				if any(len(UpperCAmelCase ) != references_per_prediction for refs in labels ):
								raise ValueError('Sacrebleu requires the same number of references for each prediction' )
				A									=   [[refs[i] for refs in labels] for i in range(UpperCAmelCase )]
				A									=   scb.corpus_bleu(
				    UpperCAmelCase,    UpperCAmelCase,    smooth_method=UpperCAmelCase,    smooth_value=UpperCAmelCase,    force=UpperCAmelCase,    lowercase=UpperCAmelCase,    use_effective_order=UpperCAmelCase,    **({'tokenize': tokenize} if tokenize else {}),    )
				return {"bleu": output.score}







def   snake_case		(				UpperCAmelCase						:							Tuple,    UpperCAmelCase						:							Tuple,    UpperCAmelCase						:							Optional[Any],    UpperCAmelCase						:							Optional[int] ):
				try:
								from jiwer import compute_measures
				except ImportError:
								raise ValueError(
								    f'jiwer has to be installed in order to apply the wer metric for {config_name}.'
								    'You can install it via `pip install jiwer`.' )

				if concatenate_texts:
								A									=   compute_measures(UpperCAmelCase,    UpperCAmelCase )['wer']

								A									=   compute_measures(UpperCAmelCase,    UpperCAmelCase,    truth_transform=UpperCAmelCase,    hypothesis_transform=UpperCAmelCase )['wer']
								return {"wer": wer, "cer": cer}
				else:

								def compute_score(UpperCAmelCase						:							Optional[int],    UpperCAmelCase						:							Tuple,    UpperCAmelCase						:							List[Any]="wer" ):
												A									=   0
												A									=   0
												for prediction, reference in zip(UpperCAmelCase,    UpperCAmelCase ):
																if score_type == "wer":
																				A									=   compute_measures(UpperCAmelCase,    UpperCAmelCase )
																elif score_type == "cer":
																				A									=   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

								return {"wer": compute_score(UpperCAmelCase,    UpperCAmelCase,    'wer' ), "cer": compute_score(UpperCAmelCase,    UpperCAmelCase,    'cer' )}



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION      ,							_KWARGS_DESCRIPTION			)
class   UpperCamelCase			(					datasets.Metric			):







		"""simple docstring"""



		def    A(	self		:							Any		)     -> str:


						'''simple docstring'''
						if self.config_name not in _CONFIG_NAMES:
										raise KeyError(f'You should supply a configuration name selected in {_CONFIG_NAMES}'		)

						A									=   'int64' if self.config_name in ['fleurs-lang_id', 'minds14'] else 'string'

						return datasets.MetricInfo(
						    description=_DESCRIPTION    ,citation=_CITATION    ,inputs_description=_KWARGS_DESCRIPTION    ,features=datasets.Features(
						        {'predictions': datasets.Value(_SCREAMING_SNAKE_CASE		), 'references': datasets.Value(_SCREAMING_SNAKE_CASE		)}		)    ,codebase_urls=[]    ,reference_urls=[]    ,format='numpy'    ,)







		def    A(	self		:							Optional[Any]    ,_SCREAMING_SNAKE_CASE		:							str    ,_SCREAMING_SNAKE_CASE		:							List[Any]    ,_SCREAMING_SNAKE_CASE		:							Dict=None    ,_SCREAMING_SNAKE_CASE		:							List[Any]=None		)     -> Tuple:


						'''simple docstring'''
						A									=   bleu_kwargs if bleu_kwargs is not None else {}
						A									=   wer_kwargs if wer_kwargs is not None else {}

						if self.config_name == "fleurs-lang_id":
										return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE    ,_SCREAMING_SNAKE_CASE		)}
						elif self.config_name == "minds14":
										return fa_and_simple_accuracy(_SCREAMING_SNAKE_CASE    ,_SCREAMING_SNAKE_CASE		)
						elif self.config_name == "covost2":
										A									=   bleu_kwargs.pop('smooth_method'    ,'exp'		)
										A									=   bleu_kwargs.pop('smooth_value'    ,_SCREAMING_SNAKE_CASE		)
										A									=   bleu_kwargs.pop('force'    ,_SCREAMING_SNAKE_CASE		)
										A									=   bleu_kwargs.pop('lowercase'    ,_SCREAMING_SNAKE_CASE		)
										A									=   bleu_kwargs.pop('tokenize'    ,_SCREAMING_SNAKE_CASE		)
										A									=   bleu_kwargs.pop('use_effective_order'    ,_SCREAMING_SNAKE_CASE		)
										return bleu(
										    preds=_SCREAMING_SNAKE_CASE    ,labels=_SCREAMING_SNAKE_CASE    ,smooth_method=_SCREAMING_SNAKE_CASE    ,smooth_value=_SCREAMING_SNAKE_CASE    ,force=_SCREAMING_SNAKE_CASE    ,lowercase=_SCREAMING_SNAKE_CASE    ,tokenize=_SCREAMING_SNAKE_CASE    ,use_effective_order=_SCREAMING_SNAKE_CASE    ,)
						elif self.config_name in ["fleurs-asr", "mls", "voxpopuli", "babel"]:
										A									=   wer_kwargs.pop('concatenate_texts'    ,_SCREAMING_SNAKE_CASE		)
										return wer_and_cer(_SCREAMING_SNAKE_CASE    ,_SCREAMING_SNAKE_CASE    ,_SCREAMING_SNAKE_CASE    ,self.config_name		)
						else:
										raise KeyError(f'You should supply a configuration name selected in {_CONFIG_NAMES}'		)





