import functools
import operator

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


_UpperCAmelCase          =						logging.get_logger(__name__)

_UpperCAmelCase          =						{
    """asapp/sew-d-tiny-100k""": """https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json""",
    # See all SEW-D models at https://huggingface.co/models?filter=sew-d
}





class UpperCAmelCase		(   __A    ):


				'''simple docstring'''






				lowerCamelCase_        =   '''sew-d'''
				def __init__(		self						,      lowercase=3_2						,      lowercase=7_6_8						,      lowercase=1_2						,      lowercase=1_2						,      lowercase=3_0_7_2						,      lowercase=2						,      lowercase=5_1_2						,      lowercase=2_5_6						,      lowercase=True						,      lowercase=True						,      lowercase=("p2c", "c2p")						,      lowercase="layer_norm"						,      lowercase="gelu_python"						,      lowercase=0.1						,      lowercase=0.1						,      lowercase=0.1						,      lowercase=0.0						,      lowercase=0.1						,      lowercase=0.02						,      lowercase=1E-7						,      lowercase=1E-5						,      lowercase="group"						,      lowercase="gelu"						,      lowercase=(6_4, 1_2_8, 1_2_8, 1_2_8, 1_2_8, 2_5_6, 2_5_6, 2_5_6, 2_5_6, 5_1_2, 5_1_2, 5_1_2, 5_1_2)						,      lowercase=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1)						,      lowercase=(1_0, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1)						,      lowercase=False						,      lowercase=1_2_8						,      lowercase=1_6						,      lowercase=True						,      lowercase=0.05						,      lowercase=1_0						,      lowercase=2						,      lowercase=0.0						,      lowercase=1_0						,      lowercase=0						,      lowercase="mean"						,      lowercase=False						,      lowercase=False						,      lowercase=2_5_6						,      lowercase=0						,      lowercase=1						,      lowercase=2						,      **lowercase						,      ):



						"""simple docstring"""





						super().__init__(**lowercase						,      pad_token_id=lowercase						,      bos_token_id=lowercase						,      eos_token_id=lowercase   )
						A_						:							Any      = hidden_size
						A_						:							Union[str, Any]      = feat_extract_norm
						A_						:							str      = feat_extract_activation
						A_						:							Optional[Any]      = list(lowercase   )
						A_						:							Dict      = list(lowercase   )
						A_						:							Optional[int]      = list(lowercase   )
						A_						:							Optional[Any]      = conv_bias
						A_						:							Optional[Any]      = num_conv_pos_embeddings
						A_						:							Optional[int]      = num_conv_pos_embedding_groups
						A_						:							Any      = len(self.conv_dim   )
						A_						:							Dict      = num_hidden_layers
						A_						:							Optional[Any]      = intermediate_size
						A_						:							Tuple      = squeeze_factor
						A_						:							str      = max_position_embeddings
						A_						:							Union[str, Any]      = position_buckets
						A_						:							Dict      = share_att_key
						A_						:							Any      = relative_attention
						A_						:							Dict      = norm_rel_ebd
						A_						:							int      = list(lowercase   )
						A_						:							Union[str, Any]      = hidden_act
						A_						:							Tuple      = num_attention_heads
						A_						:							Any      = hidden_dropout
						A_						:							str      = attention_dropout
						A_						:							Optional[int]      = activation_dropout
						A_						:							Optional[Any]      = feat_proj_dropout
						A_						:							Tuple      = final_dropout
						A_						:							Tuple      = layer_norm_eps
						A_						:							List[Any]      = feature_layer_norm_eps
						A_						:							Tuple      = initializer_range
						A_						:							Dict      = vocab_size

						if (
						    (len(self.conv_stride   ) != self.num_feat_extract_layers)
						    or (len(self.conv_kernel   ) != self.num_feat_extract_layers)
						    or (len(self.conv_dim   ) != self.num_feat_extract_layers)
						):
								raise ValueError(
								    'Configuration for convolutional layers is incorrect.'
								    'It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,'
								    F'''but is `len(config.conv_dim) = {len(self.conv_dim   )}`, `len(config.conv_stride)'''
								    F'''= {len(self.conv_stride   )}`, `len(config.conv_kernel) = {len(self.conv_kernel   )}`.'''   )

						# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
						A_						:							List[Any]      = apply_spec_augment
						A_						:							Union[str, Any]      = mask_time_prob
						A_						:							Optional[Any]      = mask_time_length
						A_						:							str      = mask_time_min_masks
						A_						:							Optional[Any]      = mask_feature_prob
						A_						:							str      = mask_feature_length
						A_						:							int      = mask_feature_min_masks

						# ctc loss
						A_						:							List[Any]      = ctc_loss_reduction
						A_						:							Union[str, Any]      = ctc_zero_infinity

						# sequence classification
						A_						:							Union[str, Any]      = use_weighted_layer_sum
						A_						:							Any      = classifier_proj_size







				@property
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						return functools.reduce(operator.mul						,      self.conv_stride						,      1   )







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		(			__lowercase		:					Optional[Any]		,__lowercase		:					Optional[int]=False      ):
		'''simple docstring'''




		try:
				A_						:							int      = os.environ[key]
		except KeyError:
				# KEY isn't set, default to `default`.
				A_						:							Any      = default
		else:
				# KEY is set, convert it to True or False.
				try:
						A_						:							Dict      = strtobool(__lowercase      )
				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 							UpperCamelCase		(			__lowercase		:					Tuple      ):
		'''simple docstring'''




		try:
				import faiss  # noqa
		except ImportError:
				A_						:							Dict      = unittest.skip('test requires faiss'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			__lowercase		:					List[str]      ):
		'''simple docstring'''




		try:
				import regex  # noqa
		except ImportError:
				A_						:							Dict      = unittest.skip('test requires regex'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			__lowercase		:					Optional[int]      ):
		'''simple docstring'''




		try:
				import elasticsearch  # noqa
		except ImportError:
				A_						:							Union[str, Any]      = unittest.skip('test requires elasticsearch'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			__lowercase		:					Tuple      ):
		'''simple docstring'''




		try:
				import sqlalchemy  # noqa
		except ImportError:
				A_						:							Dict      = unittest.skip('test requires sqlalchemy'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			__lowercase		:					Dict      ):
		'''simple docstring'''




		if not config.TORCH_AVAILABLE:
				A_						:							Tuple      = unittest.skip('test requires PyTorch'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			__lowercase		:					int      ):
		'''simple docstring'''




		if not config.TF_AVAILABLE:
				A_						:							int      = unittest.skip('test requires TensorFlow'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			__lowercase		:					int      ):
		'''simple docstring'''




		if not config.JAX_AVAILABLE:
				A_						:							Union[str, Any]      = unittest.skip('test requires JAX'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			__lowercase		:					List[str]      ):
		'''simple docstring'''




		if not config.PIL_AVAILABLE:
				A_						:							Union[str, Any]      = unittest.skip('test requires Pillow'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			__lowercase		:					List[Any]      ):
		'''simple docstring'''




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




def 							UpperCamelCase		(			__lowercase		:					str      ):
		'''simple docstring'''




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




def 							UpperCamelCase		(			__lowercase		:					str      ):
		'''simple docstring'''




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




def 							UpperCamelCase		(			__lowercase		:					List[str]      ):
		'''simple docstring'''




		def _require_spacy_model(__lowercase		:					List[Any]      ):
				try:
						import spacy  # noqa F401

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

		return _require_spacy_model




def 							UpperCamelCase		(			__lowercase		:					int      ):
		'''simple docstring'''




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




def 							UpperCamelCase		(			__lowercase		:					Tuple      ):
		'''simple docstring'''




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




def 							UpperCamelCase		(			__lowercase		:					Dict      ):
		'''simple docstring'''




		if not _run_slow_tests or _run_slow_tests == 0:
				A_						:							Union[str, Any]      = unittest.skip('test is slow'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			__lowercase		:					Optional[Any]      ):
		'''simple docstring'''




		if not _run_local_tests or _run_local_tests == 0:
				A_						:							Union[str, Any]      = unittest.skip('test is local'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			__lowercase		:					Dict      ):
		'''simple docstring'''




		if not _run_packaged_tests or _run_packaged_tests == 0:
				A_						:							Dict      = unittest.skip('test is packaged'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			__lowercase		:					Tuple      ):
		'''simple docstring'''




		if not _run_remote_tests or _run_remote_tests == 0:
				A_						:							Any      = unittest.skip('test requires remote'      )(__lowercase      )
		return test_case




def 							UpperCamelCase		(			*__lowercase		:					Optional[int]      ):
		'''simple docstring'''




		def decorate(cls		:					List[Any]      ):
				for name, fn in cls.__dict__.items():
						if callable(__lowercase      ) and name.startswith('test'      ):
								for decorator in decorators:
										A_						:							str      = decorator(__lowercase      )
								setattr(cls		,__lowercase		,__lowercase      )
				return cls

		return decorate





class UpperCAmelCase		(   __A    ):


				'''simple docstring'''






				pass





class UpperCAmelCase		(   __A    ):


				'''simple docstring'''






				lowerCamelCase_        =   0
				lowerCamelCase_        =   1
				lowerCamelCase_        =   2




@contextmanager
def 							UpperCamelCase		(			__lowercase		:					List[Any]=OfflineSimulationMode.CONNECTION_FAILS		,__lowercase		:					int=1e-1_6      ):
		'''simple docstring'''




		A_						:							Any      = requests.Session().request

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

		def raise_connection_error(__lowercase		:					List[Any]		,__lowercase		:					List[Any]		,**__lowercase		:					Optional[Any]      ):
				raise requests.ConnectionError('Offline mode is enabled.'		,request=__lowercase      )

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




@contextmanager
def 							UpperCamelCase		(			*__lowercase		:					Union[str, Any]		,**__lowercase		:					Optional[Any]      ):
		'''simple docstring'''




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




@contextmanager
def 							UpperCamelCase		(			):
		'''simple docstring'''




		import gc

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




@contextmanager
def 							UpperCamelCase		(			):
		'''simple docstring'''




		import gc

		gc.collect()
		A_						:							Optional[Any]      = pa.total_allocated_bytes()
		yield
		assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."




def 							UpperCamelCase		(			__lowercase		:					Union[str, Any]		,__lowercase		:					Any      ):
		'''simple docstring'''




		return deepcopy(__lowercase      ).integers(0		,1_00		,10      ).tolist() == deepcopy(__lowercase      ).integers(0		,1_00		,10      ).tolist()




def 							UpperCamelCase		(			__lowercase		:					List[Any]      ):
		'''simple docstring'''




		import decorator
		from requests.exceptions import HTTPError

		def _wrapper(__lowercase		:					List[Any]		,*__lowercase		:					Dict		,**__lowercase		:					str      ):
				try:
						return func(*__lowercase		,**__lowercase      )
				except HTTPError as err:
						if str(__lowercase      ).startswith('500'      ) or str(__lowercase      ).startswith('502'      ):
								pytest.xfail(str(__lowercase      )      )
						raise err

		return decorator.decorator(_wrapper		,__lowercase      )





class UpperCAmelCase		:


				'''simple docstring'''






				def __init__(		self						,      lowercase						,      lowercase						,      lowercase   ):



						"""simple docstring"""





						A_						:							int      = returncode
						A_						:							Any      = stdout
						A_						:							Any      = stderr




async def 							UpperCamelCase		(			__lowercase		:					List[Any]		,__lowercase		:					str      ):
		'''simple docstring'''




		while True:
				A_						:							int      = await stream.readline()
				if line:
						callback(__lowercase      )
				else:
						break




async def 							UpperCamelCase		(			__lowercase		:					Union[str, Any]		,__lowercase		:					List[str]=None		,__lowercase		:					List[str]=None		,__lowercase		:					Dict=None		,__lowercase		:					Dict=False		,__lowercase		:					str=False      ):
		'''simple docstring'''




		if echo:
				print('\nRunning: '		,' '.join(__lowercase      )      )

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

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

		A_						:							Optional[Any]      = []
		A_						:							str      = []

		def tee(__lowercase		:					Union[str, Any]		,__lowercase		:					Union[str, Any]		,__lowercase		:					List[str]		,__lowercase		:					Tuple=""      ):
				A_						:							Optional[Any]      = line.decode('utf-8'      ).rstrip()
				sink.append(__lowercase      )
				if not quiet:
						print(__lowercase		,__lowercase		,file=__lowercase      )

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




def 							UpperCamelCase		(			__lowercase		:					List[Any]		,__lowercase		:					Union[str, Any]=None		,__lowercase		:					Tuple=None		,__lowercase		:					Optional[int]=1_80		,__lowercase		:					Dict=False		,__lowercase		:					List[str]=True      ):
		'''simple docstring'''




		A_						:							Optional[Any]      = asyncio.get_event_loop()
		A_						:							str      = loop.run_until_complete(
		    _stream_subprocess(__lowercase		,env=__lowercase		,stdin=__lowercase		,timeout=__lowercase		,quiet=__lowercase		,echo=__lowercase      )      )

		A_						:							str      = ' '.join(__lowercase      )
		if result.returncode > 0:
				A_						:							Union[str, 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 							UpperCamelCase		(			):
		'''simple docstring'''




		A_						:							int      = os.environ.get('PYTEST_XDIST_WORKER'		,'gw0'      )
		A_						:							Dict      = re.sub(r'^gw'		,''		,__lowercase		,0		,re.M      )
		return int(__lowercase      )




def 							UpperCamelCase		(			):
		'''simple docstring'''




		A_						:							int      = 2_95_00
		A_						:							Any      = pytest_xdist_worker_id()
		return port + uniq_delta






