
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_			,			lowercase_=False )		->						str:


  '''simple docstring'''






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


lowerCamelCase__     :		str        = parse_flag_from_env("""RUN_SLOW""", default=False)
lowerCamelCase__     :		Union[str, Any]        = parse_flag_from_env("""RUN_REMOTE""", default=False)
lowerCamelCase__     :		int        = parse_flag_from_env("""RUN_LOCAL""", default=True)
lowerCamelCase__     :		Optional[Any]        = parse_flag_from_env("""RUN_PACKAGED""", default=True)

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

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

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

def 		UpperCamelCase						(   lowercase_ )		->						str:


  '''simple docstring'''






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

def 		UpperCamelCase						(   lowercase_ )		->						List[Any]:


  '''simple docstring'''






  try:
    import regex  # noqa
  except ImportError:
    lowercase__	: str     		=   unittest.skip("""test requires regex""" )(lowercase_ )
  return test_case

def 		UpperCamelCase						(   lowercase_ )		->						Union[str, Any]:


  '''simple docstring'''






  try:
    import elasticsearch  # noqa
  except ImportError:
    lowercase__	: Tuple     		=   unittest.skip("""test requires elasticsearch""" )(lowercase_ )
  return test_case

def 		UpperCamelCase						(   lowercase_ )		->						Dict:


  '''simple docstring'''






  try:
    import sqlalchemy  # noqa
  except ImportError:
    lowercase__	: str     		=   unittest.skip("""test requires sqlalchemy""" )(lowercase_ )
  return test_case

def 		UpperCamelCase						(   lowercase_ )		->						List[str]:


  '''simple docstring'''






  if not config.TORCH_AVAILABLE:
    lowercase__	: Any     		=   unittest.skip("""test requires PyTorch""" )(lowercase_ )
  return test_case

def 		UpperCamelCase						(   lowercase_ )		->						Union[str, Any]:


  '''simple docstring'''






  if not config.TF_AVAILABLE:
    lowercase__	: int     		=   unittest.skip("""test requires TensorFlow""" )(lowercase_ )
  return test_case

def 		UpperCamelCase						(   lowercase_ )		->						str:


  '''simple docstring'''






  if not config.JAX_AVAILABLE:
    lowercase__	: Any     		=   unittest.skip("""test requires JAX""" )(lowercase_ )
  return test_case

def 		UpperCamelCase						(   lowercase_ )		->						int:


  '''simple docstring'''






  if not config.PIL_AVAILABLE:
    lowercase__	: str     		=   unittest.skip("""test requires Pillow""" )(lowercase_ )
  return test_case

def 		UpperCamelCase						(   lowercase_ )		->						Any:


  '''simple docstring'''






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

def 		UpperCamelCase						(   lowercase_ )		->						Union[str, Any]:


  '''simple docstring'''






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

def 		UpperCamelCase						(   lowercase_ )		->						Dict:


  '''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_ ):
    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_ )		->						Optional[Any]:


  '''simple docstring'''






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

def 		UpperCamelCase						(   lowercase_ )		->						List[Any]:


  '''simple docstring'''






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

def 		UpperCamelCase						(   lowercase_ )		->						Optional[int]:


  '''simple docstring'''






  if not _run_slow_tests or _run_slow_tests == 0:
    lowercase__	: Union[str, Any]     		=   unittest.skip("""test is slow""" )(lowercase_ )
  return test_case

def 		UpperCamelCase						(   lowercase_ )		->						str:


  '''simple docstring'''






  if not _run_local_tests or _run_local_tests == 0:
    lowercase__	: Union[str, Any]     		=   unittest.skip("""test is local""" )(lowercase_ )
  return test_case

def 		UpperCamelCase						(   lowercase_ )		->						Any:


  '''simple docstring'''






  if not _run_packaged_tests or _run_packaged_tests == 0:
    lowercase__	: Union[str, Any]     		=   unittest.skip("""test is packaged""" )(lowercase_ )
  return test_case

def 		UpperCamelCase						(   lowercase_ )		->						Dict:


  '''simple docstring'''






  if not _run_remote_tests or _run_remote_tests == 0:
    lowercase__	: Tuple     		=   unittest.skip("""test requires remote""" )(lowercase_ )
  return test_case

def 		UpperCamelCase						(   *lowercase_ )		->						Optional[int]:


  '''simple docstring'''






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

  return decorate



class    _snake_case (						lowerCAmelCase__				):
 pass



class    _snake_case (						lowerCAmelCase__				):
 __lowerCAmelCase	:  Any	   =      0
 __lowerCAmelCase	:  Optional[int]	   =      1
 __lowerCAmelCase	:  Union[str, Any]	   =      2

@contextmanager
def 		UpperCamelCase						(   lowercase_=OfflineSimulationMode.CONNECTION_FAILS			,			lowercase_=1E-16 )		->						Dict:


  '''simple docstring'''






  lowercase__	: str     		=   requests.Session().request

  def timeout_request(lowercase_			,			lowercase_			,			lowercase_			,			**lowercase_ ):
    # Change the url to an invalid url so that the connection hangs
    lowercase__	: List[str]     		=   """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__	: List[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
      lowercase__	: Union[str, Any]     		=   url
      lowercase__	: Tuple     		=   e.args[0]
      lowercase__	: Any     		=   (max_retry_error.args[0].replace("""10.255.255.1"""			,			F'OfflineMock[{url}]' ),)
      lowercase__	: Optional[int]     		=   (max_retry_error,)
      raise

  def raise_connection_error(lowercase_			,			lowercase_			,			**lowercase_ ):
    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_			,			**lowercase_ )		->						List[Any]:


  '''simple docstring'''






  lowercase__	: Optional[Any]     		=   str(Path().resolve() )
  with tempfile.TemporaryDirectory(*lowercase_			,			**lowercase_ ) as tmp_dir:
    try:
      os.chdir(lowercase_ )
      yield
    finally:
      os.chdir(lowercase_ )

@contextmanager
def 		UpperCamelCase						(   )		->						str:


  '''simple docstring'''






  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 		UpperCamelCase						(   )		->						List[Any]:


  '''simple docstring'''






  import gc

  gc.collect()
  lowercase__	: 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_			,			lowercase_ )		->						Dict:


  '''simple docstring'''






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

def 		UpperCamelCase						(   lowercase_ )		->						List[str]:


  '''simple docstring'''






  import decorator
  from requests.exceptions import HTTPError

  def _wrapper(lowercase_			,			*lowercase_			,			**lowercase_ ):
    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    _snake_case :


 def __init__(       self       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_):


   '''simple docstring'''




   lowercase__	: Tuple     		=   returncode
   lowercase__	: Optional[int]     		=   stdout
   lowercase__	: List[Any]     		=   stderr

async def 		UpperCamelCase						(   lowercase_			,			lowercase_ )		->						Tuple:


  '''simple docstring'''






  while True:
    lowercase__	: Optional[Any]     		=   await stream.readline()
    if line:
      callback(lowercase_ )
    else:
      break

async def 		UpperCamelCase						(   lowercase_			,			lowercase_=None			,			lowercase_=None			,			lowercase_=None			,			lowercase_=False			,			lowercase_=False )		->						_RunOutput:


  '''simple docstring'''






  if echo:
    print("""\nRunning: """			,			""" """.join(lowercase_ ) )

  lowercase__	: str     		=   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)

  lowercase__	: List[str]     		=   []
  lowercase__	: Union[str, Any]     		=   []

  def tee(lowercase_			,			lowercase_			,			lowercase_			,			lowercase_="" ):
    lowercase__	: Optional[int]     		=   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_			,			lowercase_=None			,			lowercase_=None			,			lowercase_=1_80			,			lowercase_=False			,			lowercase_=True )		->						_RunOutput:


  '''simple docstring'''






  lowercase__	: List[Any]     		=   asyncio.get_event_loop()
  lowercase__	: Union[str, Any]     		=   loop.run_until_complete(
      _stream_subprocess(lowercase_			,			env=lowercase_			,			stdin=lowercase_			,			timeout=lowercase_			,			quiet=lowercase_			,			echo=lowercase_ ) )

  lowercase__	: Union[str, Any]     		=   """ """.join(lowercase_ )
  if result.returncode > 0:
    lowercase__	: List[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						(   )		->						Optional[Any]:


  '''simple docstring'''






  lowercase__	: Tuple     		=   os.environ.get("""PYTEST_XDIST_WORKER"""			,			"""gw0""" )
  lowercase__	: Union[str, Any]     		=   re.sub(R"""^gw"""			,			""""""			,			lowercase_			,			0			,			re.M )
  return int(lowercase_ )



def 		UpperCamelCase						(   )		->						str:


  '''simple docstring'''






  lowercase__	: List[str]     		=   2_95_00
  lowercase__	: Dict     		=   pytest_xdist_worker_id()
  return port + uniq_delta









"""simple docstring"""
import unittest

import numpy as np
import torch

from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad

class       lowerCamelCase	(       unittest.TestCase   ):


  '''simple docstring'''







  def  _a      (self	):


        """simple docstring"""

        UpperCAmelCase__			:							List[str]							=    10



  def  _a      (self	):


        """simple docstring"""

        UpperCAmelCase__			:							List[str]							=    [1, 2, 3, 4]
        UpperCAmelCase__			:							Tuple							=    [1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
        self.assertEqual(truncate_or_pad(_lowerCamelCase							,       self.block_size							,       0	)							,       _lowerCamelCase	)



  def  _a      (self	):


        """simple docstring"""

        UpperCAmelCase__			:							Optional[int]							=    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        UpperCAmelCase__			:							Tuple							=    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        self.assertEqual(truncate_or_pad(_lowerCamelCase							,       self.block_size							,       0	)							,       _lowerCamelCase	)



  def  _a      (self	):


        """simple docstring"""

        UpperCAmelCase__			:							Tuple							=    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
        UpperCAmelCase__			:							Dict							=    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        self.assertEqual(truncate_or_pad(_lowerCamelCase							,       self.block_size							,       0	)							,       _lowerCamelCase	)



  def  _a      (self	):


        """simple docstring"""

        UpperCAmelCase__			:							Any							=    """It was the year of Our Lord one thousand seven hundred and
        seventy-five.\n\nSpiritual revelations were conceded to England at that
        favoured period, as at this."""
        UpperCAmelCase__					,		UpperCAmelCase__			:							Any							=    process_story(_lowerCamelCase	)
        self.assertEqual(_lowerCamelCase							,       []	)



  def  _a      (self	):


        """simple docstring"""

        UpperCAmelCase__			:							str							=    """"""
        UpperCAmelCase__					,		UpperCAmelCase__			:							List[Any]							=    process_story(_lowerCamelCase	)
        self.assertEqual(_lowerCamelCase							,       []	)
        self.assertEqual(_lowerCamelCase							,       []	)



  def  _a      (self	):


        """simple docstring"""

        UpperCAmelCase__			:							Optional[Any]							=    (
            """It was the year of Our Lord one thousand seven hundred and """
            """seventy-five\n\nSpiritual revelations were conceded to England """
            """at that favoured period, as at this.\n@highlight\n\nIt was the best of times"""
        )
        UpperCAmelCase__					,		UpperCAmelCase__			:							Optional[Any]							=    process_story(_lowerCamelCase	)

        UpperCAmelCase__			:							List[Any]							=    [
            """It was the year of Our Lord one thousand seven hundred and seventy-five.""",
            """Spiritual revelations were conceded to England at that favoured period, as at this.""",
        ]
        self.assertEqual(_lowerCamelCase							,       _lowerCamelCase	)

        UpperCAmelCase__			:							List[Any]							=    ["""It was the best of times."""]
        self.assertEqual(_lowerCamelCase							,       _lowerCamelCase	)



  def  _a      (self	):


        """simple docstring"""

        UpperCAmelCase__			:							str							=    torch.tensor([1, 2, 3, 4]	)
        UpperCAmelCase__			:							str							=    torch.tensor([1, 1, 1, 1]	)
        np.testing.assert_array_equal(build_mask(_lowerCamelCase							,       0	).numpy()							,       expected.numpy()	)



  def  _a      (self	):


        """simple docstring"""

        UpperCAmelCase__			:							List[str]							=    torch.tensor([1, 2, 3, 4, 23, 23, 23]	)
        UpperCAmelCase__			:							Union[str, Any]							=    torch.tensor([1, 1, 1, 1, 0, 0, 0]	)
        np.testing.assert_array_equal(build_mask(_lowerCamelCase							,       23	).numpy()							,       expected.numpy()	)



  def  _a      (self	):


        """simple docstring"""

        UpperCAmelCase__			:							Optional[Any]							=    torch.tensor([8, 2, 3, 4, 1, 1, 1]	)
        UpperCAmelCase__			:							Any							=    torch.tensor([1, 1, 1, 1, 0, 0, 0]	)
        np.testing.assert_array_equal(build_mask(_lowerCamelCase							,       1	).numpy()							,       expected.numpy()	)




  def  _a      (self	):


        """simple docstring"""

        UpperCAmelCase__			:							Any							=    101
        UpperCAmelCase__			:							Dict							=    torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]]	)
        UpperCAmelCase__			:							Optional[Any]							=    torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]]	)

        UpperCAmelCase__			:							int							=    compute_token_type_ids(_lowerCamelCase							,       _lowerCamelCase	)
        np.testing.assert_array_equal(_lowerCamelCase							,       _lowerCamelCase	)

