



import importlib
import os
import platform
from pathlib import Path

from packaging import version

from .utils.logging import get_logger


__A       =get_logger(__name__)

# Datasets
__A       ="https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets"
__A       ="https://cdn-datasets.huggingface.co/datasets/datasets"
__A       ="https://raw.githubusercontent.com/huggingface/datasets/{revision}/datasets/{path}/{name}"

# Metrics
__A       ="https://s3.amazonaws.com/datasets.huggingface.co/datasets/metrics"
__A       ="https://cdn-datasets.huggingface.co/datasets/metric"
__A       ="https://raw.githubusercontent.com/huggingface/datasets/{revision}/metrics/{path}/{name}"

# Hub
__A       =os.environ.get("HF_ENDPOINT", "https://huggingface.co")
__A       =HF_ENDPOINT + "/datasets/{repo_id}/resolve/{revision}/{path}"
__A       ="main"

__A       =version.parse(platform.python_version())

if PY_VERSION < version.parse("3.8"):
				import importlib_metadata
else:
				import importlib.metadata as importlib_metadata

# General environment variables accepted values for booleans
__A       ={"1", "ON", "YES", "TRUE"}
__A       =ENV_VARS_TRUE_VALUES.union({"AUTO"})


# Imports
__A       =version.parse(importlib_metadata.version("dill"))
__A       =version.parse(importlib_metadata.version("pandas"))
__A       =version.parse(importlib_metadata.version("pyarrow"))

__A       =os.environ.get("USE_TF", "AUTO").upper()
__A       =os.environ.get("USE_TORCH", "AUTO").upper()
__A       =os.environ.get("USE_JAX", "AUTO").upper()

__A       ="N/A"
__A       =False

if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
				__A       =importlib.util.find_spec("torch") is not None
				if TORCH_AVAILABLE:
								try:
												__A       =version.parse(importlib_metadata.version("torch"))
												logger.info(f'''PyTorch version {TORCH_VERSION} available.''')
								except importlib_metadata.PackageNotFoundError:
												pass
else:
				logger.info("Disabling PyTorch because USE_TF is set")

__A       ="N/A"
__A       =False

if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
				__A       =importlib.util.find_spec("tensorflow") is not None
				if TF_AVAILABLE:
								# For the metadata, we have to look for both tensorflow and tensorflow-cpu
								for package in [
								    "tensorflow",
								    "tensorflow-cpu",
								    "tensorflow-gpu",
								    "tf-nightly",
								    "tf-nightly-cpu",
								    "tf-nightly-gpu",
								    "intel-tensorflow",
								    "tensorflow-rocm",
								    "tensorflow-macos",
								]:
												try:
																__A       =version.parse(importlib_metadata.version(package))
												except importlib_metadata.PackageNotFoundError:
																continue
												else:
																break
								else:
												__A       =False
				if TF_AVAILABLE:
								if TF_VERSION.major < 2:
												logger.info(f'''TensorFlow found but with version {TF_VERSION}. `datasets` requires version 2 minimum.''')
												__A       =False
								else:
												logger.info(f'''TensorFlow version {TF_VERSION} available.''')
else:
				logger.info("Disabling Tensorflow because USE_TORCH is set")


__A       ="N/A"
__A       =False

if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
				__A       =importlib.util.find_spec("jax") is not None and importlib.util.find_spec("jaxlib") is not None
				if JAX_AVAILABLE:
								try:
												__A       =version.parse(importlib_metadata.version("jax"))
												logger.info(f'''JAX version {JAX_VERSION} available.''')
								except importlib_metadata.PackageNotFoundError:
												pass
else:
				logger.info("Disabling JAX because USE_JAX is set to False")


__A       =os.environ.get("USE_BEAM", "AUTO").upper()
__A       ="N/A"
__A       =False
if USE_BEAM in ENV_VARS_TRUE_AND_AUTO_VALUES:
				try:
								__A       =version.parse(importlib_metadata.version("apache_beam"))
								__A       =True
								logger.info(f'''Apache Beam version {BEAM_VERSION} available.''')
				except importlib_metadata.PackageNotFoundError:
								pass
else:
				logger.info("Disabling Apache Beam because USE_BEAM is set to False")


# Optional tools for data loading
__A       =importlib.util.find_spec("sqlalchemy") is not None

# Optional tools for feature decoding
__A       =importlib.util.find_spec("PIL") is not None
__A       =importlib.util.find_spec("soundfile") is not None and version.parse(
    importlib.import_module("soundfile").__libsndfile_version__
) >= version.parse("1.0.31")
__A       =importlib.util.find_spec("soundfile") is not None and version.parse(
    importlib.import_module("soundfile").__libsndfile_version__
) >= version.parse("1.1.0")

# Optional compression tools
__A       =importlib.util.find_spec("rarfile") is not None
__A       =importlib.util.find_spec("zstandard") is not None
__A       =importlib.util.find_spec("lz4") is not None
__A       =importlib.util.find_spec("py7zr") is not None


# Cache location
__A       ="~/.cache"
__A       =os.getenv("XDG_CACHE_HOME", DEFAULT_XDG_CACHE_HOME)
__A       =os.path.join(XDG_CACHE_HOME, "huggingface")
__A       =os.path.expanduser(os.getenv("HF_HOME", DEFAULT_HF_CACHE_HOME))

__A       =os.path.join(HF_CACHE_HOME, "datasets")
__A       =Path(os.getenv("HF_DATASETS_CACHE", DEFAULT_HF_DATASETS_CACHE))

__A       =os.path.join(HF_CACHE_HOME, "metrics")
__A       =Path(os.getenv("HF_METRICS_CACHE", DEFAULT_HF_METRICS_CACHE))

__A       =os.path.join(HF_CACHE_HOME, "modules")
__A       =Path(os.getenv("HF_MODULES_CACHE", DEFAULT_HF_MODULES_CACHE))

__A       ="downloads"
__A       =os.path.join(HF_DATASETS_CACHE, DOWNLOADED_DATASETS_DIR)
__A       =Path(os.getenv("HF_DATASETS_DOWNLOADED_DATASETS_PATH", DEFAULT_DOWNLOADED_DATASETS_PATH))

__A       ="extracted"
__A       =os.path.join(DEFAULT_DOWNLOADED_DATASETS_PATH, EXTRACTED_DATASETS_DIR)
__A       =Path(os.getenv("HF_DATASETS_EXTRACTED_DATASETS_PATH", DEFAULT_EXTRACTED_DATASETS_PATH))

# Download count for the website
__A       =(
    os.environ.get("HF_UPDATE_DOWNLOAD_COUNTS", "AUTO").upper() in ENV_VARS_TRUE_AND_AUTO_VALUES
)

# Batch size constants. For more info, see:
# https://github.com/apache/arrow/blob/master/docs/source/cpp/arrays.rst#size-limitations-and-recommendations)
__A       =1_0_0_0

# Size of the preloaded record batch in `Dataset.__iter__`
__A       =1_0

# Pickling tables works only for small tables (<4GiB)
# For big tables, we write them on disk instead
__A       =4 << 3_0

# Max shard size in bytes (e.g. to shard parquet datasets in push_to_hub or download_and_prepare)
__A       ="500MB"

# Parquet configuration
__A       =1_0_0
__A       =1_0_0
__A       =1_0_0

# Offline mode
__A       =os.environ.get("HF_DATASETS_OFFLINE", "AUTO").upper() in ENV_VARS_TRUE_VALUES

# In-memory
__A       =0  # Disabled
__A       =float(os.environ.get("HF_DATASETS_IN_MEMORY_MAX_SIZE", DEFAULT_IN_MEMORY_MAX_SIZE))

# File names
__A       ="dataset.arrow"
__A       ="indices.arrow"
__A       ="state.json"
__A       ="dataset_info.json"
__A       ="dataset_infos.json"
__A       ="LICENSE"
__A       ="metric_info.json"
__A       ="dataset_dict.json"

__A       ="datasets_modules"

__A       =2_5_5

# Streaming
__A       =2_0
__A       =5

# Datasets without script
__A       =2_0_0
__A       =1_0
__A       =2_0_0

# Progress bars
__A       =0.05  # 20 progress updates per sec










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





