



import unittest
from unittest.util import safe_repr

from transformers import AutoTokenizer, RwkvConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    RWKV_PRETRAINED_MODEL_ARCHIVE_LIST,
				    RwkvForCausalLM,
				    RwkvModel,
				)
				from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_0
else:
				__A       =False

class 						UpperCAmelCase__     :




			'''simple docstring'''






			def __init__(  self				:					str			,			a_				:					List[str]			,			a_				:					Union[str, Any]=14			,			a_				:					Union[str, Any]=7			,			a_				:					List[str]=True			,			a_				:					Any=False			,			a_				:					Optional[int]=True			,			a_				:					Dict=True			,			a_				:					Dict=True			,			a_				:					Union[str, Any]=99			,			a_				:					str=32			,			a_				:					Any=5			,			a_				:					Union[str, Any]=37			,			a_				:					Optional[int]="gelu"			,			a_				:					Union[str, Any]=0.1			,			a_				:					Union[str, Any]=0.1			,			a_				:					Union[str, Any]=5_12			,			a_				:					int=16			,			a_				:					List[Any]=2			,			a_				:					Optional[int]=3			,			a_				:					Optional[Any]=4			,			a_				:					List[str]=None			,			):
					'''simple docstring'''





					__UpperCAmelCase       :	Optional[int]						=      parent
					__UpperCAmelCase       :	Any						=      batch_size
					__UpperCAmelCase       :	Optional[Any]						=      seq_length
					__UpperCAmelCase       :	Optional[Any]						=      is_training
					__UpperCAmelCase       :	int						=      use_token_type_ids
					__UpperCAmelCase       :	List[str]						=      use_input_mask
					__UpperCAmelCase       :	Tuple						=      use_labels
					__UpperCAmelCase       :	int						=      use_mc_token_ids
					__UpperCAmelCase       :	Union[str, Any]						=      vocab_size
					__UpperCAmelCase       :	Optional[Any]						=      hidden_size
					__UpperCAmelCase       :	List[Any]						=      num_hidden_layers
					__UpperCAmelCase       :	str						=      intermediate_size
					__UpperCAmelCase       :	int						=      hidden_act
					__UpperCAmelCase       :	str						=      hidden_dropout_prob
					__UpperCAmelCase       :	int						=      attention_probs_dropout_prob
					__UpperCAmelCase       :	Optional[int]						=      max_position_embeddings
					__UpperCAmelCase       :	Optional[Any]						=      type_vocab_size
					__UpperCAmelCase       :	int						=      type_sequence_label_size
					__UpperCAmelCase       :	Optional[int]						=      num_labels
					__UpperCAmelCase       :	List[str]						=      num_choices
					__UpperCAmelCase       :	int						=      scope
					__UpperCAmelCase       :	Any						=      vocab_size - 1
					__UpperCAmelCase       :	Tuple						=      vocab_size - 1
					__UpperCAmelCase       :	Any						=      vocab_size - 1




			def 					snake_case__	(  self				:					int					):
					'''simple docstring'''





					return RwkvConfig.from_pretrained('''sgugger/rwkv-4-pile-7b'''					)




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





					__UpperCAmelCase       :	str						=      ids_tensor([self.batch_size, self.seq_length]			,			self.vocab_size					)

					__UpperCAmelCase       :	Optional[int]						=      None
					if self.use_input_mask:
							__UpperCAmelCase       :	Optional[int]						=      random_attention_mask([self.batch_size, self.seq_length]					)

					__UpperCAmelCase       :	Tuple						=      None
					if self.use_token_type_ids:
							__UpperCAmelCase       :	Dict						=      ids_tensor([self.batch_size, self.seq_length]			,			self.type_vocab_size					)

					__UpperCAmelCase       :	Optional[Any]						=      None
					if self.use_mc_token_ids:
							__UpperCAmelCase       :	Any						=      ids_tensor([self.batch_size, self.num_choices]			,			self.seq_length					)

					__UpperCAmelCase       :	Union[str, Any]						=      None
					__UpperCAmelCase       :	int						=      None
					__UpperCAmelCase       :	Optional[int]						=      None
					if self.use_labels:
							__UpperCAmelCase       :	Optional[Any]						=      ids_tensor([self.batch_size]			,			self.type_sequence_label_size					)
							__UpperCAmelCase       :	Optional[int]						=      ids_tensor([self.batch_size, self.seq_length]			,			self.num_labels					)
							__UpperCAmelCase       :	List[str]						=      ids_tensor([self.batch_size]			,			self.num_choices					)

					__UpperCAmelCase       :	str						=      self.get_config(
					    gradient_checkpointing=a_			,			scale_attn_by_inverse_layer_idx=a_			,			reorder_and_upcast_attn=a_			,			)

					return (
					    config,
					    input_ids,
					    input_mask,
					    None,
					    token_type_ids,
					    mc_token_ids,
					    sequence_labels,
					    token_labels,
					    choice_labels,
					)




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





					return RwkvConfig(
					    vocab_size=self.vocab_size			,			hidden_size=self.hidden_size			,			num_hidden_layers=self.num_hidden_layers			,			intermediate_size=self.intermediate_size			,			activation_function=self.hidden_act			,			resid_pdrop=self.hidden_dropout_prob			,			attn_pdrop=self.attention_probs_dropout_prob			,			n_positions=self.max_position_embeddings			,			type_vocab_size=self.type_vocab_size			,			use_cache=a_			,			bos_token_id=self.bos_token_id			,			eos_token_id=self.eos_token_id			,			pad_token_id=self.pad_token_id			,			gradient_checkpointing=a_			,			scale_attn_by_inverse_layer_idx=a_			,			reorder_and_upcast_attn=a_			,			)




			def 					snake_case__	(  self				:					List[Any]					):
					'''simple docstring'''





					__UpperCAmelCase       :	List[str]						=      self.get_config()
					__UpperCAmelCase       :	List[Any]						=      3_00
					return config




			def 					snake_case__	(  self				:					int					):
					'''simple docstring'''





					(
					    (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   
					)       :	Dict						=      self.prepare_config_and_inputs()

					__UpperCAmelCase       :	Dict						=      floats_tensor([self.batch_size, self.seq_length, self.hidden_size]					)
					__UpperCAmelCase       :	Dict						=      ids_tensor([self.batch_size, self.seq_length]			,			vocab_size=2					)

					return (
					    config,
					    input_ids,
					    input_mask,
					    head_mask,
					    token_type_ids,
					    sequence_labels,
					    token_labels,
					    choice_labels,
					    encoder_hidden_states,
					    encoder_attention_mask,
					)




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





					__UpperCAmelCase       :	int						=      True
					__UpperCAmelCase       :	Optional[int]						=      RwkvModel(config=a_					)
					model.to(a_					)
					model.eval()

					__UpperCAmelCase       :	List[str]						=      model(a_					)

					self.parent.assertEqual(result.last_hidden_state.shape			,			(self.batch_size, self.seq_length, self.hidden_size)					)
					self.parent.assertEqual(len(result.hidden_states					)			,			config.num_hidden_layers + 1					)




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





					__UpperCAmelCase       :	List[str]						=      RwkvForCausalLM(a_					)
					model.to(a_					)
					model.eval()

					__UpperCAmelCase       :	int						=      model(a_			,			labels=a_					)
					self.parent.assertEqual(result.loss.shape			,			()					)
					self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.seq_length, self.vocab_size)					)




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





					__UpperCAmelCase       :	Optional[int]						=      RwkvModel(config=a_					)
					model.to(a_					)
					model.eval()

					__UpperCAmelCase       :	Dict						=      model(a_					)
					__UpperCAmelCase       :	int						=      outputs.last_hidden_state

					__UpperCAmelCase       :	Any						=      model(input_ids[:, :2]					)
					__UpperCAmelCase       :	Optional[int]						=      outputs.last_hidden_state

					# Using the state computed on the first inputs, we will get the same output
					__UpperCAmelCase       :	Any						=      model(input_ids[:, 2:]			,			state=outputs.state					)
					__UpperCAmelCase       :	Optional[int]						=      outputs.last_hidden_state

					self.parent.assertTrue(torch.allclose(torch.cat([output_one, output_two]			,			dim=1					)			,			a_			,			atol=1e-5					)					)




			def 					snake_case__	(  self				:					Union[str, Any]			,			a_				:					List[Any]			,			a_				:					List[str]			,			a_				:					Union[str, Any]			,			a_				:					Tuple			,			a_				:					List[Any]			,			*a_				:					List[Any]			,			a_				:					int=False					):
					'''simple docstring'''





					__UpperCAmelCase       :	Optional[Any]						=      RwkvForCausalLM(a_					)
					model.to(a_					)
					if gradient_checkpointing:
							model.gradient_checkpointing_enable()

					__UpperCAmelCase       :	int						=      model(a_			,			labels=a_					)
					self.parent.assertEqual(result.loss.shape			,			()					)
					self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.seq_length, self.vocab_size)					)
					result.loss.backward()




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





					__UpperCAmelCase       :	Optional[Any]						=      self.prepare_config_and_inputs()

					(
					    (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   (
					    __UpperCAmelCase
					)				,   
					)       :	Union[str, Any]						=      config_and_inputs

					__UpperCAmelCase       :	Union[str, Any]						=      {'''input_ids''': input_ids}

					return config, inputs_dict

@unittest.skipIf(
    not is_torch_greater_or_equal_than_2_0		,reason="""See https://github.com/huggingface/transformers/pull/24204"""  )
@require_torch
class 						UpperCAmelCase__     (     __UpperCamelCase		,__UpperCamelCase		,__UpperCamelCase		,unittest.TestCase  ):




			'''simple docstring'''






			UpperCamelCase     		=			(RwkvModel, RwkvForCausalLM) if is_torch_available() else ()
			UpperCamelCase     		=			(
			    {"""feature-extraction""": RwkvModel, """text-generation""": RwkvForCausalLM} if is_torch_available() else {}
			)
			# all_generative_model_classes = (RwkvForCausalLM,) if is_torch_available() else ()
			UpperCamelCase     		=			False
			UpperCamelCase     		=			False
			UpperCamelCase     		=			False
			UpperCamelCase     		=			False
			UpperCamelCase     		=			False  # Rwkv does not support head masking




			def 					snake_case__	(  self				:					Any					):
					'''simple docstring'''





					__UpperCAmelCase       :	str						=      RwkvModelTester(self					)
					__UpperCAmelCase       :	int						=      ConfigTester(
					    self			,			config_class=a_			,			n_embd=37			,			common_properties=['''hidden_size''', '''num_hidden_layers''']					)




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





					if isinstance(a_			,			torch.Tensor					):
							__UpperCAmelCase				,   __UpperCAmelCase       :	Dict						=      member.max().item(), member.min().item()
					elif isinstance(a_			,			a_					) or isinstance(a_			,			a_					):
							__UpperCAmelCase				,   __UpperCAmelCase       :	Union[str, Any]						=      max(a_					), min(a_					)

					if not isinstance(a_			,			a_					):
							raise TypeError('''container should be a list or tuple'''					)
					elif len(a_					) != 2:
							raise ValueError('''container should have 2 elements'''					)

					__UpperCAmelCase				,   __UpperCAmelCase       :	Union[str, Any]						=      container

					__UpperCAmelCase       :	Any						=      (min_value >= expected_min) and (max_value <= expected_max)

					if not is_inside_interval:
							__UpperCAmelCase       :	Tuple						=      '''%s not found in %s''' % (safe_repr(a_					), safe_repr(a_					))
							self.fail(self._formatMessage(a_			,			a_					)					)




			def 					snake_case__	(  self				:					Optional[int]					):
					'''simple docstring'''





					self.config_tester.run_common_tests()




			def 					snake_case__	(  self				:					Optional[Any]					):
					'''simple docstring'''





					__UpperCAmelCase       :	Optional[Any]						=      self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_rwkv_model(*a_					)




			def 					snake_case__	(  self				:					str					):
					'''simple docstring'''





					__UpperCAmelCase       :	List[str]						=      self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_causl_lm(*a_					)




			def 					snake_case__	(  self				:					Optional[Any]					):
					'''simple docstring'''





					__UpperCAmelCase       :	int						=      self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_state_equivalency(*a_					)




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





					__UpperCAmelCase				,   __UpperCAmelCase       :	List[str]						=      self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
							__UpperCAmelCase       :	Any						=      model_class(config=a_					)
							for name, param in model.named_parameters():
									if "time_decay" in name:
											if param.requires_grad:
													self.assertTrue(param.data.max().item() == 3.0					)
													self.assertTrue(param.data.min().item() == -5.0					)
									elif "time_first" in name:
											if param.requires_grad:
													# check if it's a ones like
													self.assertTrue(torch.allclose(param.data			,			torch.ones_like(param.data					)			,			atol=1e-5			,			rtol=1e-5					)					)
									elif any(x in name for x in ['''time_mix_key''', '''time_mix_receptance''']					):
											if param.requires_grad:
													self.assertInterval(
													    param.data			,			[0.0, 1.0]			,			msg=F'Parameter {name} of model {model_class} seems not properly initialized'			,			)
									elif "time_mix_value" in name:
											if param.requires_grad:
													self.assertInterval(
													    param.data			,			[0.0, 1.3]			,			msg=F'Parameter {name} of model {model_class} seems not properly initialized'			,			)




			def 					snake_case__	(  self				:					List[Any]					):
					'''simple docstring'''





					__UpperCAmelCase				,   __UpperCAmelCase       :	Tuple						=      self.model_tester.prepare_config_and_inputs_for_common()
					__UpperCAmelCase       :	Optional[Any]						=      True

					__UpperCAmelCase       :	List[str]						=      getattr(self.model_tester			,			'''seq_length'''			,			a_					)

					for model_class in self.all_model_classes:
							__UpperCAmelCase       :	Dict						=      True
							__UpperCAmelCase       :	Union[str, Any]						=      False
							__UpperCAmelCase       :	int						=      True
							__UpperCAmelCase       :	Any						=      model_class(a_					)
							model.to(a_					)
							model.eval()

							__UpperCAmelCase       :	List[str]						=      self._prepare_for_class(a_			,			a_					)
							__UpperCAmelCase       :	Optional[int]						=      inputs['''input_ids'''].shape[0]
							with torch.no_grad():
									__UpperCAmelCase       :	List[str]						=      model(**a_					)
							__UpperCAmelCase       :	Tuple						=      outputs.attentions
							self.assertEqual(len(a_					)			,			self.model_tester.num_hidden_layers					)

							# check that output_attentions also work using config
							del inputs_dict["output_attentions"]
							__UpperCAmelCase       :	Union[str, Any]						=      True
							__UpperCAmelCase       :	Union[str, Any]						=      model_class(a_					)
							model.to(a_					)
							model.eval()

							__UpperCAmelCase       :	Union[str, Any]						=      self._prepare_for_class(a_			,			a_					)
							__UpperCAmelCase       :	str						=      inputs['''input_ids'''].shape[0]
							with torch.no_grad():
									__UpperCAmelCase       :	Dict						=      model(**a_					)
							__UpperCAmelCase       :	str						=      outputs.attentions
							self.assertEqual(len(a_					)			,			self.model_tester.num_hidden_layers					)

							self.assertListEqual(
							    list(attentions[0].shape[-3:]					)			,			[batch_size, seq_len, config.hidden_size]			,			)
							__UpperCAmelCase       :	List[Any]						=      len(a_					)

							# Check attention is always last and order is fine
							__UpperCAmelCase       :	Optional[Any]						=      True
							__UpperCAmelCase       :	Optional[int]						=      True
							__UpperCAmelCase       :	Any						=      model_class(a_					)
							model.to(a_					)
							model.eval()

							__UpperCAmelCase       :	Dict						=      self._prepare_for_class(a_			,			a_					)
							__UpperCAmelCase       :	int						=      inputs['''input_ids'''].shape[0]
							with torch.no_grad():
									__UpperCAmelCase       :	Union[str, Any]						=      model(**a_					)

							__UpperCAmelCase       :	Union[str, Any]						=      1
							self.assertEqual(out_len + added_hidden_states			,			len(a_					)					)

							__UpperCAmelCase       :	str						=      outputs.attentions

							self.assertEqual(len(a_					)			,			self.model_tester.num_hidden_layers					)
							self.assertListEqual(
							    list(self_attentions[0].shape[-3:]					)			,			[batch_size, seq_len, config.hidden_size]			,			)




			@slow
			def 					snake_case__	(  self				:					List[Any]					):
					'''simple docstring'''





					for model_name in RWKV_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__UpperCAmelCase       :	Dict						=      RwkvModel.from_pretrained(a_					)
							self.assertIsNotNone(a_					)

@unittest.skipIf(
    not is_torch_greater_or_equal_than_2_0		,reason="""See https://github.com/huggingface/transformers/pull/24204"""  )
@slow
class 						UpperCAmelCase__     (     unittest.TestCase  ):




			'''simple docstring'''






			def 					snake_case__	(  self				:					int					):
					'''simple docstring'''





					__UpperCAmelCase       :	int						=      '''RWKV/rwkv-4-169m-pile'''
					__UpperCAmelCase       :	Union[str, Any]						=      AutoTokenizer.from_pretrained(self.model_id					)




			def 					snake_case__	(  self				:					Optional[int]					):
					'''simple docstring'''





					__UpperCAmelCase       :	str						=      '''Hello my name is Jasmine and I am a newbie to the'''
					__UpperCAmelCase       :	str						=      RwkvForCausalLM.from_pretrained(self.model_id					).to(a_					)

					__UpperCAmelCase       :	Optional[int]						=      self.tokenizer('''Hello my name is'''			,			return_tensors='''pt'''					).input_ids.to(a_					)
					__UpperCAmelCase       :	Any						=      model.generate(a_			,			max_new_tokens=10					)
					__UpperCAmelCase       :	Any						=      self.tokenizer.decode(output[0].tolist()					)

					self.assertEqual(a_			,			a_					)




			def 					snake_case__	(  self				:					Optional[Any]					):
					'''simple docstring'''





					__UpperCAmelCase       :	Dict						=      '''Hello my name is Jasmine and I am a newbie to the'''

					__UpperCAmelCase       :	str						=      self.tokenizer('''Hello my name is'''			,			return_tensors='''pt'''					).input_ids.to(a_					)
					__UpperCAmelCase       :	List[str]						=      RwkvForCausalLM.from_pretrained(self.model_id			,			torch_dtype=torch.bfloataa					).to(a_					)

					__UpperCAmelCase       :	List[Any]						=      model.generate(a_			,			max_new_tokens=10					)
					__UpperCAmelCase       :	List[Any]						=      self.tokenizer.decode(output[0].tolist()					)

					self.assertEqual(a_			,			a_					)










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}'					)





