



import math
import warnings
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch
from scipy import integrate

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin

@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->LMSDiscrete
class 						UpperCAmelCase__     (     __UpperCamelCase  ):




			'''simple docstring'''






			UpperCamelCase     		=			42
			UpperCamelCase     		=			None

def 			a		( _UpperCAmelCase				:   int					,  _UpperCAmelCase				:   str=0.9_99					,  _UpperCAmelCase				:   Optional[Any]="cosine"					,  ):







		'''simple docstring'''





		if alpha_transform_type == "cosine":

				def alpha_bar_fn(_UpperCAmelCase				:   List[str]		):
						return math.cos((t + 0.0_08) / 1.0_08 * math.pi / 2		) ** 2

		elif alpha_transform_type == "exp":

				def alpha_bar_fn(_UpperCAmelCase				:   Union[str, Any]		):
						return math.exp(t * -12.0		)

		else:
				raise ValueError(f'Unsupported alpha_tranform_type: {alpha_transform_type}'		)

		__UpperCAmelCase       :	Tuple						=      []
		for i in range(_UpperCAmelCase		):
				__UpperCAmelCase       :	List[Any]						=      i / num_diffusion_timesteps
				__UpperCAmelCase       :	Optional[int]						=      (i + 1) / num_diffusion_timesteps
				betas.append(min(1 - alpha_bar_fn(_UpperCAmelCase		) / alpha_bar_fn(_UpperCAmelCase		)					,  _UpperCAmelCase		)		)
		return torch.tensor(_UpperCAmelCase					,  dtype=torch.floataa		)

class 						UpperCAmelCase__     (     __UpperCamelCase		,__UpperCamelCase  ):




			'''simple docstring'''






			UpperCamelCase     		=			[e.name for e in KarrasDiffusionSchedulers]
			UpperCamelCase     		=			1




			@register_to_config
			def __init__(  self				:					int			,			a_				:					int = 10_00			,			a_				:					float = 0.0_0_0_1			,			a_				:					float = 0.0_2			,			a_				:					str = "linear"			,			a_				:					Optional[Union[np.ndarray, List[float]]] = None			,			a_				:					Optional[bool] = False			,			a_				:					str = "epsilon"			,			a_				:					str = "linspace"			,			a_				:					int = 0			,			):
					'''simple docstring'''





					if trained_betas is not None:
							__UpperCAmelCase       :	List[str]						=      torch.tensor(a_			,			dtype=torch.floataa					)
					elif beta_schedule == "linear":
							__UpperCAmelCase       :	Union[str, Any]						=      torch.linspace(a_			,			a_			,			a_			,			dtype=torch.floataa					)
					elif beta_schedule == "scaled_linear":
							# this schedule is very specific to the latent diffusion model.
							__UpperCAmelCase       :	Dict						=      (
							    torch.linspace(beta_start**0.5			,			beta_end**0.5			,			a_			,			dtype=torch.floataa					) ** 2
							)
					elif beta_schedule == "squaredcos_cap_v2":
							# Glide cosine schedule
							__UpperCAmelCase       :	Optional[int]						=      betas_for_alpha_bar(a_					)
					else:
							raise NotImplementedError(F'{beta_schedule} does is not implemented for {self.__class__}'					)

					__UpperCAmelCase       :	List[str]						=      1.0 - self.betas
					__UpperCAmelCase       :	List[Any]						=      torch.cumprod(self.alphas			,			dim=0					)

					__UpperCAmelCase       :	str						=      np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5					)
					__UpperCAmelCase       :	Tuple						=      np.concatenate([sigmas[::-1], [0.0]]					).astype(np.floataa					)
					__UpperCAmelCase       :	Tuple						=      torch.from_numpy(a_					)

					# setable values
					__UpperCAmelCase       :	Dict						=      None
					__UpperCAmelCase       :	Union[str, Any]						=      use_karras_sigmas
					self.set_timesteps(a_			,			a_					)
					__UpperCAmelCase       :	int						=      []
					__UpperCAmelCase       :	Tuple						=      False




			@property
			def 					snake_case__	(  self				:					List[str]					):
					'''simple docstring'''





					if self.config.timestep_spacing in ["linspace", "trailing"]:
							return self.sigmas.max()

					return (self.sigmas.max() ** 2 + 1) ** 0.5




			def 					snake_case__	(  self				:					List[str]			,			a_				:					torch.FloatTensor			,			a_				:					Union[float, torch.FloatTensor]					):
					'''simple docstring'''





					if isinstance(a_			,			torch.Tensor					):
							__UpperCAmelCase       :	Union[str, Any]						=      timestep.to(self.timesteps.device					)
					__UpperCAmelCase       :	str						=      (self.timesteps == timestep).nonzero().item()
					__UpperCAmelCase       :	List[Any]						=      self.sigmas[step_index]
					__UpperCAmelCase       :	str						=      sample / ((sigma**2 + 1) ** 0.5)
					__UpperCAmelCase       :	Optional[int]						=      True
					return sample




			def 					snake_case__	(  self				:					Dict			,			a_				:					str			,			a_				:					Union[str, Any]			,			a_				:					Any					):
					'''simple docstring'''





					def lms_derivative(a_				:					Optional[Any]					):
							__UpperCAmelCase       :	int						=      1.0
							for k in range(a_					):
									if current_order == k:
											continue
									prod *= (tau - self.sigmas[t - k]) / (self.sigmas[t - current_order] - self.sigmas[t - k])
							return prod

					__UpperCAmelCase       :	List[Any]						=      integrate.quad(a_			,			self.sigmas[t]			,			self.sigmas[t + 1]			,			epsrel=1e-4					)[0]

					return integrated_coeff




			def 					snake_case__	(  self				:					int			,			a_				:					int			,			a_				:					Union[str, torch.device] = None					):
					'''simple docstring'''





					__UpperCAmelCase       :	Optional[int]						=      num_inference_steps

					# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
					if self.config.timestep_spacing == "linspace":
							__UpperCAmelCase       :	Optional[int]						=      np.linspace(0			,			self.config.num_train_timesteps - 1			,			a_			,			dtype=a_					)[
							    ::-1
							].copy()
					elif self.config.timestep_spacing == "leading":
							__UpperCAmelCase       :	Optional[Any]						=      self.config.num_train_timesteps // self.num_inference_steps
							# creates integer timesteps by multiplying by ratio
							# casting to int to avoid issues when num_inference_step is power of 3
							__UpperCAmelCase       :	Any						=      (np.arange(0			,			a_					) * step_ratio).round()[::-1].copy().astype(a_					)
							timesteps += self.config.steps_offset
					elif self.config.timestep_spacing == "trailing":
							__UpperCAmelCase       :	List[str]						=      self.config.num_train_timesteps / self.num_inference_steps
							# creates integer timesteps by multiplying by ratio
							# casting to int to avoid issues when num_inference_step is power of 3
							__UpperCAmelCase       :	str						=      (np.arange(self.config.num_train_timesteps			,			0			,			-step_ratio					)).round().copy().astype(a_					)
							timesteps -= 1
					else:
							raise ValueError(
							    F'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'					)

					__UpperCAmelCase       :	Dict						=      np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5					)
					__UpperCAmelCase       :	str						=      np.log(a_					)
					__UpperCAmelCase       :	int						=      np.interp(a_			,			np.arange(0			,			len(a_					)					)			,			a_					)

					if self.use_karras_sigmas:
							__UpperCAmelCase       :	List[str]						=      self._convert_to_karras(in_sigmas=a_					)
							__UpperCAmelCase       :	Tuple						=      np.array([self._sigma_to_t(a_			,			a_					) for sigma in sigmas]					)

					__UpperCAmelCase       :	Union[str, Any]						=      np.concatenate([sigmas, [0.0]]					).astype(np.floataa					)

					__UpperCAmelCase       :	Optional[int]						=      torch.from_numpy(a_					).to(device=a_					)
					if str(a_					).startswith('''mps'''					):
							# mps does not support float64
							__UpperCAmelCase       :	List[str]						=      torch.from_numpy(a_					).to(a_			,			dtype=torch.floataa					)
					else:
							__UpperCAmelCase       :	Union[str, Any]						=      torch.from_numpy(a_					).to(device=a_					)

					__UpperCAmelCase       :	List[Any]						=      []




			def 					snake_case__	(  self				:					Tuple			,			a_				:					str			,			a_				:					Optional[int]					):
					'''simple docstring'''





					__UpperCAmelCase       :	List[str]						=      np.log(a_					)

					# get distribution
					__UpperCAmelCase       :	Optional[Any]						=      log_sigma - log_sigmas[:, np.newaxis]

					# get sigmas range
					__UpperCAmelCase       :	int						=      np.cumsum((dists >= 0)			,			axis=0					).argmax(axis=0					).clip(max=log_sigmas.shape[0] - 2					)
					__UpperCAmelCase       :	Union[str, Any]						=      low_idx + 1

					__UpperCAmelCase       :	int						=      log_sigmas[low_idx]
					__UpperCAmelCase       :	Optional[int]						=      log_sigmas[high_idx]

					# interpolate sigmas
					__UpperCAmelCase       :	Optional[int]						=      (low - log_sigma) / (low - high)
					__UpperCAmelCase       :	Optional[int]						=      np.clip(a_			,			0			,			1					)

					# transform interpolation to time range
					__UpperCAmelCase       :	int						=      (1 - w) * low_idx + w * high_idx
					__UpperCAmelCase       :	List[Any]						=      t.reshape(sigma.shape					)
					return t




			def 					snake_case__	(  self				:					int			,			a_				:					torch.FloatTensor					):
					'''simple docstring'''





					__UpperCAmelCase       :	float						=      in_sigmas[-1].item()
					__UpperCAmelCase       :	float						=      in_sigmas[0].item()

					__UpperCAmelCase       :	str						=      7.0  # 7.0 is the value used in the paper
					__UpperCAmelCase       :	Tuple						=      np.linspace(0			,			1			,			self.num_inference_steps					)
					__UpperCAmelCase       :	str						=      sigma_min ** (1 / rho)
					__UpperCAmelCase       :	Any						=      sigma_max ** (1 / rho)
					__UpperCAmelCase       :	List[Any]						=      (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
					return sigmas




			def 					snake_case__	(  self				:					str			,			a_				:					torch.FloatTensor			,			a_				:					Union[float, torch.FloatTensor]			,			a_				:					torch.FloatTensor			,			a_				:					int = 4			,			a_				:					bool = True			,			):
					'''simple docstring'''





					if not self.is_scale_input_called:
							warnings.warn(
							    '''The `scale_model_input` function should be called before `step` to ensure correct denoising. '''
							    '''See `StableDiffusionPipeline` for a usage example.'''					)

					if isinstance(a_			,			torch.Tensor					):
							__UpperCAmelCase       :	Any						=      timestep.to(self.timesteps.device					)
					__UpperCAmelCase       :	Dict						=      (self.timesteps == timestep).nonzero().item()
					__UpperCAmelCase       :	int						=      self.sigmas[step_index]

					# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
					if self.config.prediction_type == "epsilon":
							__UpperCAmelCase       :	str						=      sample - sigma * model_output
					elif self.config.prediction_type == "v_prediction":
							# * c_out + input * c_skip
							__UpperCAmelCase       :	str						=      model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
					elif self.config.prediction_type == "sample":
							__UpperCAmelCase       :	Any						=      model_output
					else:
							raise ValueError(
							    F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'					)

					# 2. Convert to an ODE derivative
					__UpperCAmelCase       :	List[Any]						=      (sample - pred_original_sample) / sigma
					self.derivatives.append(a_					)
					if len(self.derivatives					) > order:
							self.derivatives.pop(0					)

					# 3. Compute linear multistep coefficients
					__UpperCAmelCase       :	Optional[int]						=      min(step_index + 1			,			a_					)
					__UpperCAmelCase       :	List[str]						=      [self.get_lms_coefficient(a_			,			a_			,			a_					) for curr_order in range(a_					)]

					# 4. Compute previous sample based on the derivatives path
					__UpperCAmelCase       :	List[str]						=      sample + sum(
					    coeff * derivative for coeff, derivative in zip(a_			,			reversed(self.derivatives					)					)					)

					if not return_dict:
							return (prev_sample,)

					return LMSDiscreteSchedulerOutput(prev_sample=a_			,			pred_original_sample=a_					)




			def 					snake_case__	(  self				:					int			,			a_				:					torch.FloatTensor			,			a_				:					torch.FloatTensor			,			a_				:					torch.FloatTensor			,			):
					'''simple docstring'''





					__UpperCAmelCase       :	Tuple						=      self.sigmas.to(device=original_samples.device			,			dtype=original_samples.dtype					)
					if original_samples.device.type == "mps" and torch.is_floating_point(a_					):
							# mps does not support float64
							__UpperCAmelCase       :	Union[str, Any]						=      self.timesteps.to(original_samples.device			,			dtype=torch.floataa					)
							__UpperCAmelCase       :	str						=      timesteps.to(original_samples.device			,			dtype=torch.floataa					)
					else:
							__UpperCAmelCase       :	List[Any]						=      self.timesteps.to(original_samples.device					)
							__UpperCAmelCase       :	Union[str, Any]						=      timesteps.to(original_samples.device					)

					__UpperCAmelCase       :	Union[str, Any]						=      [(schedule_timesteps == t).nonzero().item() for t in timesteps]

					__UpperCAmelCase       :	str						=      sigmas[step_indices].flatten()
					while len(sigma.shape					) < len(original_samples.shape					):
							__UpperCAmelCase       :	List[Any]						=      sigma.unsqueeze(-1					)

					__UpperCAmelCase       :	Any						=      original_samples + noise * sigma
					return noisy_samples




			def __len__(  self				:					Dict					):
					'''simple docstring'''





					return self.config.num_train_timesteps










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)
__A       ="\\n"

__A       ="\\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"

__A       ="\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"

__A       =["fleurs-asr", "mls", "voxpopuli", "babel", "covost2", "fleurs-lang_id", "minds14"]
__A       =""

try:
				from jiwer import transforms as tr

				__A       =True
except ImportError:
				__A       =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				:					Tuple			,			a_				:					str = " "					):
									'''simple docstring'''





									__UpperCAmelCase       :	str						=      sentence_delimiter




							def 					snake_case__	(  self				:					Union[str, Any]			,			a_				:					str					):
									'''simple docstring'''





									return list(a_					)




							def 					snake_case__	(  self				:					List[str]			,			a_				:					List[str]					):
									'''simple docstring'''





									__UpperCAmelCase       :	Optional[Any]						=      []
									for sent_idx, sentence in enumerate(a_					):
											chars.extend(self.process_string(a_					)					)
											if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(a_					) - 1:
													chars.append(self.sentence_delimiter					)
									return chars
				__A       =tr.Compose(
				    [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
				)
elif _jiwer_available:
				__A       =tr.Compose(
				    [
				        tr.RemoveMultipleSpaces(),
				        tr.Strip(),
				        tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
				        tr.ReduceToListOfListOfChars(),
				    ]
				)
else:
				__A       =None

def 			a		( _UpperCAmelCase				:   Optional[Any]					,  _UpperCAmelCase				:   int		):







		'''simple docstring'''





		return float((preds == labels).mean()		)

def 			a		( _UpperCAmelCase				:   Tuple					,  _UpperCAmelCase				:   Union[str, Any]		):







		'''simple docstring'''





		return {
		    "f1": float(fa_score(y_true=_UpperCAmelCase					,  y_pred=_UpperCAmelCase					,  average='''macro'''		)		),
		    "accuracy": simple_accuracy(_UpperCAmelCase					,  _UpperCAmelCase		),
		}

def 			a		( _UpperCAmelCase				:   Optional[Any]					,  _UpperCAmelCase				:   Optional[Any]					,  _UpperCAmelCase				:   int="exp"					,  _UpperCAmelCase				:   Optional[int]=None					,  _UpperCAmelCase				:   Dict=False					,  _UpperCAmelCase				:   List[Any]=False					,  _UpperCAmelCase				:   Optional[Any]=None					,  _UpperCAmelCase				:   str=False					,  ):







		'''simple docstring'''





		__UpperCAmelCase       :	List[Any]						=      [[label] for label in labels]
		__UpperCAmelCase       :	Any						=      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"`.'''		)

		__UpperCAmelCase       :	Dict						=      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'''		)
		__UpperCAmelCase       :	Union[str, Any]						=      [[refs[i] for refs in labels] for i in range(_UpperCAmelCase		)]
		__UpperCAmelCase       :	Tuple						=      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 			a		( _UpperCAmelCase				:   Optional[int]					,  _UpperCAmelCase				:   Dict					,  _UpperCAmelCase				:   Optional[int]					,  _UpperCAmelCase				:   str		):







		'''simple docstring'''





		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:
				__UpperCAmelCase       :	int						=      compute_measures(_UpperCAmelCase					,  _UpperCAmelCase		)['''wer''']

				__UpperCAmelCase       :	List[Any]						=      compute_measures(_UpperCAmelCase					,  _UpperCAmelCase					,  truth_transform=_UpperCAmelCase					,  hypothesis_transform=_UpperCAmelCase		)['''wer''']
				return {"wer": wer, "cer": cer}
		else:

				def compute_score(_UpperCAmelCase				:   Tuple					,  _UpperCAmelCase				:   Dict					,  _UpperCAmelCase				:   Tuple="wer"		):
						__UpperCAmelCase       :	List[Any]						=      0
						__UpperCAmelCase       :	Tuple						=      0
						for prediction, reference in zip(_UpperCAmelCase					,  _UpperCAmelCase		):
								if score_type == "wer":
										__UpperCAmelCase       :	Optional[int]						=      compute_measures(_UpperCAmelCase					,  _UpperCAmelCase		)
								elif score_type == "cer":
										__UpperCAmelCase       :	Any						=      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 					snake_case__	(  self				:					Optional[int]					):
					'''simple docstring'''





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

					__UpperCAmelCase       :	Optional[int]						=      '''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(a_					), '''references''': datasets.Value(a_					)}					)			,			codebase_urls=[]			,			reference_urls=[]			,			format='''numpy'''			,			)




			def 					snake_case__	(  self				:					Any			,			a_				:					Optional[int]			,			a_				:					str			,			a_				:					str=None			,			a_				:					str=None					):
					'''simple docstring'''





					__UpperCAmelCase       :	Tuple						=      bleu_kwargs if bleu_kwargs is not None else {}
					__UpperCAmelCase       :	Any						=      wer_kwargs if wer_kwargs is not None else {}

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





