
"""simple docstring"""



import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


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


def  _UpperCamelCase	(						_A					,      _A=False      )    ->  str:





    """simple docstring"""

    try:
        _UpperCAmelCase          =   os.environ[key]
    except KeyError:
        # KEY isn't set, default to `default`.
        _UpperCAmelCase          =   default
    else:
        # KEY is set, convert it to True or False.
        try:
            _UpperCAmelCase          =   strtobool(_A      )
        except ValueError:
            # More values are supported, but let's keep the message simple.
            raise ValueError(F"""If set, {key} must be yes or no."""      )
    return _value


a					:	Union[str, Any]							=		parse_flag_from_env('''RUN_SLOW''', default=False)
a					:	Tuple							=		parse_flag_from_env('''RUN_REMOTE''', default=False)
a					:	Union[str, Any]							=		parse_flag_from_env('''RUN_LOCAL''', default=True)
a					:	int							=		parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
a					:	List[Any]							=		pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
a					:	List[Any]							=		pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
a					:	Optional[Any]							=		pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
a					:	int							=		pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('''soundfile''') is None or version.parse(importlib_metadata.version('''soundfile''')) < version.parse('''0.12.0'''),
    reason='''test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ''',
)

# Beam
a					:	Tuple							=		pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('''0.3.2'''),
    reason='''test requires apache-beam and a compatible dill version''',
)

# Dill-cloudpickle compatibility
a					:	Any							=		pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

# Windows
a					:	int							=		pytest.mark.skipif(
    sys.platform == '''win32''',
    reason='''test should not be run on Windows''',
)


def  _UpperCamelCase	(						_A      )    ->  str:





    """simple docstring"""

    try:
        import faiss  # noqa
    except ImportError:
        _UpperCAmelCase          =   unittest.skip("""test requires faiss"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						_A      )    ->  Any:





    """simple docstring"""

    try:
        import regex  # noqa
    except ImportError:
        _UpperCAmelCase          =   unittest.skip("""test requires regex"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						_A      )    ->  Union[str, Any]:





    """simple docstring"""

    try:
        import elasticsearch  # noqa
    except ImportError:
        _UpperCAmelCase          =   unittest.skip("""test requires elasticsearch"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						_A      )    ->  Dict:





    """simple docstring"""

    try:
        import sqlalchemy  # noqa
    except ImportError:
        _UpperCAmelCase          =   unittest.skip("""test requires sqlalchemy"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						_A      )    ->  Union[str, Any]:





    """simple docstring"""

    if not config.TORCH_AVAILABLE:
        _UpperCAmelCase          =   unittest.skip("""test requires PyTorch"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						_A      )    ->  Optional[Any]:





    """simple docstring"""

    if not config.TF_AVAILABLE:
        _UpperCAmelCase          =   unittest.skip("""test requires TensorFlow"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						_A      )    ->  str:





    """simple docstring"""

    if not config.JAX_AVAILABLE:
        _UpperCAmelCase          =   unittest.skip("""test requires JAX"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						_A      )    ->  Dict:





    """simple docstring"""

    if not config.PIL_AVAILABLE:
        _UpperCAmelCase          =   unittest.skip("""test requires Pillow"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						_A      )    ->  str:





    """simple docstring"""

    try:
        import transformers  # noqa F401
    except ImportError:
        return unittest.skip("""test requires transformers"""      )(_A      )
    else:
        return test_case


def  _UpperCamelCase	(						_A      )    ->  List[Any]:





    """simple docstring"""

    try:
        import tiktoken  # noqa F401
    except ImportError:
        return unittest.skip("""test requires tiktoken"""      )(_A      )
    else:
        return test_case


def  _UpperCamelCase	(						_A      )    ->  Optional[int]:





    """simple docstring"""

    try:
        import spacy  # noqa F401
    except ImportError:
        return unittest.skip("""test requires spacy"""      )(_A      )
    else:
        return test_case


def  _UpperCamelCase	(						_A      )    ->  int:





    """simple docstring"""

    def _require_spacy_model(_A      ):
        try:
            import spacy  # noqa F401

            spacy.load(_A      )
        except ImportError:
            return unittest.skip("""test requires spacy"""      )(_A      )
        except OSError:
            return unittest.skip("""test requires spacy model '{}'""".format(_A      )      )(_A      )
        else:
            return test_case

    return _require_spacy_model


def  _UpperCamelCase	(						_A      )    ->  Optional[int]:





    """simple docstring"""

    try:
        import pyspark  # noqa F401
    except ImportError:
        return unittest.skip("""test requires pyspark"""      )(_A      )
    else:
        return test_case


def  _UpperCamelCase	(						_A      )    ->  List[Any]:





    """simple docstring"""

    try:
        import joblibspark  # noqa F401
    except ImportError:
        return unittest.skip("""test requires joblibspark"""      )(_A      )
    else:
        return test_case


def  _UpperCamelCase	(						_A      )    ->  Any:





    """simple docstring"""

    if not _run_slow_tests or _run_slow_tests == 0:
        _UpperCAmelCase          =   unittest.skip("""test is slow"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						_A      )    ->  Any:





    """simple docstring"""

    if not _run_local_tests or _run_local_tests == 0:
        _UpperCAmelCase          =   unittest.skip("""test is local"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						_A      )    ->  Optional[int]:





    """simple docstring"""

    if not _run_packaged_tests or _run_packaged_tests == 0:
        _UpperCAmelCase          =   unittest.skip("""test is packaged"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						_A      )    ->  Dict:





    """simple docstring"""

    if not _run_remote_tests or _run_remote_tests == 0:
        _UpperCAmelCase          =   unittest.skip("""test requires remote"""      )(_A      )
    return test_case


def  _UpperCamelCase	(						*_A      )    ->  Dict:





    """simple docstring"""

    def decorate(cls      ):
        for name, fn in cls.__dict__.items():
            if callable(_A      ) and name.startswith("""test"""      ):
                for decorator in decorators:
                    _UpperCAmelCase          =   decorator(_A      )
                setattr(cls					,      _A					,      _A      )
        return cls

    return decorate




class 		a_						( _UpperCAmelCase	):
    pass







class 		a_						( _UpperCAmelCase	):
    a      :				Any     =				0
    a      :				Optional[Any]     =				1
    a      :				int     =				2







@contextmanager
def  _UpperCamelCase	(						_A=OfflineSimulationMode.CONNECTION_FAILS					,      _A=1e-16      )    ->  List[Any]:





    """simple docstring"""

    _UpperCAmelCase          =   requests.Session().request

    def timeout_request(_A					,      _A					,      _A					,      **_A      ):
        # Change the url to an invalid url so that the connection hangs
        _UpperCAmelCase          =   """https://10.255.255.1"""
        if kwargs.get("""timeout"""      ) is None:
            raise RequestWouldHangIndefinitelyError(
                F"""Tried a call to {url} in offline mode with no timeout set. Please set a timeout."""      )
        _UpperCAmelCase          =   timeout
        try:
            return online_request(_A					,      _A					,      **_A      )
        except Exception as e:
            # The following changes in the error are just here to make the offline timeout error prettier
            _UpperCAmelCase          =   url
            _UpperCAmelCase          =   e.args[0]
            _UpperCAmelCase          =   (max_retry_error.args[0].replace("""10.255.255.1"""					,      F"""OfflineMock[{url}]"""      ),)
            _UpperCAmelCase          =   (max_retry_error,)
            raise

    def raise_connection_error(_A					,      _A					,      **_A      ):
        raise requests.ConnectionError("""Offline mode is enabled."""					,      request=_A      )

    if mode is OfflineSimulationMode.CONNECTION_FAILS:
        with patch("""requests.Session.send"""					,      _A      ):
            yield
    elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
        # inspired from https://stackoverflow.com/a/904609
        with patch("""requests.Session.request"""					,      _A      ):
            yield
    elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
        with patch("""datasets.config.HF_DATASETS_OFFLINE"""					,      _A      ):
            yield
    else:
        raise ValueError("""Please use a value from the OfflineSimulationMode enum."""      )


@contextmanager
def  _UpperCamelCase	(						*_A					,      **_A      )    ->  str:





    """simple docstring"""

    _UpperCAmelCase          =   str(Path().resolve()      )
    with tempfile.TemporaryDirectory(*_A					,      **_A      ) as tmp_dir:
        try:
            os.chdir(_A      )
            yield
        finally:
            os.chdir(_A      )


@contextmanager
def  _UpperCamelCase	(						)    ->  Any:





    """simple docstring"""

    import gc

    gc.collect()
    _UpperCAmelCase          =   pa.total_allocated_bytes()
    yield
    assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."


@contextmanager
def  _UpperCamelCase	(						)    ->  Union[str, Any]:





    """simple docstring"""

    import gc

    gc.collect()
    _UpperCAmelCase          =   pa.total_allocated_bytes()
    yield
    assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."


def  _UpperCamelCase	(						_A					,      _A      )    ->  str:





    """simple docstring"""

    return deepcopy(_A      ).integers(0					,      1_0_0					,      1_0      ).tolist() == deepcopy(_A      ).integers(0					,      1_0_0					,      1_0      ).tolist()


def  _UpperCamelCase	(						_A      )    ->  Tuple:





    """simple docstring"""

    import decorator
    from requests.exceptions import HTTPError

    def _wrapper(_A					,      *_A					,      **_A      ):
        try:
            return func(*_A					,      **_A      )
        except HTTPError as err:
            if str(_A      ).startswith("""500"""      ) or str(_A      ).startswith("""502"""      ):
                pytest.xfail(str(_A      )      )
            raise err

    return decorator.decorator(_wrapper					,      _A      )




class 		a_						:







    def __init__(			self			:       int     ,					__UpperCamelCase			:       List[Any]     ,					__UpperCamelCase			:       Union[str, Any]     ,					__UpperCamelCase			:       List[str]     )		->int:






        '''simple docstring'''






        _UpperCAmelCase          =   returncode
        _UpperCAmelCase          =   stdout
        _UpperCAmelCase          =   stderr







async def  _UpperCamelCase	(						_A					,      _A      )    ->  Union[str, Any]:





    """simple docstring"""

    while True:
        _UpperCAmelCase          =   await stream.readline()
        if line:
            callback(_A      )
        else:
            break


async def  _UpperCamelCase	(						_A					,      _A=None					,      _A=None					,      _A=None					,      _A=False					,      _A=False      )    ->  _RunOutput:





    """simple docstring"""

    if echo:
        print("""\nRunning: """					,      """ """.join(_A      )      )

    _UpperCAmelCase          =   await asyncio.create_subprocess_exec(
        cmd[0]					,      *cmd[1:]					,      stdin=_A					,      stdout=asyncio.subprocess.PIPE					,      stderr=asyncio.subprocess.PIPE					,      env=_A					,      )

    # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
    # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
    #
    # If it starts hanging, will need to switch to the following code. The problem is that no data
    # will be seen until it's done and if it hangs for example there will be no debug info.
    # out, err = await p.communicate()
    # return _RunOutput(p.returncode, out, err)

    _UpperCAmelCase          =   []
    _UpperCAmelCase          =   []

    def tee(_A					,      _A					,      _A					,      _A=""      ):
        _UpperCAmelCase          =   line.decode("""utf-8"""      ).rstrip()
        sink.append(_A      )
        if not quiet:
            print(_A					,      _A					,      file=_A      )

    # XXX: the timeout doesn't seem to make any difference here
    await asyncio.wait(
        [
            _read_stream(p.stdout					,      lambda _A      : tee(_A					,      _A					,      sys.stdout					,      label="""stdout:"""      )      ),
            _read_stream(p.stderr					,      lambda _A      : tee(_A					,      _A					,      sys.stderr					,      label="""stderr:"""      )      ),
        ]					,      timeout=_A					,      )
    return _RunOutput(await p.wait()					,      _A					,      _A      )


def  _UpperCamelCase	(						_A					,      _A=None					,      _A=None					,      _A=1_8_0					,      _A=False					,      _A=True      )    ->  _RunOutput:





    """simple docstring"""

    _UpperCAmelCase          =   asyncio.get_event_loop()
    _UpperCAmelCase          =   loop.run_until_complete(
        _stream_subprocess(_A					,      env=_A					,      stdin=_A					,      timeout=_A					,      quiet=_A					,      echo=_A      )      )

    _UpperCAmelCase          =   """ """.join(_A      )
    if result.returncode > 0:
        _UpperCAmelCase          =   """\n""".join(result.stderr      )
        raise RuntimeError(
            F"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
            F"""The combined stderr from workers follows:\n{stderr}"""      )

    # check that the subprocess actually did run and produced some output, should the test rely on
    # the remote side to do the testing
    if not result.stdout and not result.stderr:
        raise RuntimeError(F"""'{cmd_str}' produced no output."""      )

    return result


def  _UpperCamelCase	(						)    ->  Tuple:





    """simple docstring"""

    _UpperCAmelCase          =   os.environ.get("""PYTEST_XDIST_WORKER"""					,      """gw0"""      )
    _UpperCAmelCase          =   re.sub(R"""^gw"""					,      """"""					,      _A					,      0					,      re.M      )
    return int(_A      )







def  _UpperCamelCase	(						)    ->  Tuple:





    """simple docstring"""

    _UpperCAmelCase          =   2_9_5_0_0
    _UpperCAmelCase          =   pytest_xdist_worker_id()
    return port + uniq_delta

"""simple docstring"""



import itertools
import os
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed

import numpy as np

import datasets

from .execute import check_correctness


a					:	Optional[Any]							=		'''\
@misc{chen2021evaluating,
      title={Evaluating Large Language Models Trained on Code},
      author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \
and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \
and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \
and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \
and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \
and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \
and Mohammad Bavarian and Clemens Winter and Philippe Tillet \
and Felipe Petroski Such and Dave Cummings and Matthias Plappert \
and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \
and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \
and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \
and William Saunders and Christopher Hesse and Andrew N. Carr \
and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \
and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \
and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \
and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},
      year={2021},
      eprint={2107.03374},
      archivePrefix={arXiv},
      primaryClass={cs.LG}
}
'''

a					:	List[str]							=		'''\
This metric implements the evaluation harness for the HumanEval problem solving dataset
described in the paper "Evaluating Large Language Models Trained on Code"
(https://arxiv.org/abs/2107.03374).
'''


a					:	Any							=		'''
Calculates how good are predictions given some references, using certain scores
Args:
    predictions: list of candidates to evaluate. Each candidates should be a list
        of strings with several code candidates to solve the problem.
    references: a list with a test for each prediction. Each test should evaluate the
        correctness of a code candidate.
    k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])
    num_workers: number of workers used to evaluate the canidate programs (Default: 4).
    timeout:
Returns:
    pass_at_k: dict with pass rates for each k
    results: dict with granular results of each unittest
Examples:
    >>> code_eval = datasets.load_metric("code_eval")
    >>> test_cases = ["assert add(2,3)==5"]
    >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]
    >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])
    >>> print(pass_at_k)
    {\'pass@1\': 0.5, \'pass@2\': 1.0}
'''


a					:	int							=		'''
################################################################################
                                  !!!WARNING!!!
################################################################################
The "code_eval" metric executes untrusted model-generated code in Python.
Although it is highly unlikely that model-generated code will do something
overtly malicious in response to this test suite, model-generated code may act
destructively due to a lack of model capability or alignment.
Users are strongly encouraged to sandbox this evaluation suite so that it
does not perform destructive actions on their host or network. For more
information on how OpenAI sandboxes its code, see the paper "Evaluating Large
Language Models Trained on Code" (https://arxiv.org/abs/2107.03374).

Once you have read this disclaimer and taken appropriate precautions,
set the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this
with:

>>> import os
>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"

################################################################################\
'''

a					:	List[Any]							=		'''The MIT License

Copyright (c) OpenAI (https://openai.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.'''




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







    def      _snake_case					(			self			:       Tuple     )		->Tuple:






        '''simple docstring'''






        return datasets.MetricInfo(
            # This is the description that will appear on the metrics page.
            description=_DESCRIPTION     ,					citation=_CITATION     ,					inputs_description=_KWARGS_DESCRIPTION     ,					features=datasets.Features(
                {
                    """predictions""": datasets.Sequence(datasets.Value("""string"""     )     ),
                    """references""": datasets.Value("""string"""     ),
                }     )     ,					homepage="""https://github.com/openai/human-eval"""     ,					codebase_urls=["""https://github.com/openai/human-eval"""]     ,					reference_urls=["""https://github.com/openai/human-eval"""]     ,					license=_LICENSE     ,					)







    def      _snake_case					(			self			:       Optional[Any]     ,					__UpperCamelCase			:       Dict     ,					__UpperCamelCase			:       Union[str, Any]     ,					__UpperCamelCase			:       List[Any]=[1, 10, 1_00]     ,					__UpperCamelCase			:       Dict=4     ,					__UpperCamelCase			:       Tuple=3.0     )		->Union[str, Any]:






        '''simple docstring'''






        if os.getenv("""HF_ALLOW_CODE_EVAL"""     ,					0     ) != "1":
            raise ValueError(_WARNING     )

        if os.name == "nt":
            raise NotImplementedError("""This metric is currently not supported on Windows."""     )

        with ThreadPoolExecutor(max_workers=__UpperCamelCase     ) as executor:
            _UpperCAmelCase          =   []
            _UpperCAmelCase          =   Counter()
            _UpperCAmelCase          =   0
            _UpperCAmelCase          =   defaultdict(__UpperCamelCase     )

            for task_id, (candidates, test_case) in enumerate(zip(__UpperCamelCase     ,					__UpperCamelCase     )     ):
                for candidate in candidates:
                    _UpperCAmelCase          =   candidate + """\n""" + test_case
                    _UpperCAmelCase          =   (test_program, timeout, task_id, completion_id[task_id])
                    _UpperCAmelCase          =   executor.submit(__UpperCamelCase     ,					*__UpperCamelCase     )
                    futures.append(__UpperCamelCase     )
                    completion_id[task_id] += 1
                    n_samples += 1

            for future in as_completed(__UpperCamelCase     ):
                _UpperCAmelCase          =   future.result()
                results[result["task_id"]].append((result["""completion_id"""], result)     )

        _UpperCAmelCase    ,_UpperCAmelCase          =   [], []
        for result in results.values():
            result.sort()
            _UpperCAmelCase          =   [r[1]["""passed"""] for r in result]
            total.append(len(__UpperCamelCase     )     )
            correct.append(sum(__UpperCamelCase     )     )
        _UpperCAmelCase          =   np.array(__UpperCamelCase     )
        _UpperCAmelCase          =   np.array(__UpperCamelCase     )

        _UpperCAmelCase          =   k
        _UpperCAmelCase          =   {f"""pass@{k}""": estimate_pass_at_k(__UpperCamelCase     ,					__UpperCamelCase     ,					__UpperCamelCase     ).mean() for k in ks if (total >= k).all()}

        return pass_at_k, results







def  _UpperCamelCase	(						_A					,      _A					,      _A      )    ->  Dict:





    """simple docstring"""

    def estimator(_A					,      _A					,      _A      ) -> float:
        if n - c < k:
            return 1.0
        return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1					,      n + 1      )      )

    if isinstance(_A					,      _A      ):
        _UpperCAmelCase          =   itertools.repeat(_A					,      len(_A      )      )
    else:
        assert len(_A      ) == len(_A      )
        _UpperCAmelCase          =   iter(_A      )

    return np.array([estimator(int(_A      )					,      int(_A      )					,      _A      ) for n, c in zip(_A					,      _A      )]      )