





import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)





def      lowerCAmelCase_ (       __a	,    __a=False		)     ->		Union[str, Any]:







  """simple docstring"""





  try:
    lowerCamelCase__:      Optional[int]			  =os.environ[key]
  except KeyError:
    # KEY isn't set, default to `default`.
    lowerCamelCase__:      int			  =default
  else:
    # KEY is set, convert it to True or False.
    try:
      lowerCamelCase__:      List[str]			  =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									=				parse_flag_from_env("RUN_SLOW", default=False)





def      lowerCAmelCase_ (       __a		)     ->		int:







  """simple docstring"""





  return unittest.skip("Test was skipped"		)(__a		)





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







  """simple docstring"""





  return unittest.skipUnless(_run_slow_tests	,    "test is slow"		)(__a		)





def      lowerCAmelCase_ (       __a		)     ->		str:







  """simple docstring"""





  return unittest.skipUnless(not torch.cuda.is_available()	,    "test requires only a CPU"		)(__a		)





def      lowerCAmelCase_ (       __a		)     ->		Dict:







  """simple docstring"""





  return unittest.skipUnless(torch.cuda.is_available()	,    "test requires a GPU"		)(__a		)





def      lowerCAmelCase_ (       __a		)     ->		Tuple:







  """simple docstring"""





  return unittest.skipUnless(is_xpu_available()	,    "test requires a XPU"		)(__a		)





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







  """simple docstring"""





  return unittest.skipUnless(is_mps_available()	,    "test requires a `mps` backend support in `torch`"		)(__a		)





def      lowerCAmelCase_ (       __a		)     ->		int:







  """simple docstring"""





  return unittest.skipUnless(
      is_transformers_available() and is_datasets_available()	,    "test requires the Hugging Face suite"		)(__a		)





def      lowerCAmelCase_ (       __a		)     ->		Dict:







  """simple docstring"""





  return unittest.skipUnless(is_bnb_available()	,    "test requires the bitsandbytes library"		)(__a		)





def      lowerCAmelCase_ (       __a		)     ->		str:







  """simple docstring"""





  return unittest.skipUnless(is_tpu_available()	,    "test requires TPU"		)(__a		)





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







  """simple docstring"""





  return unittest.skipUnless(torch.cuda.device_count() == 1	,    "test requires a GPU"		)(__a		)





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







  """simple docstring"""





  return unittest.skipUnless(torch.xpu.device_count() == 1	,    "test requires a XPU"		)(__a		)





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







  """simple docstring"""





  return unittest.skipUnless(torch.cuda.device_count() > 1	,    "test requires multiple GPUs"		)(__a		)





def      lowerCAmelCase_ (       __a		)     ->		Tuple:







  """simple docstring"""





  return unittest.skipUnless(torch.xpu.device_count() > 1	,    "test requires multiple XPUs"		)(__a		)





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







  """simple docstring"""





  return unittest.skipUnless(is_safetensors_available()	,    "test requires safetensors"		)(__a		)





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







  """simple docstring"""





  return unittest.skipUnless(is_deepspeed_available()	,    "test requires DeepSpeed"		)(__a		)





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







  """simple docstring"""





  return unittest.skipUnless(is_torch_version(">="	,    "1.12.0"		)	,    "test requires torch version >= 1.12.0"		)(__a		)





def      lowerCAmelCase_ (       __a=None	,    __a=None		)     ->		int:







  """simple docstring"""





  if test_case is None:
    return partial(__a	,    version=__a		)
  return unittest.skipUnless(is_torch_version(">="	,    __a		)	,    F"""test requires torch version >= {version}"""		)(__a		)





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







  """simple docstring"""





  return unittest.skipUnless(is_tensorboard_available()	,    "test requires Tensorboard"		)(__a		)





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







  """simple docstring"""





  return unittest.skipUnless(is_wandb_available()	,    "test requires wandb"		)(__a		)





def      lowerCAmelCase_ (       __a		)     ->		Tuple:







  """simple docstring"""





  return unittest.skipUnless(is_comet_ml_available()	,    "test requires comet_ml"		)(__a		)


__A									=				(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)





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







  """simple docstring"""





  return unittest.skipUnless(
      _atleast_one_tracker_available	,    "test requires at least one tracker to be available and for `comet_ml` to not be installed"	,    )(__a		)



class    _SCREAMING_SNAKE_CASE						(	unittest.TestCase    ):







 '''simple docstring'''
 lowercase_		=			True

 @classmethod
 def 							SCREAMING_SNAKE_CASE_					(cls				:   Optional[int])       ->str:



   '''simple docstring'''



   lowerCamelCase__:      Dict			  =tempfile.mkdtemp()

 @classmethod
 def 							SCREAMING_SNAKE_CASE_					(cls				:   str)       ->int:



   '''simple docstring'''



   if os.path.exists(cls.tmpdir):
     shutil.rmtree(cls.tmpdir)







 def 							SCREAMING_SNAKE_CASE_					(self				:   Optional[Any])       ->Optional[Any]:



   '''simple docstring'''



   if self.clear_on_setup:
     for path in Path(self.tmpdir).glob("**/*"):
       if path.is_file():
         path.unlink()
       elif path.is_dir():
         shutil.rmtree(snake_case__)



class    _SCREAMING_SNAKE_CASE						(	unittest.TestCase    ):







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_					(self				:   str)       ->List[Any]:



   '''simple docstring'''



   super().tearDown()
   # Reset the state of the AcceleratorState singleton.
   AcceleratorState._reset_state()
   PartialState._reset_state()



class    _SCREAMING_SNAKE_CASE						(	unittest.TestCase    ):







 '''simple docstring'''

 def 							SCREAMING_SNAKE_CASE_					(self				:   List[Any]       , UpperCAmelCase_				:   Dict)       ->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__:      Tuple			  =mocks if isinstance(snake_case__       , (tuple, list)) else [mocks]
   for m in self.mocks:
     m.start()
     self.addCleanup(m.stop)





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







  """simple docstring"""





  lowerCamelCase__:      List[str]			  =AcceleratorState()
  lowerCamelCase__:      Dict			  =tensor[None].clone().to(state.device		)
  lowerCamelCase__:      str			  =gather(__a		).cpu()
  lowerCamelCase__:      List[Any]			  =tensor[0].cpu()
  for i in range(tensors.shape[0]		):
    if not torch.equal(tensors[i]	,    __a		):
      return False
  return True



class    _SCREAMING_SNAKE_CASE						:







 '''simple docstring'''

 def __init__(self				:   Optional[Any]       , UpperCAmelCase_				:   Optional[int]       , UpperCAmelCase_				:   Tuple       , UpperCAmelCase_				:   Union[str, Any])       ->List[str]:



   '''simple docstring'''



   lowerCamelCase__:      Any			  =returncode
   lowerCamelCase__:      Optional[int]			  =stdout
   lowerCamelCase__:      str			  =stderr





async def      lowerCAmelCase_ (       __a	,    __a		)     ->		Optional[Any]:







  """simple docstring"""





  while True:
    lowerCamelCase__:      Tuple			  =await stream.readline()
    if line:
      callback(__a		)
    else:
      break





async def      lowerCAmelCase_ (       __a	,    __a=None	,    __a=None	,    __a=None	,    __a=False	,    __a=False		)     ->		int:







  """simple docstring"""





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

  lowerCamelCase__:      List[str]			  =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)

  lowerCamelCase__:      Dict			  =[]
  lowerCamelCase__:      Dict			  =[]

  def tee(__a	,    __a	,    __a	,    __a=""		):
    lowerCamelCase__:      List[Any]			  =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(
      [
          asyncio.create_task(_read_stream(p.stdout	,    lambda __a		: tee(__a	,    __a	,    sys.stdout	,    label="stdout:"		)		)		),
          asyncio.create_task(_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		)     ->		Any:







  """simple docstring"""





  lowerCamelCase__:      Any			  =asyncio.get_event_loop()
  lowerCamelCase__:      Optional[int]			  =loop.run_until_complete(
      _stream_subprocess(__a	,    env=__a	,    stdin=__a	,    timeout=__a	,    quiet=__a	,    echo=__a		)		)

  lowerCamelCase__:      Tuple			  =" ".join(__a		)
  if result.returncode > 0:
    lowerCamelCase__:      int			  ="\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}"""		)

  return result



class    _SCREAMING_SNAKE_CASE						(	__SCREAMING_SNAKE_CASE    ):







 '''simple docstring'''
 pass





def      lowerCAmelCase_ (       __a	,    __a=False		)     ->		Any:







  """simple docstring"""





  try:
    lowerCamelCase__:      List[Any]			  =subprocess.check_output(__a	,    stderr=subprocess.STDOUT		)
    if return_stdout:
      if hasattr(__a	,    "decode"		):
        lowerCamelCase__:      Union[str, Any]			  =output.decode("utf-8"		)
      return output
  except subprocess.CalledProcessError as e:
    raise SubprocessCallException(
        F"""Command `{" ".join(__a		)}` failed with the following error:\n\n{e.output.decode()}"""		) from e





"""simple docstring"""







# Lint as: python3
import os
import re
import urllib.parse
from pathlib import Path
from typing import Callable, List, Optional, Union
from zipfile import ZipFile

from ..utils.file_utils import cached_path, hf_github_url
from ..utils.logging import get_logger
from ..utils.version import Version


lowerCAmelCase__      				=   get_logger(__name__)


class       SCREAMING_SNAKE_CASE__				:
       """simple docstring"""


       a  :				Optional[Any]   ="dummy_data"
       a  :				int   ="datasets"
       a  :				Tuple   =False

       def __init__(						self		,     snake_case__		,     snake_case__		,     snake_case__		,     snake_case__ = None		,     snake_case__ = False		,     snake_case__ = True		,     snake_case__ = None		,     ):






         """simple docstring"""





         lowerCAmelCase     :     Tuple								=							0
         lowerCAmelCase     :     int								=							dataset_name
         lowerCAmelCase     :     List[Any]								=							cache_dir
         lowerCAmelCase     :     List[str]								=							use_local_dummy_data
         lowerCAmelCase     :     List[str]								=							config
         # download_callbacks take a single url as input
         lowerCAmelCase     :     List[Callable]								=							download_callbacks or []
         # if False, it doesn't load existing files and it returns the paths of the dummy files relative
         # to the dummy_data zip file root
         lowerCAmelCase     :     Tuple								=							load_existing_dummy_data

         # TODO(PVP, QL) might need to make this more general
         lowerCAmelCase     :     Union[str, Any]								=							str(snake_case__						)
         # to be downloaded
         lowerCAmelCase     :     List[Any]								=							None
         lowerCAmelCase     :     List[Any]								=							None

       @property
       def        lowercase__							(						self						):






         """simple docstring"""





         if self._dummy_file is None:
           lowerCAmelCase     :     Any								=							self.download_dummy_data()
         return self._dummy_file

       @property
       def        lowercase__							(						self						):






         """simple docstring"""





         if self.config is not None:
           # structure is dummy / config_name / version_name
           return os.path.join("dummy"		,     self.config.name		,     self.version_name						)
         # structure is dummy / version_name
         return os.path.join("dummy"		,     self.version_name						)

       @property
       def        lowercase__							(						self						):






         """simple docstring"""





         return os.path.join(self.dummy_data_folder		,     "dummy_data.zip"						)

       def        lowercase__							(						self						):






         """simple docstring"""





         lowerCAmelCase     :     Optional[Any]								=							(
             self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data
         )

         lowerCAmelCase     :     str								=							cached_path(
             snake_case__		,     cache_dir=self.cache_dir		,     extract_compressed_file=snake_case__		,     force_extract=snake_case__						)

         return os.path.join(snake_case__		,     self.dummy_file_name						)

       @property
       def        lowercase__							(						self						):






         """simple docstring"""





         return os.path.join(self.datasets_scripts_dir		,     self.dataset_name		,     self.dummy_zip_file						)

       @property
       def        lowercase__							(						self						):






         """simple docstring"""





         if self._bucket_url is None:
           lowerCAmelCase     :     Union[str, Any]								=							hf_github_url(self.dataset_name		,     self.dummy_zip_file.replace(os.sep		,     "/"						)						)
         return self._bucket_url

       @property
       def        lowercase__							(						self						):






         """simple docstring"""





         if os.path.isdir(self.dummy_file						):
           return self.dummy_file
         # else cut off path to file -> example `xsum`.
         return "/".join(self.dummy_file.replace(os.sep		,     "/"						).split("/"						)[:-1]						)

       def        lowercase__							(						self		,     snake_case__		,     *snake_case__						):






         """simple docstring"""





         if self.load_existing_dummy_data:
           # dummy data is downloaded and tested
           lowerCAmelCase     :     int								=							self.dummy_file
         else:
           # dummy data cannot be downloaded and only the path to dummy file is returned
           lowerCAmelCase     :     List[Any]								=							self.dummy_file_name

         # special case when data_url is a dict
         if isinstance(snake_case__		,     snake_case__						):
           return self.create_dummy_data_dict(snake_case__		,     snake_case__						)
         elif isinstance(snake_case__		,     (list, tuple)						):
           return self.create_dummy_data_list(snake_case__		,     snake_case__						)
         else:
           return self.create_dummy_data_single(snake_case__		,     snake_case__						)

       def        lowercase__							(						self		,     snake_case__		,     *snake_case__						):






         """simple docstring"""





         return self.download_and_extract(snake_case__						)

       def        lowercase__							(						self		,     snake_case__		,     snake_case__						):






         """simple docstring"""





         return self.download_and_extract(snake_case__						)

       def        lowercase__							(						self		,     snake_case__		,     *snake_case__		,     **snake_case__						):






         """simple docstring"""





         return path

       def        lowercase__							(						self						):






         """simple docstring"""





         return {}

       def        lowercase__							(						self		,     snake_case__		,     snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     List[Any]								=							{}
         for key, single_urls in data_url.items():
           for download_callback in self.download_callbacks:
             if isinstance(snake_case__		,     snake_case__						):
               for single_url in single_urls:
                 download_callback(snake_case__						)
             else:
               lowerCAmelCase     :     List[str]								=							single_urls
               download_callback(snake_case__						)
            # we force the name of each key to be the last file / folder name of the url path
            # if the url has arguments, we need to encode them with urllib.parse.quote_plus
           if isinstance(snake_case__		,     snake_case__						):
             lowerCAmelCase     :     Tuple								=							[os.path.join(snake_case__		,     urllib.parse.quote_plus(Path(snake_case__						).name						)						) for x in single_urls]
           else:
             lowerCAmelCase     :     int								=							single_urls
             lowerCAmelCase     :     Any								=							os.path.join(snake_case__		,     urllib.parse.quote_plus(Path(snake_case__						).name						)						)
           lowerCAmelCase     :     Union[str, Any]								=							value

         # make sure that values are unique
         if all(isinstance(snake_case__		,     snake_case__						) for i in dummy_data_dict.values()						) and len(set(dummy_data_dict.values()						)						) < len(
             dummy_data_dict.values()						):
           # append key to value to make its name unique
           lowerCAmelCase     :     Union[str, Any]								=							{key: value + key for key, value in dummy_data_dict.items()}

         return dummy_data_dict

       def        lowercase__							(						self		,     snake_case__		,     snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     Dict								=							[]
         # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one
         lowerCAmelCase     :     Optional[Any]								=							all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}"		,     snake_case__						)						) for url in data_url						)
         lowerCAmelCase     :     Any								=							all(
             url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed"						) for url in data_url						)
         if data_url and (is_tf_records or is_pubmed_records):
           lowerCAmelCase     :     int								=							[data_url[0]] * len(snake_case__						)
         for single_url in data_url:
           for download_callback in self.download_callbacks:
             download_callback(snake_case__						)
           # we force the name of each key to be the last file / folder name of the url path
           # if the url has arguments, we need to encode them with urllib.parse.quote_plus
           lowerCAmelCase     :     Dict								=							os.path.join(snake_case__		,     urllib.parse.quote_plus(single_url.split("/"						)[-1]						)						)
           dummy_data_list.append(snake_case__						)
         return dummy_data_list

       def        lowercase__							(						self		,     snake_case__		,     snake_case__						):






         """simple docstring"""





         for download_callback in self.download_callbacks:
           download_callback(snake_case__						)
         # we force the name of each key to be the last file / folder name of the url path
         # if the url has arguments, we need to encode them with urllib.parse.quote_plus
         lowerCAmelCase     :     Tuple								=							os.path.join(snake_case__		,     urllib.parse.quote_plus(data_url.split("/"						)[-1]						)						)
         if os.path.exists(snake_case__						) or not self.load_existing_dummy_data:
           return value
         else:
           # Backward compatibility, maybe deprecate at one point.
           # For many datasets with single url calls to dl_manager.download_and_extract,
           # the dummy_data.zip file is actually the zipped downloaded file
           # while now we expected the dummy_data.zip file to be a directory containing
           # the downloaded file.
           return path_to_dummy_data

       def        lowercase__							(						self						):






         """simple docstring"""





         pass

       def        lowercase__							(						self						):






         """simple docstring"""





         pass

       def        lowercase__							(						self		,     snake_case__						):






         """simple docstring"""





         def _iter_archive_members(snake_case__						):
           # this preserves the order of the members inside the ZIP archive
           lowerCAmelCase     :     str								=							Path(self.dummy_file						).parent
           lowerCAmelCase     :     Optional[Any]								=							path.relative_to(snake_case__						)
           with ZipFile(self.local_path_to_dummy_data						) as zip_file:
             lowerCAmelCase     :     List[Any]								=							zip_file.namelist()
           for member in members:
             if member.startswith(relative_path.as_posix()						):
               yield dummy_parent_path.joinpath(snake_case__						)

         lowerCAmelCase     :     List[Any]								=							Path(snake_case__						)
         lowerCAmelCase     :     str								=							_iter_archive_members(snake_case__						) if self.use_local_dummy_data else path.rglob("*"						)
         for file_path in file_paths:
           if file_path.is_file() and not file_path.name.startswith((".", "__")						):
             yield file_path.relative_to(snake_case__						).as_posix(), file_path.open("rb"						)







       def        lowercase__							(						self		,     snake_case__						):






         """simple docstring"""





         if not isinstance(snake_case__		,     snake_case__						):
           lowerCAmelCase     :     List[Any]								=							[paths]
         for path in paths:
           if os.path.isfile(snake_case__						):
             if os.path.basename(snake_case__						).startswith((".", "__")						):
               return
             yield path
           else:
             for dirpath, dirnames, filenames in os.walk(snake_case__						):
               if os.path.basename(snake_case__						).startswith((".", "__")						):
                 continue
               dirnames.sort()
               for filename in sorted(snake_case__						):
                 if filename.startswith((".", "__")						):
                   continue
                 yield os.path.join(snake_case__		,     snake_case__						)





