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							)     ->				Any:







      '''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


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    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


      try:
            import faiss  # noqa
      except ImportError:
            UpperCAmelCase__								=  unittest.skip("test requires faiss"							)(__A							)
      return test_case




def    lowerCAmelCase_ (     __A							)     ->				Optional[Any]:







      '''simple docstring'''


      try:
            import regex  # noqa
      except ImportError:
            UpperCAmelCase__								=  unittest.skip("test requires regex"							)(__A							)
      return test_case




def    lowerCAmelCase_ (     __A							)     ->				List[str]:







      '''simple docstring'''


      try:
            import elasticsearch  # noqa
      except ImportError:
            UpperCAmelCase__								=  unittest.skip("test requires elasticsearch"							)(__A							)
      return test_case




def    lowerCAmelCase_ (     __A							)     ->				List[Any]:







      '''simple docstring'''


      try:
            import sqlalchemy  # noqa
      except ImportError:
            UpperCAmelCase__								=  unittest.skip("test requires sqlalchemy"							)(__A							)
      return test_case




def    lowerCAmelCase_ (     __A							)     ->				List[str]:







      '''simple docstring'''


      if not config.TORCH_AVAILABLE:
            UpperCAmelCase__								=  unittest.skip("test requires PyTorch"							)(__A							)
      return test_case




def    lowerCAmelCase_ (     __A							)     ->				Union[str, Any]:







      '''simple docstring'''


      if not config.TF_AVAILABLE:
            UpperCAmelCase__								=  unittest.skip("test requires TensorFlow"							)(__A							)
      return test_case




def    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


      if not config.JAX_AVAILABLE:
            UpperCAmelCase__								=  unittest.skip("test requires JAX"							)(__A							)
      return test_case




def    lowerCAmelCase_ (     __A							)     ->				int:







      '''simple docstring'''


      if not config.PIL_AVAILABLE:
            UpperCAmelCase__								=  unittest.skip("test requires Pillow"							)(__A							)
      return test_case




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Dict:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Optional[Any]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


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







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      if not _run_slow_tests or _run_slow_tests == 0:
            UpperCAmelCase__								=  unittest.skip("test is slow"							)(__A							)
      return test_case




def    lowerCAmelCase_ (     __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    lowerCAmelCase_ (     __A							)     ->				Optional[Any]:







      '''simple docstring'''


      if not _run_packaged_tests or _run_packaged_tests == 0:
            UpperCAmelCase__								=  unittest.skip("test is packaged"							)(__A							)
      return test_case




def    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


      if not _run_remote_tests or _run_remote_tests == 0:
            UpperCAmelCase__								=  unittest.skip("test requires remote"							)(__A							)
      return test_case




def    lowerCAmelCase_ (     *__A							)     ->				Optional[int]:







      '''simple docstring'''


      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      A							(				UpperCAmelCase_     ):
   pass





class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : Union[str, Any]      =			0
   __UpperCAmelCase : str      =			1
   __UpperCAmelCase : int      =			2




@contextmanager
def    lowerCAmelCase_ (     __A=OfflineSimulationMode.CONNECTION_FAILS,  __A=1e-16							)     ->				List[str]:







      '''simple docstring'''


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







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







      '''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    lowerCAmelCase_ (     )     ->				List[str]:







      '''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    lowerCAmelCase_ (     __A,  __A							)     ->				List[str]:







      '''simple docstring'''


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




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      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      A							:


   def __init__(self     :						Optional[Any]       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						List[str]		)						->				Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  returncode
         UpperCAmelCase__								=  stdout
         UpperCAmelCase__								=  stderr




async def    lowerCAmelCase_ (     __A,  __A							)     ->				Optional[int]:







      '''simple docstring'''


      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							)     ->				_RunOutput:







      '''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,  __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							)     ->				_RunOutput:







      '''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    lowerCAmelCase_ (     )     ->				Tuple:







      '''simple docstring'''


      UpperCAmelCase__								=  os.environ.get("PYTEST_XDIST_WORKER",  "gw0"							)
      UpperCAmelCase__								=  re.sub(r"^gw",  "",  __A,  0,  re.M							)
      return int(__A							)







def    lowerCAmelCase_ (     )     ->				List[Any]:







      '''simple docstring'''


      UpperCAmelCase__								=  29_500
      UpperCAmelCase__								=  pytest_xdist_worker_id()
      return port + uniq_delta










"""simple docstring"""




from datetime import datetime

import requests






def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    str					) ->bytes:






	'''simple docstring'''






	a      :		Dict	=				"https://downloadgram.net/wp-json/wppress/video-downloader/video?url="
	a      :		Dict	=				requests.get(base_url + url					).json()[0]["urls"][0]["src"]
	return requests.get(_lowercase					).content


if __name__ == "__main__":
		a						: str     	=			input('''Enter Video/IGTV url: ''').strip()
		a						: Any     	=			F'''{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4'''
		with open(file_name, '''wb''') as fp:
				fp.write(download_video(url))
		print(F'''Done. Video saved to disk as {file_name}.''')


