



"""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     (		A	:						Tuple     ,				A	:						List[str]=False       ):

		'''simple docstring'''


		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


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

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

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

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




def 	UpperCAmelCase     (		A	:						Optional[Any]       ):

		'''simple docstring'''


		try:
				import faiss  # noqa
		except ImportError:
				_UpperCAmelCase							 =		unittest.skip('test requires faiss'       )(A       )
		return test_case




def 	UpperCAmelCase     (		A	:						List[Any]       ):

		'''simple docstring'''


		try:
				import regex  # noqa
		except ImportError:
				_UpperCAmelCase							 =		unittest.skip('test requires regex'       )(A       )
		return test_case




def 	UpperCAmelCase     (		A	:						List[str]       ):

		'''simple docstring'''


		try:
				import elasticsearch  # noqa
		except ImportError:
				_UpperCAmelCase							 =		unittest.skip('test requires elasticsearch'       )(A       )
		return test_case




def 	UpperCAmelCase     (		A	:						Optional[int]       ):

		'''simple docstring'''


		try:
				import sqlalchemy  # noqa
		except ImportError:
				_UpperCAmelCase							 =		unittest.skip('test requires sqlalchemy'       )(A       )
		return test_case




def 	UpperCAmelCase     (		A	:						str       ):

		'''simple docstring'''


		if not config.TORCH_AVAILABLE:
				_UpperCAmelCase							 =		unittest.skip('test requires PyTorch'       )(A       )
		return test_case




def 	UpperCAmelCase     (		A	:						Tuple       ):

		'''simple docstring'''


		if not config.TF_AVAILABLE:
				_UpperCAmelCase							 =		unittest.skip('test requires TensorFlow'       )(A       )
		return test_case




def 	UpperCAmelCase     (		A	:						Optional[Any]       ):

		'''simple docstring'''


		if not config.JAX_AVAILABLE:
				_UpperCAmelCase							 =		unittest.skip('test requires JAX'       )(A       )
		return test_case




def 	UpperCAmelCase     (		A	:						str       ):

		'''simple docstring'''


		if not config.PIL_AVAILABLE:
				_UpperCAmelCase							 =		unittest.skip('test requires Pillow'       )(A       )
		return test_case




def 	UpperCAmelCase     (		A	:						Union[str, Any]       ):

		'''simple docstring'''


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




def 	UpperCAmelCase     (		A	:						Optional[int]       ):

		'''simple docstring'''


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




def 	UpperCAmelCase     (		A	:						Any       ):

		'''simple docstring'''


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




def 	UpperCAmelCase     (		A	:						Any       ):

		'''simple docstring'''


		def _require_spacy_model(A	:						Dict       ):
				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 	UpperCAmelCase     (		A	:						str       ):

		'''simple docstring'''


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




def 	UpperCAmelCase     (		A	:						Optional[int]       ):

		'''simple docstring'''


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




def 	UpperCAmelCase     (		A	:						List[str]       ):

		'''simple docstring'''


		if not _run_slow_tests or _run_slow_tests == 0:
				_UpperCAmelCase							 =		unittest.skip('test is slow'       )(A       )
		return test_case




def 	UpperCAmelCase     (		A	:						List[Any]       ):

		'''simple docstring'''


		if not _run_local_tests or _run_local_tests == 0:
				_UpperCAmelCase							 =		unittest.skip('test is local'       )(A       )
		return test_case




def 	UpperCAmelCase     (		A	:						Dict       ):

		'''simple docstring'''


		if not _run_packaged_tests or _run_packaged_tests == 0:
				_UpperCAmelCase							 =		unittest.skip('test is packaged'       )(A       )
		return test_case




def 	UpperCAmelCase     (		A	:						List[Any]       ):

		'''simple docstring'''


		if not _run_remote_tests or _run_remote_tests == 0:
				_UpperCAmelCase							 =		unittest.skip('test requires remote'       )(A       )
		return test_case




def 	UpperCAmelCase     (		*A	:						List[Any]       ):

		'''simple docstring'''


		def decorate(cls	:						Tuple       ):
				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 			lowercase__			(      A    ):
							'''simple docstring'''







							pass







class 			lowercase__			(      A    ):
							'''simple docstring'''







							_UpperCAmelCase      				=					0
							_UpperCAmelCase      				=					1
							_UpperCAmelCase      				=					2







@contextmanager
def 	UpperCAmelCase     (		A	:						Optional[Any]=OfflineSimulationMode.CONNECTION_FAILS     ,				A	:						Optional[int]=1e-16       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		requests.Session().request

		def timeout_request(A	:						str     ,				A	:						Tuple     ,				A	:						List[Any]     ,				**A	:						List[str]       ):
				# 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	:						Dict     ,				A	:						int     ,				**A	:						Optional[int]       ):
				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 	UpperCAmelCase     (		*A	:						List[str]     ,				**A	:						Optional[Any]       ):

		'''simple docstring'''


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




@contextmanager
def 	UpperCAmelCase     (		):

		'''simple docstring'''


		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 	UpperCAmelCase     (		):

		'''simple docstring'''


		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 	UpperCAmelCase     (		A	:						Optional[Any]     ,				A	:						str       ):

		'''simple docstring'''


		return deepcopy(A       ).integers(0     ,				100     ,				10       ).tolist() == deepcopy(A       ).integers(0     ,				100     ,				10       ).tolist()




def 	UpperCAmelCase     (		A	:						int       ):

		'''simple docstring'''


		import decorator
		from requests.exceptions import HTTPError

		def _wrapper(A	:						str     ,				*A	:						Dict     ,				**A	:						List[str]       ):
				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 			lowercase__			:
							'''simple docstring'''







							def __init__(  self	,       snake_case	,       snake_case	,       snake_case						)			->							Optional[Any]:
									_UpperCAmelCase							 =		returncode
									_UpperCAmelCase							 =		stdout
									_UpperCAmelCase							 =		stderr







async def 	UpperCAmelCase     (		A	:						List[str]     ,				A	:						int       ):

		'''simple docstring'''


		while True:
				_UpperCAmelCase							 =		await stream.readline()
				if line:
						callback(A       )
				else:
						break




async def 	UpperCAmelCase     (		A	:						str     ,				A	:						Tuple=None     ,				A	:						List[str]=None     ,				A	:						Dict=None     ,				A	:						int=False     ,				A	:						Dict=False       ):

		'''simple docstring'''


		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	:						Optional[int]     ,				A	:						Optional[Any]     ,				A	:						Optional[int]     ,				A	:						Optional[Any]=""       ):
				_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 	UpperCAmelCase     (		A	:						Tuple     ,				A	:						Any=None     ,				A	:						Dict=None     ,				A	:						Optional[int]=180     ,				A	:						str=False     ,				A	:						Dict=True       ):

		'''simple docstring'''


		_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 	UpperCAmelCase     (		):

		'''simple docstring'''


		_UpperCAmelCase							 =		os.environ.get('PYTEST_XDIST_WORKER'     ,				'gw0'       )
		_UpperCAmelCase							 =		re.sub(r'^gw'     ,				''     ,				A     ,				0     ,				re.M       )
		return int(A       )





def 	UpperCAmelCase     (		):

		'''simple docstring'''


		_UpperCAmelCase							 =		2_9500
		_UpperCAmelCase							 =		pytest_xdist_worker_id()
		return port + uniq_delta







"""simple docstring"""





import unittest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TextaTextGenerationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch
from transformers.utils import is_torch_available

from .test_pipelines_common import ANY


if is_torch_available():
					import torch




@is_pipeline_test
class 			lowercase__			(      unittest.TestCase    ):
							'''simple docstring'''







							_UpperCAmelCase      				=					MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
							_UpperCAmelCase      				=					TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING






							def        lowerCamelCase_   (  self	,       snake_case	,       snake_case	,       snake_case						)			->							Dict:
									_UpperCAmelCase							 =		TextaTextGenerationPipeline(model=snake_case	,       tokenizer=snake_case						)
									return generator, ["Something to write", "Something else"]






							def        lowerCamelCase_   (  self	,       snake_case	,       snake_case						)			->							Dict:
									_UpperCAmelCase							 =		generator('Something there'						)
									self.assertEqual(snake_case	,       [{'generated_text': ANY(snake_case						)}]						)
									# These are encoder decoder, they don't just append to incoming string
									self.assertFalse(outputs[0]['generated_text'].startswith('Something there'						)						)

									_UpperCAmelCase							 =		generator(['This is great !', 'Something else']	,       num_return_sequences=2	,       do_sample=snake_case						)
									self.assertEqual(
									    snake_case	,       [
									        [{'generated_text': ANY(snake_case						)}, {'generated_text': ANY(snake_case						)}],
									        [{'generated_text': ANY(snake_case						)}, {'generated_text': ANY(snake_case						)}],
									    ]	,       )

									_UpperCAmelCase							 =		generator(
									    ['This is great !', 'Something else']	,       num_return_sequences=2	,       batch_size=2	,       do_sample=snake_case						)
									self.assertEqual(
									    snake_case	,       [
									        [{'generated_text': ANY(snake_case						)}, {'generated_text': ANY(snake_case						)}],
									        [{'generated_text': ANY(snake_case						)}, {'generated_text': ANY(snake_case						)}],
									    ]	,       )

									with self.assertRaises(snake_case						):
											generator(4						)






							@require_torch
							def        lowerCamelCase_   (  self						)			->							Dict:
									_UpperCAmelCase							 =		pipeline('text2text-generation'	,       model='patrickvonplaten/t5-tiny-random'	,       framework='pt'						)
									# do_sample=False necessary for reproducibility
									_UpperCAmelCase							 =		generator('Something there'	,       do_sample=snake_case						)
									self.assertEqual(snake_case	,       [{'generated_text': ''}]						)

									_UpperCAmelCase							 =		3
									_UpperCAmelCase							 =		generator(
									    'Something there'	,       num_return_sequences=snake_case	,       num_beams=snake_case	,       )
									_UpperCAmelCase							 =		[
									    {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'},
									    {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'},
									    {'generated_text': ''},
									]
									self.assertEqual(snake_case	,       snake_case						)

									_UpperCAmelCase							 =		generator('This is a test'	,       do_sample=snake_case	,       num_return_sequences=2	,       return_tensors=snake_case						)
									self.assertEqual(
									    snake_case	,       [
									        {'generated_token_ids': ANY(torch.Tensor						)},
									        {'generated_token_ids': ANY(torch.Tensor						)},
									    ]	,       )
									_UpperCAmelCase							 =		generator.model.config.eos_token_id
									_UpperCAmelCase							 =		'<pad>'
									_UpperCAmelCase							 =		generator(
									    ['This is a test', 'This is a second test']	,       do_sample=snake_case	,       num_return_sequences=2	,       batch_size=2	,       return_tensors=snake_case	,       )
									self.assertEqual(
									    snake_case	,       [
									        [
									            {'generated_token_ids': ANY(torch.Tensor						)},
									            {'generated_token_ids': ANY(torch.Tensor						)},
									        ],
									        [
									            {'generated_token_ids': ANY(torch.Tensor						)},
									            {'generated_token_ids': ANY(torch.Tensor						)},
									        ],
									    ]	,       )






							@require_tf
							def        lowerCamelCase_   (  self						)			->							Any:
									_UpperCAmelCase							 =		pipeline('text2text-generation'	,       model='patrickvonplaten/t5-tiny-random'	,       framework='tf'						)
									# do_sample=False necessary for reproducibility
									_UpperCAmelCase							 =		generator('Something there'	,       do_sample=snake_case						)
									self.assertEqual(snake_case	,       [{'generated_text': ''}]						)


