

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       __lowerCAmelCase      (						A       ,     A=False    ):
	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:    Optional[int] 							=			parse_flag_from_env("""RUN_SLOW""", default=False)
_a:    Any 							=			parse_flag_from_env("""RUN_REMOTE""", default=False)
_a:    Union[str, Any] 							=			parse_flag_from_env("""RUN_LOCAL""", default=True)
_a:    List[str] 							=			parse_flag_from_env("""RUN_PACKAGED""", default=True)

# Compression
_a:    List[str] 							=			pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="""test requires lz4""")
_a:    List[str] 							=			pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="""test requires py7zr""")
_a:    Union[str, 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:    Dict 							=			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:    List[Any] 							=			pytest.mark.skipif(
    sys.platform == """win32""",
    reason="""test should not be run on Windows""",
)



def       __lowerCAmelCase      (						A    ):
	try:
		import faiss  # noqa
	except ImportError:
		UpperCAmelCase_       				=			unittest.skip("test requires faiss"    )(A    )
	return test_case



def       __lowerCAmelCase      (						A    ):
	try:
		import regex  # noqa
	except ImportError:
		UpperCAmelCase_       				=			unittest.skip("test requires regex"    )(A    )
	return test_case



def       __lowerCAmelCase      (						A    ):
	try:
		import elasticsearch  # noqa
	except ImportError:
		UpperCAmelCase_       				=			unittest.skip("test requires elasticsearch"    )(A    )
	return test_case



def       __lowerCAmelCase      (						A    ):
	try:
		import sqlalchemy  # noqa
	except ImportError:
		UpperCAmelCase_       				=			unittest.skip("test requires sqlalchemy"    )(A    )
	return test_case



def       __lowerCAmelCase      (						A    ):
	if not config.TORCH_AVAILABLE:
		UpperCAmelCase_       				=			unittest.skip("test requires PyTorch"    )(A    )
	return test_case



def       __lowerCAmelCase      (						A    ):
	if not config.TF_AVAILABLE:
		UpperCAmelCase_       				=			unittest.skip("test requires TensorFlow"    )(A    )
	return test_case



def       __lowerCAmelCase      (						A    ):
	if not config.JAX_AVAILABLE:
		UpperCAmelCase_       				=			unittest.skip("test requires JAX"    )(A    )
	return test_case



def       __lowerCAmelCase      (						A    ):
	if not config.PIL_AVAILABLE:
		UpperCAmelCase_       				=			unittest.skip("test requires Pillow"    )(A    )
	return test_case



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



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



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



def       __lowerCAmelCase      (						A    ):

	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       __lowerCAmelCase      (						A    ):
	try:
		import pyspark  # noqa F401
	except ImportError:
		return unittest.skip("test requires pyspark"    )(A    )
	else:
		return test_case



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



def       __lowerCAmelCase      (						A    ):
	if not _run_slow_tests or _run_slow_tests == 0:
		UpperCAmelCase_       				=			unittest.skip("test is slow"    )(A    )
	return test_case



def       __lowerCAmelCase      (						A    ):
	if not _run_local_tests or _run_local_tests == 0:
		UpperCAmelCase_       				=			unittest.skip("test is local"    )(A    )
	return test_case



def       __lowerCAmelCase      (						A    ):
	if not _run_packaged_tests or _run_packaged_tests == 0:
		UpperCAmelCase_       				=			unittest.skip("test is packaged"    )(A    )
	return test_case



def       __lowerCAmelCase      (						A    ):
	if not _run_remote_tests or _run_remote_tests == 0:
		UpperCAmelCase_       				=			unittest.skip("test requires remote"    )(A    )
	return test_case



def       __lowerCAmelCase      (						*A    ):
	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 						__UpperCamelCase    (					lowercase						):
	pass


class 						__UpperCamelCase    (					lowercase						):
	SCREAMING_SNAKE_CASE__    				=     0
	SCREAMING_SNAKE_CASE__    				=     1
	SCREAMING_SNAKE_CASE__    				=     2



@contextmanager
def       __lowerCAmelCase      (						A=OfflineSimulationMode.CONNECTION_FAILS       ,     A=1E-16    ):
	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       __lowerCAmelCase      (						*A       ,     **A    ):
	UpperCAmelCase_       				=			str(Path().resolve()    )
	with tempfile.TemporaryDirectory(*A       ,     **A    ) as tmp_dir:
		try:
			os.chdir(A    )
			yield
		finally:
			os.chdir(A    )



@contextmanager
def       __lowerCAmelCase      (						):
	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       __lowerCAmelCase      (						):
	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       __lowerCAmelCase      (						A       ,     A    ):
	return deepcopy(A    ).integers(0       ,     100       ,     10    ).tolist() == deepcopy(A    ).integers(0       ,     100       ,     10    ).tolist()



def       __lowerCAmelCase      (						A    ):
	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 						__UpperCamelCase    :




	def __init__(		self	:						str		,	lowerCAmelCase	:						Union[str, Any]		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			returncode
		UpperCAmelCase_       				=			stdout
		UpperCAmelCase_       				=			stderr



async def       __lowerCAmelCase      (						A       ,     A    ):
	while True:
		UpperCAmelCase_       				=			await stream.readline()
		if line:
			callback(A    )
		else:
			break



async def       __lowerCAmelCase      (						A       ,     A=None       ,     A=None       ,     A=None       ,     A=False       ,     A=False    ):
	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       __lowerCAmelCase      (						A       ,     A=None       ,     A=None       ,     A=180       ,     A=False       ,     A=True    ):
	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       __lowerCAmelCase      (						):
	UpperCAmelCase_       				=			os.environ.get("PYTEST_XDIST_WORKER"       ,     "gw0"    )
	UpperCAmelCase_       				=			re.sub(r"^gw"       ,     ""       ,     A       ,     0       ,     re.M    )
	return int(A    )




def       __lowerCAmelCase      (						):
	UpperCAmelCase_       				=			29500
	UpperCAmelCase_       				=			pytest_xdist_worker_id()
	return port + uniq_delta


import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_a:    List[Any] 							=			logging.get_logger(__name__)

_a:    List[str] 							=			"""▁"""

_a:    Union[str, Any] 							=			{
    """vocab_file""": """vocab.json""",
    """spm_file""": """sentencepiece.bpe.model""",
}

_a:    Tuple 							=			{
    """vocab_file""": {
        """facebook/s2t-small-librispeech-asr""": (
            """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json"""
        ),
    },
    """spm_file""": {
        """facebook/s2t-small-librispeech-asr""": (
            """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model"""
        )
    },
}

_a:    Optional[int] 							=			{
    """facebook/s2t-small-librispeech-asr""": 1024,
}

_a:    List[Any] 							=			["""pt""", """fr""", """ru""", """nl""", """ro""", """it""", """es""", """de"""]

_a:    Tuple 							=			{"""mustc""": MUSTC_LANGS}

class 						__UpperCamelCase    (					lowercase						):
	SCREAMING_SNAKE_CASE__    				=     VOCAB_FILES_NAMES
	SCREAMING_SNAKE_CASE__    				=     PRETRAINED_VOCAB_FILES_MAP
	SCREAMING_SNAKE_CASE__    				=     MAX_MODEL_INPUT_SIZES
	SCREAMING_SNAKE_CASE__    				=     ['input_ids', 'attention_mask']

	SCREAMING_SNAKE_CASE__    				=     []




	def __init__(		self	:						Union[str, Any]		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Tuple		,	lowerCAmelCase	:						Tuple="<s>"		,	lowerCAmelCase	:						Optional[int]="</s>"		,	lowerCAmelCase	:						Any="<pad>"		,	lowerCAmelCase	:						Union[str, Any]="<unk>"		,	lowerCAmelCase	:						Tuple=False		,	lowerCAmelCase	:						List[Any]=False		,	lowerCAmelCase	:						Optional[int]=None		,	lowerCAmelCase	:						List[str]=None		,	lowerCAmelCase	:						Optional[Dict[str, Any]] = None		,	**lowerCAmelCase	:						Any		,	):


		'''simple docstring'''







		UpperCAmelCase_       				=			{} if sp_model_kwargs is None else sp_model_kwargs

		super().__init__(
		    bos_token=lowerCAmelCase		,	eos_token=lowerCAmelCase		,	unk_token=lowerCAmelCase		,	pad_token=lowerCAmelCase		,	do_upper_case=lowerCAmelCase		,	do_lower_case=lowerCAmelCase		,	tgt_lang=lowerCAmelCase		,	lang_codes=lowerCAmelCase		,	sp_model_kwargs=self.sp_model_kwargs		,	**lowerCAmelCase		,	)
		UpperCAmelCase_       				=			do_upper_case
		UpperCAmelCase_       				=			do_lower_case

		UpperCAmelCase_       				=			load_json(lowerCAmelCase							)
		UpperCAmelCase_       				=			{v: k for k, v in self.encoder.items()}
		UpperCAmelCase_       				=			spm_file
		UpperCAmelCase_       				=			load_spm(lowerCAmelCase		,	self.sp_model_kwargs							)

		if lang_codes is not None:
			UpperCAmelCase_       				=			lang_codes
			UpperCAmelCase_       				=			LANGUAGES[lang_codes]
			UpperCAmelCase_       				=			[F"<lang:{lang}>" for lang in self.langs]
			UpperCAmelCase_       				=			{lang: self.sp_model.PieceToId(F"<lang:{lang}>"							) for lang in self.langs}

			UpperCAmelCase_       				=			self.lang_tokens
			UpperCAmelCase_       				=			tgt_lang if tgt_lang is not None else self.langs[0]

			self.set_tgt_lang_special_tokens(self._tgt_lang							)
		else:
			UpperCAmelCase_       				=			{}




	@property
	def       __A					(		self	:						List[Any]							):


		'''simple docstring'''







		return len(self.encoder							)




	@property
	def       __A					(		self	:						Any							):


		'''simple docstring'''







		return self._tgt_lang




	@tgt_lang.setter
	def       __A					(		self	:						int		,	lowerCAmelCase	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			new_tgt_lang
		self.set_tgt_lang_special_tokens(lowerCAmelCase							)




	def       __A					(		self	:						List[Any]		,	lowerCAmelCase	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.lang_code_to_id[tgt_lang]
		UpperCAmelCase_       				=			[lang_code_id]




	def       __A					(		self	:						List[str]		,	lowerCAmelCase	:						str							):


		'''simple docstring'''







		return self.sp_model.encode(lowerCAmelCase		,	out_type=lowerCAmelCase							)




	def       __A					(		self	:						str		,	lowerCAmelCase	:						int							):


		'''simple docstring'''







		return self.encoder.get(lowerCAmelCase		,	self.encoder[self.unk_token]							)




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						int							):


		'''simple docstring'''







		return self.decoder.get(lowerCAmelCase		,	self.unk_token							)




	def       __A					(		self	:						Dict		,	lowerCAmelCase	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			[]
		UpperCAmelCase_       				=			""
		for token in tokens:
			# make sure that special tokens are not decoded using sentencepiece model
			if token in self.all_special_tokens:
				UpperCAmelCase_       				=			self.sp_model.decode(lowerCAmelCase							)
				out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
				UpperCAmelCase_       				=			[]
			else:
				current_sub_tokens.append(lowerCAmelCase							)
		UpperCAmelCase_       				=			self.sp_model.decode(lowerCAmelCase							)
		out_string += decoded.upper() if self.do_upper_case else decoded
		return out_string.strip()




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						Optional[int]=None							):


		'''simple docstring'''







		if token_ids_a is None:
			return self.prefix_tokens + token_ids_a + [self.eos_token_id]
		# We don't expect to process pairs, but leave the pair logic for API consistency
		return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id]




	def       __A					(		self	:						Any		,	lowerCAmelCase	:						List[int]		,	lowerCAmelCase	:						Optional[List[int]] = None		,	lowerCAmelCase	:						bool = False							):


		'''simple docstring'''







		if already_has_special_tokens:
			return super().get_special_tokens_mask(
			    token_ids_a=lowerCAmelCase		,	token_ids_a=lowerCAmelCase		,	already_has_special_tokens=lowerCAmelCase							)

		UpperCAmelCase_       				=			[1] * len(self.prefix_tokens							)
		UpperCAmelCase_       				=			[1]
		if token_ids_a is None:
			return prefix_ones + ([0] * len(lowerCAmelCase							)) + suffix_ones
		return prefix_ones + ([0] * len(lowerCAmelCase							)) + ([0] * len(lowerCAmelCase							)) + suffix_ones




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.encoder.copy()
		vocab.update(self.added_tokens_encoder							)
		return vocab




	def __getstate__(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.__dict__.copy()
		UpperCAmelCase_       				=			None
		return state




	def __setstate__(		self	:						Tuple		,	lowerCAmelCase	:						Dict							):


		'''simple docstring'''







		UpperCAmelCase_       				=			d

		# for backward compatibility
		if not hasattr(self		,	"sp_model_kwargs"							):
			UpperCAmelCase_       				=			{}

		UpperCAmelCase_       				=			load_spm(self.spm_file		,	self.sp_model_kwargs							)




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Optional[str] = None							):


		'''simple docstring'''







		UpperCAmelCase_       				=			Path(lowerCAmelCase							)
		assert save_dir.is_dir(), F"{save_directory} should be a directory"
		UpperCAmelCase_       				=			save_dir / (
		    (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
		)
		UpperCAmelCase_       				=			save_dir / (
		    (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"]
		)

		save_json(self.encoder		,	lowerCAmelCase							)

		if os.path.abspath(self.spm_file							) != os.path.abspath(lowerCAmelCase							) and os.path.isfile(self.spm_file							):
			copyfile(self.spm_file		,	lowerCAmelCase							)
		elif not os.path.isfile(self.spm_file							):
			with open(lowerCAmelCase		,	"wb"							) as fi:
				UpperCAmelCase_       				=			self.sp_model.serialized_model_proto()
				fi.write(lowerCAmelCase							)

		return (str(lowerCAmelCase							), str(lowerCAmelCase							))



def       __lowerCAmelCase      (						A       ,     A    ):
	UpperCAmelCase_       				=			sentencepiece.SentencePieceProcessor(**A    )
	spm.Load(str(A    )    )
	return spm



def       __lowerCAmelCase      (						A    ):
	with open(A       ,     "r"    ) as f:
		return json.load(A    )




def       __lowerCAmelCase      (						A       ,     A    ):
	with open(A       ,     "w"    ) as f:
		json.dump(A       ,     A       ,     indent=2    )