import importlib
import os
import platform
from pathlib import Path

from packaging import version

from .utils.logging import get_logger


_lowerCamelCase    :      Union[str, Any]	 =						get_logger(__name__)

# Datasets
_lowerCamelCase    :      Any	 =						'''https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets'''
_lowerCamelCase    :      Union[str, Any]	 =						'''https://cdn-datasets.huggingface.co/datasets/datasets'''
_lowerCamelCase    :      Optional[Any]	 =						'''https://raw.githubusercontent.com/huggingface/datasets/{revision}/datasets/{path}/{name}'''

# Metrics
_lowerCamelCase    :      Tuple	 =						'''https://s3.amazonaws.com/datasets.huggingface.co/datasets/metrics'''
_lowerCamelCase    :      int	 =						'''https://cdn-datasets.huggingface.co/datasets/metric'''
_lowerCamelCase    :      Dict	 =						'''https://raw.githubusercontent.com/huggingface/datasets/{revision}/metrics/{path}/{name}'''

# Hub
_lowerCamelCase    :      str	 =						os.environ.get('''HF_ENDPOINT''', '''https://huggingface.co''')
_lowerCamelCase    :      Optional[Any]	 =						HF_ENDPOINT + '''/datasets/{repo_id}/resolve/{revision}/{path}'''
_lowerCamelCase    :      Union[str, Any]	 =						'''main'''

_lowerCamelCase    :      Union[str, Any]	 =						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
_lowerCamelCase    :      Any	 =						{'''1''', '''ON''', '''YES''', '''TRUE'''}
_lowerCamelCase    :      int	 =						ENV_VARS_TRUE_VALUES.union({'''AUTO'''})


# Imports
_lowerCamelCase    :      Optional[int]	 =						version.parse(importlib_metadata.version('''dill'''))
_lowerCamelCase    :      Optional[Any]	 =						version.parse(importlib_metadata.version('''pandas'''))
_lowerCamelCase    :      Any	 =						version.parse(importlib_metadata.version('''pyarrow'''))

_lowerCamelCase    :      List[Any]	 =						os.environ.get('''USE_TF''', '''AUTO''').upper()
_lowerCamelCase    :      Optional[int]	 =						os.environ.get('''USE_TORCH''', '''AUTO''').upper()
_lowerCamelCase    :      Dict	 =						os.environ.get('''USE_JAX''', '''AUTO''').upper()

_lowerCamelCase    :      str	 =						'''N/A'''
_lowerCamelCase    :      Any	 =						False

if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
							_lowerCamelCase    :      Any	 =						importlib.util.find_spec('''torch''') is not None
							if TORCH_AVAILABLE:
														try:
																					_lowerCamelCase    :      List[str]	 =						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''')

_lowerCamelCase    :      List[str]	 =						'''N/A'''
_lowerCamelCase    :      List[str]	 =						False

if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
							_lowerCamelCase    :      str	 =						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:
																												_lowerCamelCase    :      List[Any]	 =						version.parse(importlib_metadata.version(package))
																					except importlib_metadata.PackageNotFoundError:
																												continue
																					else:
																												break
														else:
																					_lowerCamelCase    :      Dict	 =						False
							if TF_AVAILABLE:
														if TF_VERSION.major < 2:
																					logger.info(f"""TensorFlow found but with version {TF_VERSION}. `datasets` requires version 2 minimum.""")
																					_lowerCamelCase    :      List[str]	 =						False
														else:
																					logger.info(f"""TensorFlow version {TF_VERSION} available.""")
else:
							logger.info('''Disabling Tensorflow because USE_TORCH is set''')


_lowerCamelCase    :      Any	 =						'''N/A'''
_lowerCamelCase    :      Optional[int]	 =						False

if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
							_lowerCamelCase    :      int	 =						importlib.util.find_spec('''jax''') is not None and importlib.util.find_spec('''jaxlib''') is not None
							if JAX_AVAILABLE:
														try:
																					_lowerCamelCase    :      Dict	 =						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''')


_lowerCamelCase    :      Union[str, Any]	 =						os.environ.get('''USE_BEAM''', '''AUTO''').upper()
_lowerCamelCase    :      Dict	 =						'''N/A'''
_lowerCamelCase    :      Tuple	 =						False
if USE_BEAM in ENV_VARS_TRUE_AND_AUTO_VALUES:
							try:
														_lowerCamelCase    :      Tuple	 =						version.parse(importlib_metadata.version('''apache_beam'''))
														_lowerCamelCase    :      Optional[int]	 =						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
_lowerCamelCase    :      Union[str, Any]	 =						importlib.util.find_spec('''sqlalchemy''') is not None

# Optional tools for feature decoding
_lowerCamelCase    :      int	 =						importlib.util.find_spec('''PIL''') is not None
_lowerCamelCase    :      Optional[int]	 =						importlib.util.find_spec('''soundfile''') is not None and version.parse(
    importlib.import_module('''soundfile''').__libsndfile_version__
) >= version.parse('''1.0.31''')
_lowerCamelCase    :      Optional[Any]	 =						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
_lowerCamelCase    :      Union[str, Any]	 =						importlib.util.find_spec('''rarfile''') is not None
_lowerCamelCase    :      List[str]	 =						importlib.util.find_spec('''zstandard''') is not None
_lowerCamelCase    :      int	 =						importlib.util.find_spec('''lz4''') is not None
_lowerCamelCase    :      Optional[int]	 =						importlib.util.find_spec('''py7zr''') is not None


# Cache location
_lowerCamelCase    :      Tuple	 =						'''~/.cache'''
_lowerCamelCase    :      Any	 =						os.getenv('''XDG_CACHE_HOME''', DEFAULT_XDG_CACHE_HOME)
_lowerCamelCase    :      Dict	 =						os.path.join(XDG_CACHE_HOME, '''huggingface''')
_lowerCamelCase    :      Union[str, Any]	 =						os.path.expanduser(os.getenv('''HF_HOME''', DEFAULT_HF_CACHE_HOME))

_lowerCamelCase    :      Dict	 =						os.path.join(HF_CACHE_HOME, '''datasets''')
_lowerCamelCase    :      Dict	 =						Path(os.getenv('''HF_DATASETS_CACHE''', DEFAULT_HF_DATASETS_CACHE))

_lowerCamelCase    :      int	 =						os.path.join(HF_CACHE_HOME, '''metrics''')
_lowerCamelCase    :      Optional[Any]	 =						Path(os.getenv('''HF_METRICS_CACHE''', DEFAULT_HF_METRICS_CACHE))

_lowerCamelCase    :      List[str]	 =						os.path.join(HF_CACHE_HOME, '''modules''')
_lowerCamelCase    :      Optional[int]	 =						Path(os.getenv('''HF_MODULES_CACHE''', DEFAULT_HF_MODULES_CACHE))

_lowerCamelCase    :      Optional[Any]	 =						'''downloads'''
_lowerCamelCase    :      Any	 =						os.path.join(HF_DATASETS_CACHE, DOWNLOADED_DATASETS_DIR)
_lowerCamelCase    :      str	 =						Path(os.getenv('''HF_DATASETS_DOWNLOADED_DATASETS_PATH''', DEFAULT_DOWNLOADED_DATASETS_PATH))

_lowerCamelCase    :      str	 =						'''extracted'''
_lowerCamelCase    :      Optional[Any]	 =						os.path.join(DEFAULT_DOWNLOADED_DATASETS_PATH, EXTRACTED_DATASETS_DIR)
_lowerCamelCase    :      List[Any]	 =						Path(os.getenv('''HF_DATASETS_EXTRACTED_DATASETS_PATH''', DEFAULT_EXTRACTED_DATASETS_PATH))

# Download count for the website
_lowerCamelCase    :      int	 =						(
    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)
_lowerCamelCase    :      List[str]	 =						10_00

# Size of the preloaded record batch in `Dataset.__iter__`
_lowerCamelCase    :      Optional[Any]	 =						10

# Pickling tables works only for small tables (<4GiB)
# For big tables, we write them on disk instead
_lowerCamelCase    :      List[str]	 =						4 << 30

# Max shard size in bytes (e.g. to shard parquet datasets in push_to_hub or download_and_prepare)
_lowerCamelCase    :      List[Any]	 =						'''500MB'''

# Parquet configuration
_lowerCamelCase    :      int	 =						1_00
_lowerCamelCase    :      Union[str, Any]	 =						1_00
_lowerCamelCase    :      Optional[Any]	 =						1_00

# Offline mode
_lowerCamelCase    :      Tuple	 =						os.environ.get('''HF_DATASETS_OFFLINE''', '''AUTO''').upper() in ENV_VARS_TRUE_VALUES

# In-memory
_lowerCamelCase    :      str	 =						0  # Disabled
_lowerCamelCase    :      int	 =						float(os.environ.get('''HF_DATASETS_IN_MEMORY_MAX_SIZE''', DEFAULT_IN_MEMORY_MAX_SIZE))

# File names
_lowerCamelCase    :      Any	 =						'''dataset.arrow'''
_lowerCamelCase    :      Tuple	 =						'''indices.arrow'''
_lowerCamelCase    :      Optional[int]	 =						'''state.json'''
_lowerCamelCase    :      Tuple	 =						'''dataset_info.json'''
_lowerCamelCase    :      Dict	 =						'''dataset_infos.json'''
_lowerCamelCase    :      Optional[Any]	 =						'''LICENSE'''
_lowerCamelCase    :      List[Any]	 =						'''metric_info.json'''
_lowerCamelCase    :      Tuple	 =						'''dataset_dict.json'''

_lowerCamelCase    :      str	 =						'''datasets_modules'''

_lowerCamelCase    :      str	 =						2_55

# Streaming
_lowerCamelCase    :      List[Any]	 =						20
_lowerCamelCase    :      List[str]	 =						5

# Datasets without script
_lowerCamelCase    :      List[str]	 =						2_00
_lowerCamelCase    :      Optional[Any]	 =						10
_lowerCamelCase    :      Union[str, Any]	 =						2_00

# Progress bars
_lowerCamelCase    :      Union[str, Any]	 =						0.05  # 20 progress updates per sec





from sklearn.metrics import mean_absolute_error

import datasets


_lowerCamelCase    :      Any	 =						'''\
@article{scikit-learn,
 title={Scikit-learn: Machine Learning in {P}ython},
 author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
 journal={Journal of Machine Learning Research},
 volume={12},
 pages={2825--2830},
 year={2011}
}
'''

_lowerCamelCase    :      str	 =						'''\
Mean Absolute Error (MAE) is the mean of the magnitude of difference between the predicted and actual
values.
'''


_lowerCamelCase    :      List[str]	 =						'''
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

                 "raw_values" : Returns a full set of errors in case of multioutput input.

                 "uniform_average" : Errors of all outputs are averaged with uniform weight.

Returns:
    mae : mean absolute error.
        If multioutput is "raw_values", then mean absolute error is returned for each output separately. If multioutput is "uniform_average" or an ndarray of weights, then the weighted average of all output errors is returned.
        MAE output is non-negative floating point. The best value is 0.0.
Examples:

    >>> mae_metric = datasets.load_metric("mae")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mae\': 0.5}

    If you\'re using multi-dimensional lists, then set the config as follows :

    >>> mae_metric = datasets.load_metric("mae", "multilist")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mae\': 0.75}
    >>> results = mae_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')
    >>> print(results)
    {\'mae\': array([0.5, 1. ])}
'''


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




							def 		__snake_case(  self      :    int					)    -> str:



												'''simple docstring'''

												return datasets.MetricInfo(
												    description=_DESCRIPTION		,							citation=_CITATION		,							inputs_description=_KWARGS_DESCRIPTION		,							features=datasets.Features(self._get_feature_types()					)		,							reference_urls=[
												        "https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_absolute_error.html"
												    ]		,							)




							def 		__snake_case(  self      :    int					)    -> Tuple:



												'''simple docstring'''

												if self.config_name == "multilist":
																	return {
																	    "predictions": datasets.Sequence(datasets.Value("float"					)					),
																	    "references": datasets.Sequence(datasets.Value("float"					)					),
																	}
												else:
																	return {
																	    "predictions": datasets.Value("float"					),
																	    "references": datasets.Value("float"					),
																	}





							def 		__snake_case(  self      :    Tuple		,							_UpperCamelCase      :    List[str]		,							_UpperCamelCase      :    List[Any]		,							_UpperCamelCase      :    str=None		,							_UpperCamelCase      :    Any="uniform_average"					)    -> int:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				mean_absolute_error(_UpperCamelCase		,							_UpperCamelCase		,							sample_weight=_UpperCamelCase		,							multioutput=_UpperCamelCase					)

												return {"mae": mae_score}




