


"""simple docstring"""


from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


A     :   Tuple			    =			{
    "configuration_whisper": ["WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP", "WhisperConfig", "WhisperOnnxConfig"],
    "feature_extraction_whisper": ["WhisperFeatureExtractor"],
    "processing_whisper": ["WhisperProcessor"],
    "tokenization_whisper": ["WhisperTokenizer"],
}

try:
	if not is_tokenizers_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	A     :   Tuple			    =			["WhisperTokenizerFast"]

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	A     :   List[Any]			    =			[
	    "WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST",
	    "WhisperForConditionalGeneration",
	    "WhisperModel",
	    "WhisperPreTrainedModel",
	    "WhisperForAudioClassification",
	]

try:
	if not is_tf_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	A     :   Union[str, Any]			    =			[
	    "TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST",
	    "TFWhisperForConditionalGeneration",
	    "TFWhisperModel",
	    "TFWhisperPreTrainedModel",
	]

try:
	if not is_flax_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	A     :   List[str]			    =			[
	    "FlaxWhisperForConditionalGeneration",
	    "FlaxWhisperModel",
	    "FlaxWhisperPreTrainedModel",
	    "FlaxWhisperForAudioClassification",
	]


if TYPE_CHECKING:
	from .configuration_whisper import WHISPER_PRETRAINED_CONFIG_ARCHIVE_MAP, WhisperConfig, WhisperOnnxConfig
	from .feature_extraction_whisper import WhisperFeatureExtractor
	from .processing_whisper import WhisperProcessor
	from .tokenization_whisper import WhisperTokenizer

	try:
		if not is_tokenizers_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .tokenization_whisper_fast import WhisperTokenizerFast

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_whisper import (
		    WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST,
		    WhisperForAudioClassification,
		    WhisperForConditionalGeneration,
		    WhisperModel,
		    WhisperPreTrainedModel,
		)

	try:
		if not is_tf_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_tf_whisper import (
		    TF_WHISPER_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFWhisperForConditionalGeneration,
		    TFWhisperModel,
		    TFWhisperPreTrainedModel,
		)

	try:
		if not is_flax_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_flax_whisper import (
		    FlaxWhisperForAudioClassification,
		    FlaxWhisperForConditionalGeneration,
		    FlaxWhisperModel,
		    FlaxWhisperPreTrainedModel,
		)

else:
	import sys

	A     :   List[Any]			    =			_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)





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


UpperCamelCase  							=						parse_flag_from_env('''RUN_SLOW''', default=False)
UpperCamelCase  							=						parse_flag_from_env('''RUN_REMOTE''', default=False)
UpperCamelCase  							=						parse_flag_from_env('''RUN_LOCAL''', default=True)
UpperCamelCase  							=						parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
UpperCamelCase  							=						pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
UpperCamelCase  							=						pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
UpperCamelCase  							=						pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
UpperCamelCase  							=						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
UpperCamelCase  							=						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
UpperCamelCase  							=						pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

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

def 			lowercase_				(			_lowerCamelCase							:       int):
    try:
        import faiss  # noqa
    except ImportError:
        lowercase__ :   Optional[Any]    					=				unittest.skip("test requires faiss")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       int):
    try:
        import regex  # noqa
    except ImportError:
        lowercase__ :   List[Any]    					=				unittest.skip("test requires regex")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       int):
    try:
        import elasticsearch  # noqa
    except ImportError:
        lowercase__ :   Optional[int]    					=				unittest.skip("test requires elasticsearch")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       Union[str, Any]):
    try:
        import sqlalchemy  # noqa
    except ImportError:
        lowercase__ :   Optional[int]    					=				unittest.skip("test requires sqlalchemy")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       int):
    if not config.TORCH_AVAILABLE:
        lowercase__ :   Tuple    					=				unittest.skip("test requires PyTorch")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       Tuple):
    if not config.TF_AVAILABLE:
        lowercase__ :   Any    					=				unittest.skip("test requires TensorFlow")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       Dict):
    if not config.JAX_AVAILABLE:
        lowercase__ :   List[str]    					=				unittest.skip("test requires JAX")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       int):
    if not config.PIL_AVAILABLE:
        lowercase__ :   Dict    					=				unittest.skip("test requires Pillow")(_lowerCamelCase)
    return test_case

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

def 			lowercase_				(			_lowerCamelCase							:       Optional[Any]):
    try:
        import tiktoken  # noqa F401
    except ImportError:
        return unittest.skip("test requires tiktoken")(_lowerCamelCase)
    else:
        return test_case

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

def 			lowercase_				(			_lowerCamelCase							:       Optional[int]):

    def _require_spacy_model(_lowerCamelCase							:       Optional[int]):
        try:
            import spacy  # noqa F401

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

    return _require_spacy_model

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

def 			lowercase_				(			_lowerCamelCase							:       List[str]):
    try:
        import joblibspark  # noqa F401
    except ImportError:
        return unittest.skip("test requires joblibspark")(_lowerCamelCase)
    else:
        return test_case

def 			lowercase_				(			_lowerCamelCase							:       Dict):
    if not _run_slow_tests or _run_slow_tests == 0:
        lowercase__ :   Tuple    					=				unittest.skip("test is slow")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       int):
    if not _run_local_tests or _run_local_tests == 0:
        lowercase__ :   str    					=				unittest.skip("test is local")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       Optional[int]):
    if not _run_packaged_tests or _run_packaged_tests == 0:
        lowercase__ :   List[Any]    					=				unittest.skip("test is packaged")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       Tuple):
    if not _run_remote_tests or _run_remote_tests == 0:
        lowercase__ :   Union[str, Any]    					=				unittest.skip("test requires remote")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			*_lowerCamelCase							:       str):
    def decorate(cls							:       str):
        for name, fn in cls.__dict__.items():
            if callable(_lowerCamelCase) and name.startswith("test"):
                for decorator in decorators:
                    lowercase__ :   Optional[int]    					=				decorator(_lowerCamelCase)
                setattr(cls		,	_lowerCamelCase		,	_lowerCamelCase)
        return cls

    return decorate



class   snake_case_       (		__A       ):
   pass



class   snake_case_       (		__A       ):
   __A	:		List[Any]         =				0
   __A	:		str         =				1
   __A	:		int         =				2



@contextmanager
def 			lowercase_				(			_lowerCamelCase							:       List[str]=OfflineSimulationMode.CONNECTION_FAILS		,	_lowerCamelCase							:       int=1E-16):
    lowercase__ :   int    					=				requests.Session().request

    def timeout_request(_lowerCamelCase							:       str		,	_lowerCamelCase							:       Dict		,	_lowerCamelCase							:       Dict		,	**_lowerCamelCase							:       str):
        # Change the url to an invalid url so that the connection hangs
        lowercase__ :   Any    					=				"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__ :   Dict    					=				timeout
        try:
            return online_request(_lowerCamelCase		,	_lowerCamelCase		,	**_lowerCamelCase)
        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__ :   Optional[Any]    					=				(max_retry_error.args[0].replace("10.255.255.1"		,	f'''OfflineMock[{url}]'''),)
            lowercase__ :   int    					=				(max_retry_error,)
            raise

    def raise_connection_error(_lowerCamelCase							:       Union[str, Any]		,	_lowerCamelCase							:       Optional[Any]		,	**_lowerCamelCase							:       Tuple):
        raise requests.ConnectionError("Offline mode is enabled."		,	request=_lowerCamelCase)

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

@contextmanager
def 			lowercase_				(			*_lowerCamelCase							:       str		,	**_lowerCamelCase							:       Tuple):
    lowercase__ :   Dict    					=				str(Path().resolve())
    with tempfile.TemporaryDirectory(*_lowerCamelCase		,	**_lowerCamelCase) as tmp_dir:
        try:
            os.chdir(_lowerCamelCase)
            yield
        finally:
            os.chdir(_lowerCamelCase)

@contextmanager
def 			lowercase_				(			):
    import gc

    gc.collect()
    lowercase__ :   Union[str, Any]    					=				pa.total_allocated_bytes()
    yield
    assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."

@contextmanager
def 			lowercase_				(			):
    import gc

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

def 			lowercase_				(			_lowerCamelCase							:       Optional[Any]		,	_lowerCamelCase							:       Optional[Any]):
    return deepcopy(_lowerCamelCase).integers(0		,	100		,	10).tolist() == deepcopy(_lowerCamelCase).integers(0		,	100		,	10).tolist()

def 			lowercase_				(			_lowerCamelCase							:       str):
    import decorator
    from requests.exceptions import HTTPError

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

    return decorator.decorator(_wrapper		,	_lowerCamelCase)



class   snake_case_       :






   def __init__(      self				:     int	,						lowercase_				:     Union[str, Any]	,						lowercase_				:     Dict	,						lowercase_				:     List[str]  )					->						List[str]:
       lowercase__ :   Tuple    					=				returncode
       lowercase__ :   int    					=				stdout
       lowercase__ :   Union[str, Any]    					=				stderr



async def 			lowercase_				(			_lowerCamelCase							:       List[str]		,	_lowerCamelCase							:       Dict):
    while True:
        lowercase__ :   Optional[int]    					=				await stream.readline()
        if line:
            callback(_lowerCamelCase)
        else:
            break

async def 			lowercase_				(			_lowerCamelCase							:       Optional[int]		,	_lowerCamelCase							:       Union[str, Any]=None		,	_lowerCamelCase							:       Optional[Any]=None		,	_lowerCamelCase							:       int=None		,	_lowerCamelCase							:       Optional[Any]=False		,	_lowerCamelCase							:       Tuple=False):
    if echo:
        print("\nRunning: "		,	" ".join(_lowerCamelCase))

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

    # 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__ :   str    					=				[]
    lowercase__ :   List[str]    					=				[]

    def tee(_lowerCamelCase							:       str		,	_lowerCamelCase							:       Optional[Any]		,	_lowerCamelCase							:       Union[str, Any]		,	_lowerCamelCase							:       Optional[int]=""):
        lowercase__ :   Optional[int]    					=				line.decode("utf-8").rstrip()
        sink.append(_lowerCamelCase)
        if not quiet:
            print(_lowerCamelCase		,	_lowerCamelCase		,	file=_lowerCamelCase)

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

def 			lowercase_				(			_lowerCamelCase							:       Optional[int]		,	_lowerCamelCase							:       List[str]=None		,	_lowerCamelCase							:       Dict=None		,	_lowerCamelCase							:       int=180		,	_lowerCamelCase							:       Union[str, Any]=False		,	_lowerCamelCase							:       Optional[Any]=True):
    lowercase__ :   Any    					=				asyncio.get_event_loop()
    lowercase__ :   Tuple    					=				loop.run_until_complete(
        _stream_subprocess(_lowerCamelCase		,	env=_lowerCamelCase		,	stdin=_lowerCamelCase		,	timeout=_lowerCamelCase		,	quiet=_lowerCamelCase		,	echo=_lowerCamelCase))

    lowercase__ :   int    					=				" ".join(_lowerCamelCase)
    if result.returncode > 0:
        lowercase__ :   Any    					=				"\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 			lowercase_				(			):
    lowercase__ :   List[str]    					=				os.environ.get("PYTEST_XDIST_WORKER"		,	"gw0")
    lowercase__ :   str    					=				re.sub(R"^gw"		,	""		,	_lowerCamelCase		,	0		,	re.M)
    return int(_lowerCamelCase)

def 			lowercase_				(			):
    lowercase__ :   Union[str, Any]    					=				2_9500
    lowercase__ :   Optional[int]    					=				pytest_xdist_worker_id()
    return port + uniq_delta



