




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


lowerCamelCase__			:       Dict         =							parse_flag_from_env('RUN_SLOW', default=False)
lowerCamelCase__			:       str         =							parse_flag_from_env('RUN_REMOTE', default=False)
lowerCamelCase__			:       Union[str, Any]         =							parse_flag_from_env('RUN_LOCAL', default=True)
lowerCamelCase__			:       str         =							parse_flag_from_env('RUN_PACKAGED', default=True)

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

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

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

def  UpperCAmelCase_							(				__UpperCAmelCase						:     List[str]							) ->			Optional[int]:
      try:
            import faiss  # noqa
      except ImportError:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test requires faiss'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Optional[Any]							) ->			str:
      try:
            import regex  # noqa
      except ImportError:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test requires regex'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     List[Any]							) ->			List[Any]:
      try:
            import elasticsearch  # noqa
      except ImportError:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test requires elasticsearch'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Optional[Any]							) ->			Optional[Any]:
      try:
            import sqlalchemy  # noqa
      except ImportError:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test requires sqlalchemy'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Union[str, Any]							) ->			Tuple:
      if not config.TORCH_AVAILABLE:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test requires PyTorch'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     List[Any]							) ->			Dict:
      if not config.TF_AVAILABLE:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test requires TensorFlow'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Optional[Any]							) ->			Tuple:
      if not config.JAX_AVAILABLE:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test requires JAX'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Optional[int]							) ->			Any:
      if not config.PIL_AVAILABLE:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test requires Pillow'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     List[str]							) ->			str:
      try:
            import transformers  # noqa F401
      except ImportError:
            return unittest.skip('test requires transformers'							)(__UpperCAmelCase							)
      else:
            return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     List[Any]							) ->			Tuple:
      try:
            import tiktoken  # noqa F401
      except ImportError:
            return unittest.skip('test requires tiktoken'							)(__UpperCAmelCase							)
      else:
            return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     List[Any]							) ->			Union[str, Any]:
      try:
            import spacy  # noqa F401
      except ImportError:
            return unittest.skip('test requires spacy'							)(__UpperCAmelCase							)
      else:
            return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Tuple							) ->			str:

      def _require_spacy_model(__UpperCAmelCase						:     Any							):
            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						:     Any							) ->			Dict:
      try:
            import pyspark  # noqa F401
      except ImportError:
            return unittest.skip('test requires pyspark'							)(__UpperCAmelCase							)
      else:
            return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Union[str, Any]							) ->			Dict:
      try:
            import joblibspark  # noqa F401
      except ImportError:
            return unittest.skip('test requires joblibspark'							)(__UpperCAmelCase							)
      else:
            return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     List[str]							) ->			Tuple:
      if not _run_slow_tests or _run_slow_tests == 0:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test is slow'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Tuple							) ->			Optional[int]:
      if not _run_local_tests or _run_local_tests == 0:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test is local'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Dict							) ->			str:
      if not _run_packaged_tests or _run_packaged_tests == 0:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test is packaged'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Union[str, Any]							) ->			str:
      if not _run_remote_tests or _run_remote_tests == 0:
            SCREAMING_SNAKE_CASE_     						=      unittest.skip('test requires remote'							)(__UpperCAmelCase							)
      return test_case

def  UpperCAmelCase_							(				*__UpperCAmelCase						:     Tuple							) ->			Union[str, Any]:
      def decorate(cls						:     int							):
            for name, fn in cls.__dict__.items():
                  if callable(__UpperCAmelCase							) and name.startswith('test'							):
                        for decorator in decorators:
                              SCREAMING_SNAKE_CASE_     						=      decorator(__UpperCAmelCase							)
                        setattr(cls      ,      __UpperCAmelCase      ,      __UpperCAmelCase							)
            return cls

      return decorate





class 	lowerCamelCase_							(				_SCREAMING_SNAKE_CASE ):


 '''simple docstring'''







 pass





class 	lowerCamelCase_							(				_SCREAMING_SNAKE_CASE ):


 '''simple docstring'''







 lowercase_       =   0
 lowercase_       =   1
 lowercase_       =   2


@contextmanager
def  UpperCAmelCase_							(				__UpperCAmelCase						:     List[Any]=OfflineSimulationMode.CONNECTION_FAILS      ,      __UpperCAmelCase						:     List[str]=1E-16							) ->			List[str]:
      SCREAMING_SNAKE_CASE_     						=      requests.Session().request

      def timeout_request(__UpperCAmelCase						:     Dict      ,      __UpperCAmelCase						:     str      ,      __UpperCAmelCase						:     List[Any]      ,      **__UpperCAmelCase						:     str							):
            # Change the url to an invalid url so that the connection hangs
            SCREAMING_SNAKE_CASE_     						=      '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."							)
            SCREAMING_SNAKE_CASE_     						=      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
                  SCREAMING_SNAKE_CASE_     						=      url
                  SCREAMING_SNAKE_CASE_     						=      e.args[0]
                  SCREAMING_SNAKE_CASE_     						=      (max_retry_error.args[0].replace('10.255.255.1'      ,      f"OfflineMock[{url}]"							),)
                  SCREAMING_SNAKE_CASE_     						=      (max_retry_error,)
                  raise

      def raise_connection_error(__UpperCAmelCase						:     Optional[int]      ,      __UpperCAmelCase						:     int      ,      **__UpperCAmelCase						:     Union[str, Any]							):
            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						:     Tuple      ,      **__UpperCAmelCase						:     List[str]							) ->			Any:
      SCREAMING_SNAKE_CASE_     						=      str(Path().resolve()							)
      with tempfile.TemporaryDirectory(*__UpperCAmelCase      ,      **__UpperCAmelCase							) as tmp_dir:
            try:
                  os.chdir(__UpperCAmelCase							)
                  yield
            finally:
                  os.chdir(__UpperCAmelCase							)

@contextmanager
def  UpperCAmelCase_							(				) ->			str:
      import gc

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

@contextmanager
def  UpperCAmelCase_							(				) ->			List[str]:
      import gc

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

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Optional[Any]      ,      __UpperCAmelCase						:     List[Any]							) ->			List[str]:
      return deepcopy(__UpperCAmelCase							).integers(0      ,      1_00      ,      10							).tolist() == deepcopy(__UpperCAmelCase							).integers(0      ,      1_00      ,      10							).tolist()

def  UpperCAmelCase_							(				__UpperCAmelCase						:     Optional[int]							) ->			int:
      import decorator
      from requests.exceptions import HTTPError

      def _wrapper(__UpperCAmelCase						:     List[Any]      ,      *__UpperCAmelCase						:     Union[str, Any]      ,      **__UpperCAmelCase						:     Dict							):
            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 	lowerCamelCase_							:


 '''simple docstring'''







 def __init__(							self  :		Any    ,    _lowerCAmelCase  :		str    ,    _lowerCAmelCase  :		Any    ,    _lowerCAmelCase  :		List[Any]						):
       SCREAMING_SNAKE_CASE_     						=      returncode
       SCREAMING_SNAKE_CASE_     						=      stdout
       SCREAMING_SNAKE_CASE_     						=      stderr


async def  UpperCAmelCase_							(				__UpperCAmelCase						:     List[Any]      ,      __UpperCAmelCase						:     Dict							) ->			int:
      while True:
            SCREAMING_SNAKE_CASE_     						=      await stream.readline()
            if line:
                  callback(__UpperCAmelCase							)
            else:
                  break

async def  UpperCAmelCase_							(				__UpperCAmelCase						:     List[Any]      ,      __UpperCAmelCase						:     Optional[int]=None      ,      __UpperCAmelCase						:     Tuple=None      ,      __UpperCAmelCase						:     Any=None      ,      __UpperCAmelCase						:     int=False      ,      __UpperCAmelCase						:     Optional[Any]=False							) ->			_RunOutput:
      if echo:
            print('\nRunning: '      ,      ' '.join(__UpperCAmelCase							)							)

      SCREAMING_SNAKE_CASE_     						=      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)

      SCREAMING_SNAKE_CASE_     						=      []
      SCREAMING_SNAKE_CASE_     						=      []

      def tee(__UpperCAmelCase						:     Dict      ,      __UpperCAmelCase						:     str      ,      __UpperCAmelCase						:     str      ,      __UpperCAmelCase						:     Tuple=""							):
            SCREAMING_SNAKE_CASE_     						=      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						:     int      ,      __UpperCAmelCase						:     int=None      ,      __UpperCAmelCase						:     List[Any]=None      ,      __UpperCAmelCase						:     List[Any]=1_80      ,      __UpperCAmelCase						:     Optional[int]=False      ,      __UpperCAmelCase						:     List[str]=True							) ->			_RunOutput:
      SCREAMING_SNAKE_CASE_     						=      asyncio.get_event_loop()
      SCREAMING_SNAKE_CASE_     						=      loop.run_until_complete(
          _stream_subprocess(__UpperCAmelCase      ,      env=__UpperCAmelCase      ,      stdin=__UpperCAmelCase      ,      timeout=__UpperCAmelCase      ,      quiet=__UpperCAmelCase      ,      echo=__UpperCAmelCase							)							)

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





def  UpperCAmelCase_							(				) ->			Tuple:
      SCREAMING_SNAKE_CASE_     						=      2_95_00
      SCREAMING_SNAKE_CASE_     						=      pytest_xdist_worker_id()
      return port + uniq_delta





from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase__			:       Dict         =							logging.get_logger(__name__)

lowerCamelCase__			:       Any         =							{
    'facebook/s2t-small-librispeech-asr': (
        'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json'
    ),
    # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text
}





class 	lowerCamelCase_							(				_SCREAMING_SNAKE_CASE ):


 '''simple docstring'''







 lowercase_       =   "speech_to_text"
 lowercase_       =   ["past_key_values"]
 lowercase_       =   {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}



 def __init__(							self  :		Union[str, Any]    ,    _lowerCAmelCase  :		Optional[int]=10_000    ,    _lowerCAmelCase  :		str=12    ,    _lowerCAmelCase  :		Tuple=2_048    ,    _lowerCAmelCase  :		str=4    ,    _lowerCAmelCase  :		Tuple=6    ,    _lowerCAmelCase  :		Optional[int]=2_048    ,    _lowerCAmelCase  :		Dict=4    ,    _lowerCAmelCase  :		List[Any]=0.0    ,    _lowerCAmelCase  :		int=0.0    ,    _lowerCAmelCase  :		Optional[int]=True    ,    _lowerCAmelCase  :		Union[str, Any]=True    ,    _lowerCAmelCase  :		Any="relu"    ,    _lowerCAmelCase  :		Any=256    ,    _lowerCAmelCase  :		List[str]=0.1    ,    _lowerCAmelCase  :		Optional[Any]=0.0    ,    _lowerCAmelCase  :		Optional[int]=0.0    ,    _lowerCAmelCase  :		Tuple=0.02    ,    _lowerCAmelCase  :		List[str]=2    ,    _lowerCAmelCase  :		Tuple=True    ,    _lowerCAmelCase  :		List[str]=1    ,    _lowerCAmelCase  :		Dict=0    ,    _lowerCAmelCase  :		Tuple=2    ,    _lowerCAmelCase  :		Optional[int]=6_000    ,    _lowerCAmelCase  :		Tuple=1_024    ,    _lowerCAmelCase  :		Any=2    ,    _lowerCAmelCase  :		str=(5, 5)    ,    _lowerCAmelCase  :		Optional[int]=1_024    ,    _lowerCAmelCase  :		List[Any]=80    ,    _lowerCAmelCase  :		List[Any]=1    ,    **_lowerCAmelCase  :		List[Any]    ,    ):
       SCREAMING_SNAKE_CASE_     						=      vocab_size
       SCREAMING_SNAKE_CASE_     						=      d_model
       SCREAMING_SNAKE_CASE_     						=      encoder_ffn_dim
       SCREAMING_SNAKE_CASE_     						=      encoder_layers
       SCREAMING_SNAKE_CASE_     						=      encoder_attention_heads
       SCREAMING_SNAKE_CASE_     						=      decoder_ffn_dim
       SCREAMING_SNAKE_CASE_     						=      decoder_layers
       SCREAMING_SNAKE_CASE_     						=      decoder_attention_heads
       SCREAMING_SNAKE_CASE_     						=      dropout
       SCREAMING_SNAKE_CASE_     						=      attention_dropout
       SCREAMING_SNAKE_CASE_     						=      activation_dropout
       SCREAMING_SNAKE_CASE_     						=      activation_function
       SCREAMING_SNAKE_CASE_     						=      init_std
       SCREAMING_SNAKE_CASE_     						=      encoder_layerdrop
       SCREAMING_SNAKE_CASE_     						=      decoder_layerdrop
       SCREAMING_SNAKE_CASE_     						=      use_cache
       SCREAMING_SNAKE_CASE_     						=      encoder_layers
       SCREAMING_SNAKE_CASE_     						=      scale_embedding  # scale factor will be sqrt(d_model) if True
       SCREAMING_SNAKE_CASE_     						=      max_source_positions
       SCREAMING_SNAKE_CASE_     						=      max_target_positions
       SCREAMING_SNAKE_CASE_     						=      num_conv_layers
       SCREAMING_SNAKE_CASE_     						=      list(_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_     						=      conv_channels
       SCREAMING_SNAKE_CASE_     						=      input_feat_per_channel
       SCREAMING_SNAKE_CASE_     						=      input_channels

       if len(self.conv_kernel_sizes						) != self.num_conv_layers:
             raise ValueError(
                 'Configuration for convolutional module is incorrect. '
                 'It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` '
                 F"but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes						)}`, "
                 F"`config.num_conv_layers = {self.num_conv_layers}`."						)

       super().__init__(
           pad_token_id=_lowerCAmelCase    ,    bos_token_id=_lowerCAmelCase    ,    eos_token_id=_lowerCAmelCase    ,    is_encoder_decoder=_lowerCAmelCase    ,    decoder_start_token_id=_lowerCAmelCase    ,    **_lowerCAmelCase    ,    )