'''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	(       UpperCAmelCase		,					UpperCAmelCase=False					):
 try:
  lowercase__    :   Dict						= os.environ[key]
 except KeyError:
  # KEY isn't set, default to `default`.
  lowercase__    :   List[Any]						= default
 else:
  # KEY is set, convert it to True or False.
  try:
   lowercase__    :   int						= strtobool(UpperCAmelCase					)
  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:			Dict	       =       parse_flag_from_env("""RUN_SLOW""", default=False)
__a:			Dict	       =       parse_flag_from_env("""RUN_REMOTE""", default=False)
__a:			Optional[Any]	       =       parse_flag_from_env("""RUN_LOCAL""", default=True)
__a:			Union[str, Any]	       =       parse_flag_from_env("""RUN_PACKAGED""", default=True)

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

# Audio
__a:			Optional[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:			List[str]	       =       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:			List[str]	       =       pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("""0.3.2"""),
    reason="""test requires dill>0.3.2 for cloudpickle compatibility""",
)

# Windows
__a:			Any	       =       pytest.mark.skipif(
    sys.platform == """win32""",
    reason="""test should not be run on Windows""",
)
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import faiss  # noqa
 except ImportError:
  lowercase__    :   Any						= unittest.skip('''test requires faiss'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import regex  # noqa
 except ImportError:
  lowercase__    :   Optional[int]						= unittest.skip('''test requires regex'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import elasticsearch  # noqa
 except ImportError:
  lowercase__    :   List[str]						= unittest.skip('''test requires elasticsearch'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import sqlalchemy  # noqa
 except ImportError:
  lowercase__    :   Union[str, Any]						= unittest.skip('''test requires sqlalchemy'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not config.TORCH_AVAILABLE:
  lowercase__    :   Optional[Any]						= unittest.skip('''test requires PyTorch'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not config.TF_AVAILABLE:
  lowercase__    :   Any						= unittest.skip('''test requires TensorFlow'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not config.JAX_AVAILABLE:
  lowercase__    :   int						= unittest.skip('''test requires JAX'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not config.PIL_AVAILABLE:
  lowercase__    :   Any						= unittest.skip('''test requires Pillow'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import transformers  # noqa F401
 except ImportError:
  return unittest.skip('''test requires transformers'''					)(UpperCAmelCase					)
 else:
  return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import tiktoken  # noqa F401
 except ImportError:
  return unittest.skip('''test requires tiktoken'''					)(UpperCAmelCase					)
 else:
  return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import spacy  # noqa F401
 except ImportError:
  return unittest.skip('''test requires spacy'''					)(UpperCAmelCase					)
 else:
  return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):

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

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

 return _require_spacy_model
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import pyspark  # noqa F401
 except ImportError:
  return unittest.skip('''test requires pyspark'''					)(UpperCAmelCase					)
 else:
  return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import joblibspark  # noqa F401
 except ImportError:
  return unittest.skip('''test requires joblibspark'''					)(UpperCAmelCase					)
 else:
  return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not _run_slow_tests or _run_slow_tests == 0:
  lowercase__    :   int						= unittest.skip('''test is slow'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not _run_local_tests or _run_local_tests == 0:
  lowercase__    :   Optional[int]						= unittest.skip('''test is local'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not _run_packaged_tests or _run_packaged_tests == 0:
  lowercase__    :   Dict						= unittest.skip('''test is packaged'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not _run_remote_tests or _run_remote_tests == 0:
  lowercase__    :   Dict						= unittest.skip('''test requires remote'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       *UpperCAmelCase					):
 def decorate(cls					):
  for name, fn in cls.__dict__.items():
   if callable(UpperCAmelCase					) and name.startswith('''test'''					):
    for decorator in decorators:
     lowercase__    :   List[Any]						= decorator(UpperCAmelCase					)
    setattr(cls		,					UpperCAmelCase		,					UpperCAmelCase					)
  return cls

 return decorate



class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       pass



class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   0
       SCREAMING_SNAKE_CASE 		=   1
       SCREAMING_SNAKE_CASE 		=   2


@contextmanager
def       __UpperCamelCase	(       UpperCAmelCase=OfflineSimulationMode.CONNECTION_FAILS		,					UpperCAmelCase=1E-16					):
 lowercase__    :   str						= requests.Session().request

 def timeout_request(UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase		,					**UpperCAmelCase					):
  # Change the url to an invalid url so that the connection hangs
  lowercase__    :   int						= '''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."""					)
  lowercase__    :   List[str]						= timeout
  try:
   return online_request(UpperCAmelCase		,					UpperCAmelCase		,					**UpperCAmelCase					)
  except Exception as e:
   # The following changes in the error are just here to make the offline timeout error prettier
   lowercase__    :   Dict						= url
   lowercase__    :   Union[str, Any]						= e.args[0]
   lowercase__    :   Union[str, Any]						= (max_retry_error.args[0].replace('''10.255.255.1'''		,					F"""OfflineMock[{url}]"""					),)
   lowercase__    :   List[str]						= (max_retry_error,)
   raise

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

 if mode is OfflineSimulationMode.CONNECTION_FAILS:
  with patch('''requests.Session.send'''		,					UpperCAmelCase					):
   yield
 elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
  # inspired from https://stackoverflow.com/a/904609
  with patch('''requests.Session.request'''		,					UpperCAmelCase					):
   yield
 elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
  with patch('''datasets.config.HF_DATASETS_OFFLINE'''		,					UpperCAmelCase					):
   yield
 else:
  raise ValueError('''Please use a value from the OfflineSimulationMode enum.'''					)
@contextmanager
def       __UpperCamelCase	(       *UpperCAmelCase		,					**UpperCAmelCase					):
 lowercase__    :   Optional[int]						= str(Path().resolve()					)
 with tempfile.TemporaryDirectory(*UpperCAmelCase		,					**UpperCAmelCase					) as tmp_dir:
  try:
   os.chdir(UpperCAmelCase					)
   yield
  finally:
   os.chdir(UpperCAmelCase					)
@contextmanager
def       __UpperCamelCase	(       ):
 import gc

 gc.collect()
 lowercase__    :   Tuple						= pa.total_allocated_bytes()
 yield
 assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."
@contextmanager
def       __UpperCamelCase	(       ):
 import gc

 gc.collect()
 lowercase__    :   Optional[int]						= pa.total_allocated_bytes()
 yield
 assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase					):
 return deepcopy(UpperCAmelCase					).integers(0		,					100		,					10					).tolist() == deepcopy(UpperCAmelCase					).integers(0		,					100		,					10					).tolist()
def       __UpperCamelCase	(       UpperCAmelCase					):
 import decorator
 from requests.exceptions import HTTPError

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

 return decorator.decorator(_wrapper		,					UpperCAmelCase					)



class       UpperCAmelCase  :





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  Any:
        lowercase__    :   Any						= returncode
        lowercase__    :   Tuple						= stdout
        lowercase__    :   Any						= stderr


async def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase					):
 while True:
  lowercase__    :   Optional[Any]						= await stream.readline()
  if line:
   callback(UpperCAmelCase					)
  else:
   break
async def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase=None		,					UpperCAmelCase=None		,					UpperCAmelCase=None		,					UpperCAmelCase=False		,					UpperCAmelCase=False					):
 if echo:
  print('''\nRunning: '''		,					''' '''.join(UpperCAmelCase					)					)

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

 # 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)

 lowercase__    :   List[str]						= []
 lowercase__    :   Optional[int]						= []

 def tee(UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase=""					):
  lowercase__    :   Any						= line.decode('''utf-8'''					).rstrip()
  sink.append(UpperCAmelCase					)
  if not quiet:
   print(UpperCAmelCase		,					UpperCAmelCase		,					file=UpperCAmelCase					)

    # XXX: the timeout doesn't seem to make any difference here
 await asyncio.wait(
     [
         _read_stream(p.stdout		,					lambda UpperCAmelCase					: tee(UpperCAmelCase		,					UpperCAmelCase		,					sys.stdout		,					label='''stdout:'''					)					),
         _read_stream(p.stderr		,					lambda UpperCAmelCase					: tee(UpperCAmelCase		,					UpperCAmelCase		,					sys.stderr		,					label='''stderr:'''					)					),
     ]		,					timeout=UpperCAmelCase		,					)
 return _RunOutput(await p.wait()		,					UpperCAmelCase		,					UpperCAmelCase					)
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase=None		,					UpperCAmelCase=None		,					UpperCAmelCase=180		,					UpperCAmelCase=False		,					UpperCAmelCase=True					):
 lowercase__    :   Dict						= asyncio.get_event_loop()
 lowercase__    :   Tuple						= loop.run_until_complete(
     _stream_subprocess(UpperCAmelCase		,					env=UpperCAmelCase		,					stdin=UpperCAmelCase		,					timeout=UpperCAmelCase		,					quiet=UpperCAmelCase		,					echo=UpperCAmelCase					)					)

 lowercase__    :   Tuple						= ''' '''.join(UpperCAmelCase					)
 if result.returncode > 0:
  lowercase__    :   Optional[int]						= '''\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	(       ):
 lowercase__    :   str						= os.environ.get('''PYTEST_XDIST_WORKER'''		,					'''gw0'''					)
 lowercase__    :   List[str]						= re.sub(r'''^gw'''		,					''''''		,					UpperCAmelCase		,					0		,					re.M					)
 return int(UpperCAmelCase					)





def       __UpperCamelCase	(       ):
 lowercase__    :   Any						= 2_9500
 lowercase__    :   List[Any]						= pytest_xdist_worker_id()
 return port + uniq_delta


'''simple docstring'''

import unittest

from datasets import load_dataset

from transformers.pipelines import pipeline
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow



@is_pipeline_test
@require_torch
class       UpperCAmelCase  (						unittest.TestCase ):





       '''simple docstring'''



       @require_torch
       def _lowerCAmelCase(						self			)  ->  int:
        lowercase__    :   str						= pipeline(
            task='''zero-shot-audio-classification'''     ,       model='''hf-internal-testing/tiny-clap-htsat-unfused'''			)
        lowercase__    :   Optional[Any]						= load_dataset('''ashraq/esc50'''			)
        lowercase__    :   Tuple						= dataset['''train''']['''audio'''][-1]['''array''']
        lowercase__    :   Optional[Any]						= audio_classifier(__lowerCAmelCase     ,       candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner''']			)
        self.assertEqual(
            nested_simplify(__lowerCAmelCase			)     ,       [{'''score''': 0.5_0_1, '''label''': '''Sound of a dog'''}, {'''score''': 0.4_9_9, '''label''': '''Sound of vaccum cleaner'''}]     ,       )

       @unittest.skip('''No models are available in TF'''			)
       def _lowerCAmelCase(						self			)  ->  str:
        pass

       @slow
       @require_torch
       def _lowerCAmelCase(						self			)  ->  Tuple:
        lowercase__    :   List[str]						= pipeline(
            task='''zero-shot-audio-classification'''     ,       model='''laion/clap-htsat-unfused'''     ,       )
        # This is an audio of a dog
        lowercase__    :   int						= load_dataset('''ashraq/esc50'''			)
        lowercase__    :   str						= dataset['''train''']['''audio'''][-1]['''array''']
        lowercase__    :   Any						= audio_classifier(__lowerCAmelCase     ,       candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner''']			)

        self.assertEqual(
            nested_simplify(__lowerCAmelCase			)     ,       [
                {'''score''': 0.9_9_9, '''label''': '''Sound of a dog'''},
                {'''score''': 0.0_0_1, '''label''': '''Sound of vaccum cleaner'''},
            ]     ,       )

        lowercase__    :   Dict						= audio_classifier([audio] * 5     ,       candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner''']			)
        self.assertEqual(
            nested_simplify(__lowerCAmelCase			)     ,       [
                [
                    {'''score''': 0.9_9_9, '''label''': '''Sound of a dog'''},
                    {'''score''': 0.0_0_1, '''label''': '''Sound of vaccum cleaner'''},
                ],
            ]
            * 5     ,       )
        lowercase__    :   Any						= audio_classifier(
            [audio] * 5     ,       candidate_labels=['''Sound of a dog''', '''Sound of vaccum cleaner''']     ,       batch_size=5			)
        self.assertEqual(
            nested_simplify(__lowerCAmelCase			)     ,       [
                [
                    {'''score''': 0.9_9_9, '''label''': '''Sound of a dog'''},
                    {'''score''': 0.0_0_1, '''label''': '''Sound of vaccum cleaner'''},
                ],
            ]
            * 5     ,       )


       @unittest.skip('''No models are available in TF'''			)
       def _lowerCAmelCase(						self			)  ->  Union[str, Any]:
        pass

