



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

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

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

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

try:
			from jiwer import transforms as tr

			UpperCamelCase__			=    True
except ImportError:
			UpperCamelCase__			=    False

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






						"""simple docstring"""





						def __init__(					self						:							Union[str, Any]      ,  lowercase						:							str = " " )    ->       Optional[int]:
												"""simple docstring"""







												__lowercase											=					sentence_delimiter





						def 		snake_case__      (					self						:							List[str]      ,  lowercase						:							str )    ->       Any:
												"""simple docstring"""







												return list(lowercase )







						def 		snake_case__      (					self						:							Optional[int]      ,  lowercase						:							List[str] )    ->       List[Any]:
												"""simple docstring"""







												__lowercase											=					[]
												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





			UpperCamelCase__			=    tr.Compose(
			    [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
			)
elif _jiwer_available:
			UpperCamelCase__			=    tr.Compose(
			    [
			        tr.RemoveMultipleSpaces(),
			        tr.Strip(),
			        tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
			        tr.ReduceToListOfListOfChars(),
			    ]
			)
else:
			UpperCamelCase__			=    None






def 			UpperCAmelCase__     (     lowercase__    ,							lowercase__ )			->   Dict:
						return float((preds == labels).mean() )






def 			UpperCAmelCase__     (     lowercase__    ,							lowercase__ )			->   Optional[int]:
						return {
						    "f1": float(fa_score(y_true=lowercase__    ,							y_pred=lowercase__    ,							average="""macro""" ) ),
						    "accuracy": simple_accuracy(lowercase__    ,							lowercase__ ),
						}






def 			UpperCAmelCase__     (     lowercase__    ,							lowercase__    ,							lowercase__="exp"    ,							lowercase__=None    ,							lowercase__=False    ,							lowercase__=False    ,							lowercase__=None    ,							lowercase__=False    ,							)			->   int:
						# xtreme-s can only have one label
						__lowercase											=					[[label] for label in labels]
						__lowercase											=					list(lowercase__ )
						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\"`.""" )

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






def 			UpperCAmelCase__     (     lowercase__    ,							lowercase__    ,							lowercase__    ,							lowercase__ )			->   Dict:
						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:
												__lowercase											=					compute_measures(lowercase__    ,							lowercase__ )["""wer"""]

												__lowercase											=					compute_measures(lowercase__    ,							lowercase__    ,							truth_transform=lowercase__    ,							hypothesis_transform=lowercase__ )["""wer"""]
												return {"wer": wer, "cer": cer}
						else:

												def compute_score(lowercase__    ,							lowercase__    ,							lowercase__="wer" ):
																		__lowercase											=					0
																		__lowercase											=					0
																		for prediction, reference in zip(lowercase__    ,							lowercase__ ):
																								if score_type == "wer":
																														__lowercase											=					compute_measures(lowercase__    ,							lowercase__ )
																								elif score_type == "cer":
																														__lowercase											=					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

												return {"wer": compute_score(lowercase__    ,							lowercase__    ,							"""wer""" ), "cer": compute_score(lowercase__    ,							lowercase__    ,							"""cer""" )}







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






			"""simple docstring"""





			def 		snake_case__      (					self						:							str )    ->       Optional[Any]:
									"""simple docstring"""







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

									__lowercase											=					"""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(lowercase ), """references""": datasets.Value(lowercase )} )      ,  codebase_urls=[]      ,  reference_urls=[]      ,  format="""numpy"""      ,  )







			def 		snake_case__      (					self						:							Optional[Any]      ,  lowercase						:							Union[str, Any]      ,  lowercase						:							int      ,  lowercase						:							List[str]=None      ,  lowercase						:							int=None )    ->       Dict:
									"""simple docstring"""







									__lowercase											=					bleu_kwargs if bleu_kwargs is not None else {}
									__lowercase											=					wer_kwargs if wer_kwargs is not None else {}

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










# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


UpperCamelCase__			=    os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
UpperCamelCase__			=    os.path.join(hf_cache_home, "accelerate")
UpperCamelCase__			=    os.path.join(cache_dir, "default_config.yaml")
UpperCamelCase__			=    os.path.join(cache_dir, "default_config.yaml")

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
			UpperCamelCase__			=    default_yaml_config_file
else:
			UpperCamelCase__			=    default_json_config_file






def 			UpperCAmelCase__     (     lowercase__ )			->   int:
						if config_file is not None:
												if not os.path.isfile(lowercase__ ):
																		raise FileNotFoundError(
																		    F"The passed configuration file `{config_file}` does not exist. "
																		    """Please pass an existing file to `accelerate launch`, or use the the default one """
																		    """created through `accelerate config` and run `accelerate launch` """
																		    """without the `--config_file` argument.""" )
						else:
												__lowercase											=					default_config_file
						with open(lowercase__    ,							"""r"""    ,							encoding="""utf-8""" ) as f:
												if config_file.endswith(""".json""" ):
																		if (
																		    json.load(lowercase__ ).get("""compute_environment"""    ,							ComputeEnvironment.LOCAL_MACHINE )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								__lowercase											=					ClusterConfig
																		else:
																								__lowercase											=					SageMakerConfig
																		return config_class.from_json_file(json_file=lowercase__ )
												else:
																		if (
																		    yaml.safe_load(lowercase__ ).get("""compute_environment"""    ,							ComputeEnvironment.LOCAL_MACHINE )
																		    == ComputeEnvironment.LOCAL_MACHINE
																		):
																								__lowercase											=					ClusterConfig
																		else:
																								__lowercase											=					SageMakerConfig
																		return config_class.from_yaml_file(yaml_file=lowercase__ )
@dataclass
class       _lowerCAmelCase :






			"""simple docstring"""





			lowercase__   :	ComputeEnvironment
			lowercase__   :	Union[DistributedType, SageMakerDistributedType]
			lowercase__   :	str
			lowercase__   :	bool





			def 		snake_case__      (					self						:							Union[str, Any] )    ->       List[Any]:
									"""simple docstring"""







									__lowercase											=					self.__dict__
									# For serialization, it's best to convert Enums to strings (or their underlying value type).
									for key, value in result.items():
															if isinstance(lowercase      ,  lowercase ):
																					__lowercase											=					value.value
															if isinstance(lowercase      ,  lowercase ) and not bool(lowercase ):
																					__lowercase											=					None
									__lowercase											=					{k: v for k, v in result.items() if v is not None}
									return result





			@classmethod
			def 		snake_case__      (					cls						:							List[str]      ,  lowercase						:							List[str]=None )    ->       Union[str, Any]:
									"""simple docstring"""







									__lowercase											=					default_json_config_file if json_file is None else json_file
									with open(lowercase      ,  """r"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					json.load(lowercase )
									if "compute_environment" not in config_dict:
															__lowercase											=					ComputeEnvironment.LOCAL_MACHINE
									if "mixed_precision" not in config_dict:
															__lowercase											=					"""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
									if "fp16" in config_dict:  # Convert the config to the new format.
															del config_dict["fp16"]
									if "dynamo_backend" in config_dict:  # Convert the config to the new format.
															__lowercase											=					config_dict.pop("""dynamo_backend""" )
															__lowercase											=					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
									if "use_cpu" not in config_dict:
															__lowercase											=					False
									return cls(**lowercase )





			def 		snake_case__      (					self						:							Tuple      ,  lowercase						:							str )    ->       Any:
									"""simple docstring"""







									with open(lowercase      ,  """w"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					json.dumps(self.to_dict()      ,  indent=2      ,  sort_keys=lowercase ) + """\n"""
															f.write(lowercase )





			@classmethod
			def 		snake_case__      (					cls						:							List[str]      ,  lowercase						:							Optional[Any]=None )    ->       Union[str, Any]:
									"""simple docstring"""







									__lowercase											=					default_yaml_config_file if yaml_file is None else yaml_file
									with open(lowercase      ,  """r"""      ,  encoding="""utf-8""" ) as f:
															__lowercase											=					yaml.safe_load(lowercase )
									if "compute_environment" not in config_dict:
															__lowercase											=					ComputeEnvironment.LOCAL_MACHINE

									if "mixed_precision" not in config_dict:
															__lowercase											=					"""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
									if isinstance(config_dict["""mixed_precision"""]      ,  lowercase ) and not config_dict["mixed_precision"]:
															__lowercase											=					"""no"""
									if "fp16" in config_dict:  # Convert the config to the new format.
															del config_dict["fp16"]
									if "dynamo_backend" in config_dict:  # Convert the config to the new format.
															__lowercase											=					config_dict.pop("""dynamo_backend""" )
															__lowercase											=					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
									if "use_cpu" not in config_dict:
															__lowercase											=					False
									return cls(**lowercase )





			def 		snake_case__      (					self						:							Union[str, Any]      ,  lowercase						:							Any )    ->       Tuple:
									"""simple docstring"""







									with open(lowercase      ,  """w"""      ,  encoding="""utf-8""" ) as f:
															yaml.safe_dump(self.to_dict()      ,  lowercase )







			def 		snake_case__      (					self						:							int )    ->       Optional[int]:
									"""simple docstring"""







									if isinstance(self.compute_environment      ,  lowercase ):
															__lowercase											=					ComputeEnvironment(self.compute_environment )
									if isinstance(self.distributed_type      ,  lowercase ):
															if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																					__lowercase											=					SageMakerDistributedType(self.distributed_type )
															else:
																					__lowercase											=					DistributedType(self.distributed_type )
									if self.dynamo_config is None:
															__lowercase											=					{}





@dataclass
class       _lowerCAmelCase (			_UpperCAmelCase      ):






			"""simple docstring"""





			lowercase__   :	int
			lowercase__   :	int  			=      0
			lowercase__   :	int  			=      1
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[int]  			=      None
			lowercase__   :	Optional[str]  			=      "static"
			lowercase__   :	Optional[bool]  			=      False
			lowercase__   :	str  			=      "main"

			# args for deepspeed_plugin
			lowercase__   :	dict  			=      None
			# args for fsdp
			lowercase__   :	dict  			=      None
			# args for megatron_lm
			lowercase__   :	dict  			=      None
			# args for ipex
			lowercase__   :	dict  			=      None
			# args for TPU
			lowercase__   :	bool  			=      False

			# args for TPU pods
			lowercase__   :	str  			=      None
			lowercase__   :	str  			=      None
			lowercase__   :	bool  			=      False
			lowercase__   :	bool  			=      False
			lowercase__   :	str  			=      None
			lowercase__   :	List[str]  			=      None
			lowercase__   :	List[str]  			=      None
			lowercase__   :	List[str]  			=      None

			# args for dynamo
			lowercase__   :	dict  			=      None





			def 		snake_case__      (					self						:							List[Any] )    ->       int:
									"""simple docstring"""







									if self.deepspeed_config is None:
															__lowercase											=					{}
									if self.fsdp_config is None:
															__lowercase											=					{}
									if self.megatron_lm_config is None:
															__lowercase											=					{}
									if self.ipex_config is None:
															__lowercase											=					{}
									return super().__post_init__()





@dataclass
class       _lowerCAmelCase (			_UpperCAmelCase      ):






			"""simple docstring"""





			lowercase__   :	str
			lowercase__   :	str
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	Optional[str]  			=      None
			lowercase__   :	str  			=      "us-east-1"
			lowercase__   :	int  			=      1
			lowercase__   :	str  			=      "all"
			lowercase__   :	str  			=      F'''accelerate-sagemaker-{num_machines}'''
			lowercase__   :	str  			=      SAGEMAKER_PYTORCH_VERSION
			lowercase__   :	str  			=      SAGEMAKER_TRANSFORMERS_VERSION
			lowercase__   :	str  			=      SAGEMAKER_PYTHON_VERSION
			lowercase__   :	str  			=      None
			lowercase__   :	str  			=      None
			lowercase__   :	dict  			=      None
			lowercase__   :	dict  			=      None





