





import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


lowercase      :       Dict									=  get_logger(__name__)





class  A__    :




   """simple docstring"""



   def __init__(					self					,  lowercase = None)			->						str:







          '''simple docstring'''

          a__						:	Union[str, Any] =				(
              os.path.join(lowercase					,  config.EXTRACTED_DATASETS_DIR) if cache_dir else config.EXTRACTED_DATASETS_PATH
          )
          a__						:	Union[str, Any] =				Extractor

   def 							__lowercase		(					self					,  lowercase)			->						str:







          '''simple docstring'''

          from .file_utils import hash_url_to_filename

          # Path where we extract compressed archives
          # We extract in the cache dir, and get the extracted path name by hashing the original path"
          a__						:	str =				os.path.abspath(lowercase)
          return os.path.join(self.extract_dir					,  hash_url_to_filename(lowercase))

   def 							__lowercase		(					self					,  lowercase					,  lowercase)			->						bool:







          '''simple docstring'''

          return force_extract or (
              not os.path.isfile(lowercase) and not (os.path.isdir(lowercase) and os.listdir(lowercase))
          )

   def 							__lowercase		(					self					,  lowercase					,  lowercase = False)			->						str:







          '''simple docstring'''

          a__						:	List[Any] =				self.extractor.infer_extractor_format(lowercase)
          if not extractor_format:
                 return input_path
          a__						:	Union[str, Any] =				self._get_output_path(lowercase)
          if self._do_extract(lowercase					,  lowercase):
                 self.extractor.extract(lowercase					,  lowercase					,  lowercase)
          return output_path





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   @classmethod
   @abstractmethod
   def 							__lowercase		(					cls					,  lowercase					,  **lowercase)			->						bool:







          '''simple docstring'''

          ...

   @staticmethod
   @abstractmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						None:







          '''simple docstring'''

          ...





class  A__    (							__UpperCAmelCase ,  __UpperCAmelCase	):




   """simple docstring"""



   __A   :				List[bytes]         =  []

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						Union[str, Any]:







          '''simple docstring'''

          with open(lowercase					,  'rb') as f:
                 return f.read(lowercase)

   @classmethod
   def 							__lowercase		(					cls					,  lowercase					,  lowercase = b"")			->						bool:







          '''simple docstring'''

          if not magic_number:
                 a__						:	Dict =				max(len(lowercase) for cls_magic_number in cls.magic_numbers)
                 try:
                        a__						:	List[Any] =				cls.read_magic_number(lowercase					,  lowercase)
                 except OSError:
                        return False
          return any(magic_number.startswith(lowercase) for cls_magic_number in cls.magic_numbers)





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   @classmethod
   def 							__lowercase		(					cls					,  lowercase					,  **lowercase)			->						bool:







          '''simple docstring'''

          return tarfile.is_tarfile(lowercase)

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						Dict:







          '''simple docstring'''

          def resolved(lowercase) -> str:
                 return os.path.realpath(os.path.abspath(lowercase))

          def badpath(lowercase					,  lowercase) -> bool:
                 # joinpath will ignore base if path is absolute
                 return not resolved(os.path.join(lowercase					,  lowercase)).startswith(lowercase)

          def badlink(lowercase					,  lowercase) -> bool:
                 # Links are interpreted relative to the directory containing the link
                 a__						:	Optional[int] =				resolved(os.path.join(lowercase					,  os.path.dirname(info.name)))
                 return badpath(info.linkname					,  base=lowercase)

          a__						:	int =				resolved(lowercase)

          for finfo in members:
                 if badpath(finfo.name					,  lowercase):
                        logger.error(F'Extraction of {finfo.name} is blocked (illegal path)')
                 elif finfo.issym() and badlink(lowercase					,  lowercase):
                        logger.error(F'Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}')
                 elif finfo.islnk() and badlink(lowercase					,  lowercase):
                        logger.error(F'Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}')
                 else:
                        yield finfo

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						None:







          '''simple docstring'''

          os.makedirs(lowercase					,  exist_ok=lowercase)
          a__						:	Optional[Any] =				tarfile.open(lowercase)
          tar_file.extractall(lowercase					,  members=TarExtractor.safemembers(lowercase					,  lowercase))
          tar_file.close()





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   __A   :				List[str]         =  [b'''\x1F\x8B''']

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						None:







          '''simple docstring'''

          with gzip.open(lowercase					,  'rb') as gzip_file:
                 with open(lowercase					,  'wb') as extracted_file:
                        shutil.copyfileobj(lowercase					,  lowercase)





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   __A   :				Optional[int]         =  [
       b'''PK\x03\x04''',
       b'''PK\x05\x06''',  # empty archive
       b'''PK\x07\x08''',  # spanned archive
   ]

   @classmethod
   def 							__lowercase		(					cls					,  lowercase					,  lowercase = b"")			->						bool:







          '''simple docstring'''

          if super().is_extractable(lowercase					,  magic_number=lowercase):
                 return True
          try:
                 # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
                 # From: https://github.com/python/cpython/pull/5053
                 from zipfile import (
                     _CD_SIGNATURE,
                     _ECD_DISK_NUMBER,
                     _ECD_DISK_START,
                     _ECD_ENTRIES_TOTAL,
                     _ECD_OFFSET,
                     _ECD_SIZE,
                     _EndRecData,
                     sizeCentralDir,
                     stringCentralDir,
                     structCentralDir,
                 )

                 with open(lowercase					,  'rb') as fp:
                        a__						:	Tuple =				_EndRecData(lowercase)
                        if endrec:
                               if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
                                      return True  # Empty zipfiles are still zipfiles
                               elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
                                      fp.seek(endrec[_ECD_OFFSET])  # Central directory is on the same disk
                                      if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
                                             a__						:	Dict =				fp.read(lowercase)  # CD is where we expect it to be
                                             if len(lowercase) == sizeCentralDir:
                                                    a__						:	Any =				struct.unpack(lowercase					,  lowercase)  # CD is the right size
                                                    if centdir[_CD_SIGNATURE] == stringCentralDir:
                                                           return True  # First central directory entry  has correct magic number
                 return False
          except Exception:  # catch all errors in case future python versions change the zipfile internals
                 return False

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						None:







          '''simple docstring'''

          os.makedirs(lowercase					,  exist_ok=lowercase)
          with zipfile.ZipFile(lowercase					,  'r') as zip_file:
                 zip_file.extractall(lowercase)
                 zip_file.close()





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   __A   :				List[Any]         =  [b'''\xFD\x37\x7A\x58\x5A\x00''']

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						None:







          '''simple docstring'''

          with lzma.open(lowercase) as compressed_file:
                 with open(lowercase					,  'wb') as extracted_file:
                        shutil.copyfileobj(lowercase					,  lowercase)





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   __A   :				int         =  [b'''Rar!\x1a\x07\x00''', b'''Rar!\x1a\x07\x01\x00''']  # RAR_ID  # RAR5_ID

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						None:







          '''simple docstring'''

          if not config.RARFILE_AVAILABLE:
                 raise ImportError('Please pip install rarfile')
          import rarfile

          os.makedirs(lowercase					,  exist_ok=lowercase)
          a__						:	Union[str, Any] =				rarfile.RarFile(lowercase)
          rf.extractall(lowercase)
          rf.close()





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   __A   :				Optional[int]         =  [b'''\x28\xb5\x2F\xFD''']

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						None:







          '''simple docstring'''

          if not config.ZSTANDARD_AVAILABLE:
                 raise ImportError('Please pip install zstandard')
          import zstandard as zstd

          a__						:	str =				zstd.ZstdDecompressor()
          with open(lowercase					,  'rb') as ifh, open(lowercase					,  'wb') as ofh:
                 dctx.copy_stream(lowercase					,  lowercase)





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   __A   :				Optional[Any]         =  [b'''\x42\x5A\x68''']

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						None:







          '''simple docstring'''

          with bza.open(lowercase					,  'rb') as compressed_file:
                 with open(lowercase					,  'wb') as extracted_file:
                        shutil.copyfileobj(lowercase					,  lowercase)





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   __A   :				Union[str, Any]         =  [b'''\x37\x7A\xBC\xAF\x27\x1C''']

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						None:







          '''simple docstring'''

          if not config.PY7ZR_AVAILABLE:
                 raise ImportError('Please pip install py7zr')
          import pyazr

          os.makedirs(lowercase					,  exist_ok=lowercase)
          with pyazr.SevenZipFile(lowercase					,  'r') as archive:
                 archive.extractall(lowercase)





class  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   __A   :				Any         =  [b'''\x04\x22\x4D\x18''']

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						None:







          '''simple docstring'''

          if not config.LZ4_AVAILABLE:
                 raise ImportError('Please pip install lz4')
          import lza.frame

          with lza.frame.open(lowercase					,  'rb') as compressed_file:
                 with open(lowercase					,  'wb') as extracted_file:
                        shutil.copyfileobj(lowercase					,  lowercase)





class  A__    :




   """simple docstring"""



   __A   :				Dict[str, Type[BaseExtractor]]         =  {
       "tar": TarExtractor,
       "gzip": GzipExtractor,
       "zip": ZipExtractor,
       "xz": XzExtractor,
       "rar": RarExtractor,
       "zstd": ZstdExtractor,
       "bz2": BzipaExtractor,
       "7z": SevenZipExtractor,  # <Added version="2.4.0"/>
       "lz4": LzaExtractor,  # <Added version="2.4.0"/>
   }

   @classmethod
   def 							__lowercase		(					cls)			->						str:







          '''simple docstring'''

          return max(
              len(lowercase)
              for extractor in cls.extractors.values()
              if issubclass(lowercase					,  lowercase)
              for extractor_magic_number in extractor.magic_numbers)

   @staticmethod
   def 							__lowercase		(					lowercase					,  lowercase)			->						str:







          '''simple docstring'''

          try:
                 return MagicNumberBaseExtractor.read_magic_number(lowercase					,  magic_number_length=lowercase)
          except OSError:
                 return b""

   @classmethod
   def 							__lowercase		(					cls					,  lowercase					,  lowercase = False)			->						bool:







          '''simple docstring'''

          warnings.warn(
              'Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. '
              'Use \'infer_extractor_format\' instead.'					,  category=lowercase					,  )
          a__						:	Dict =				cls.infer_extractor_format(lowercase)
          if extractor_format:
                 return True if not return_extractor else (True, cls.extractors[extractor_format])
          return False if not return_extractor else (False, None)

   @classmethod
   def 							__lowercase		(					cls					,  lowercase)			->						str:  # <Added version="2.4.0"/>







          '''simple docstring'''

          a__						:	int =				cls._get_magic_number_max_length()
          a__						:	Optional[Any] =				cls._read_magic_number(lowercase					,  lowercase)
          for extractor_format, extractor in cls.extractors.items():
                 if extractor.is_extractable(lowercase					,  magic_number=lowercase):
                        return extractor_format

   @classmethod
   def 							__lowercase		(					cls					,  lowercase					,  lowercase					,  lowercase = None					,  lowercase = "deprecated"					,  )			->						None:







          '''simple docstring'''

          os.makedirs(os.path.dirname(lowercase)					,  exist_ok=lowercase)
          # Prevent parallel extractions
          a__						:	Optional[Any] =				str(Path(lowercase).with_suffix('.lock'))
          with FileLock(lowercase):
                 shutil.rmtree(lowercase					,  ignore_errors=lowercase)
                 if extractor_format or extractor != "deprecated":
                        if extractor != "deprecated" or not isinstance(lowercase					,  lowercase):  # passed as positional arg
                               warnings.warn(
                                   'Parameter \'extractor\' was deprecated in version 2.4.0 and will be removed in 3.0.0. '
                                   'Use \'extractor_format\' instead.'					,  category=lowercase					,  )
                               a__						:	Optional[int] =				extractor if extractor != 'deprecated' else extractor_format
                        else:
                               a__						:	Dict =				cls.extractors[extractor_format]
                        return extractor.extract(lowercase					,  lowercase)
                 else:
                        warnings.warn(
                            'Parameter \'extractor_format\' was made required in version 2.4.0 and not passing it will raise an '
                            'exception in 3.0.0.'					,  category=lowercase					,  )
                        for extractor in cls.extractors.values():
                               if extractor.is_extractable(lowercase):
                                      return extractor.extract(lowercase					,  lowercase)









import os
import tempfile
import unittest
from pathlib import Path

from transformers import AutoConfig, is_tf_available
from transformers.testing_utils import require_tf


if is_tf_available():
    import tensorflow as tf

    from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments





@require_tf
class  A__    (							unittest.TestCase	):




   """simple docstring"""



   def 							__lowercase		(					self					,  lowercase)			->						Dict:







          '''simple docstring'''

          for model_result in results.values():
                 for batch_size, sequence_length in zip(model_result['bs']					,  model_result['ss']):
                        a__						:	int =				model_result['result'][batch_size][sequence_length]
                        self.assertIsNotNone(lowercase)

   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          a__						:	Tuple =				'sshleifer/tiny-gpt2'
          a__						:	str =				TensorFlowBenchmarkArguments(
              models=[MODEL_ID]					,  training=lowercase					,  inference=lowercase					,  sequence_lengths=[8]					,  batch_sizes=[1]					,  eager_mode=lowercase					,  multi_process=lowercase					,  )
          a__						:	List[Any] =				TensorFlowBenchmark(lowercase)
          a__						:	Any =				benchmark.run()
          self.check_results_dict_not_empty(results.time_inference_result)
          self.check_results_dict_not_empty(results.memory_inference_result)

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__						:	Optional[Any] =				'sgugger/tiny-distilbert-classification'
          a__						:	List[str] =				TensorFlowBenchmarkArguments(
              models=[MODEL_ID]					,  training=lowercase					,  inference=lowercase					,  sequence_lengths=[8]					,  batch_sizes=[1]					,  multi_process=lowercase					,  only_pretrain_model=lowercase					,  )
          a__						:	str =				TensorFlowBenchmark(lowercase)
          a__						:	int =				benchmark.run()
          self.check_results_dict_not_empty(results.time_inference_result)
          self.check_results_dict_not_empty(results.memory_inference_result)

   def 							__lowercase		(					self)			->						List[str]:







          '''simple docstring'''

          a__						:	Union[str, Any] =				'sshleifer/tiny-gpt2'
          a__						:	Dict =				TensorFlowBenchmarkArguments(
              models=[MODEL_ID]					,  training=lowercase					,  inference=lowercase					,  sequence_lengths=[8]					,  batch_sizes=[1]					,  multi_process=lowercase					,  )
          a__						:	List[str] =				TensorFlowBenchmark(lowercase)
          a__						:	Tuple =				benchmark.run()
          self.check_results_dict_not_empty(results.time_inference_result)
          self.check_results_dict_not_empty(results.memory_inference_result)

   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          a__						:	str =				'sshleifer/tiny-gpt2'
          a__						:	str =				AutoConfig.from_pretrained(lowercase)
          a__						:	Any =				TensorFlowBenchmarkArguments(
              models=[MODEL_ID]					,  training=lowercase					,  inference=lowercase					,  sequence_lengths=[8]					,  batch_sizes=[1]					,  eager_mode=lowercase					,  multi_process=lowercase					,  )
          a__						:	Optional[Any] =				TensorFlowBenchmark(lowercase					,  [config])
          a__						:	Union[str, Any] =				benchmark.run()
          self.check_results_dict_not_empty(results.time_inference_result)
          self.check_results_dict_not_empty(results.memory_inference_result)

   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          a__						:	Dict =				'sshleifer/tiny-gpt2'
          a__						:	Union[str, Any] =				AutoConfig.from_pretrained(lowercase)
          a__						:	Optional[int] =				TensorFlowBenchmarkArguments(
              models=[MODEL_ID]					,  training=lowercase					,  inference=lowercase					,  sequence_lengths=[8]					,  batch_sizes=[1]					,  multi_process=lowercase					,  )
          a__						:	str =				TensorFlowBenchmark(lowercase					,  [config])
          a__						:	List[str] =				benchmark.run()
          self.check_results_dict_not_empty(results.time_inference_result)
          self.check_results_dict_not_empty(results.memory_inference_result)

   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          a__						:	Optional[int] =				'sshleifer/tiny-gpt2'
          a__						:	Any =				TensorFlowBenchmarkArguments(
              models=[MODEL_ID]					,  training=lowercase					,  inference=lowercase					,  sequence_lengths=[8]					,  batch_sizes=[1]					,  multi_process=lowercase					,  )
          a__						:	Tuple =				TensorFlowBenchmark(lowercase)
          a__						:	str =				benchmark.run()
          self.check_results_dict_not_empty(results.time_train_result)
          self.check_results_dict_not_empty(results.memory_train_result)

   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          a__						:	Optional[Any] =				'sshleifer/tiny-gpt2'
          a__						:	List[Any] =				AutoConfig.from_pretrained(lowercase)
          a__						:	List[Any] =				TensorFlowBenchmarkArguments(
              models=[MODEL_ID]					,  training=lowercase					,  inference=lowercase					,  sequence_lengths=[8]					,  batch_sizes=[1]					,  multi_process=lowercase					,  )
          a__						:	Optional[Any] =				TensorFlowBenchmark(lowercase					,  [config])
          a__						:	List[Any] =				benchmark.run()
          self.check_results_dict_not_empty(results.time_train_result)
          self.check_results_dict_not_empty(results.memory_train_result)

   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          a__						:	Optional[int] =				'patrickvonplaten/t5-tiny-random'
          a__						:	Optional[int] =				AutoConfig.from_pretrained(lowercase)
          a__						:	Any =				TensorFlowBenchmarkArguments(
              models=[MODEL_ID]					,  training=lowercase					,  inference=lowercase					,  sequence_lengths=[8]					,  batch_sizes=[1]					,  multi_process=lowercase					,  )
          a__						:	List[Any] =				TensorFlowBenchmark(lowercase					,  configs=[config])
          a__						:	Union[str, Any] =				benchmark.run()
          self.check_results_dict_not_empty(results.time_inference_result)
          self.check_results_dict_not_empty(results.memory_inference_result)

   @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices('GPU')) == 0					,  'Cannot do xla on CPU.')
   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          a__						:	Optional[int] =				'sshleifer/tiny-gpt2'
          a__						:	str =				TensorFlowBenchmarkArguments(
              models=[MODEL_ID]					,  training=lowercase					,  inference=lowercase					,  sequence_lengths=[8]					,  batch_sizes=[1]					,  use_xla=lowercase					,  multi_process=lowercase					,  )
          a__						:	int =				TensorFlowBenchmark(lowercase)
          a__						:	Tuple =				benchmark.run()
          self.check_results_dict_not_empty(results.time_inference_result)
          self.check_results_dict_not_empty(results.memory_inference_result)

   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          a__						:	str =				'sshleifer/tiny-gpt2'
          with tempfile.TemporaryDirectory() as tmp_dir:
                 a__						:	int =				TensorFlowBenchmarkArguments(
                     models=[MODEL_ID]					,  inference=lowercase					,  save_to_csv=lowercase					,  sequence_lengths=[8]					,  batch_sizes=[1]					,  inference_time_csv_file=os.path.join(lowercase					,  'inf_time.csv')					,  inference_memory_csv_file=os.path.join(lowercase					,  'inf_mem.csv')					,  env_info_csv_file=os.path.join(lowercase					,  'env.csv')					,  multi_process=lowercase					,  )
                 a__						:	List[str] =				TensorFlowBenchmark(lowercase)
                 benchmark.run()
                 self.assertTrue(Path(os.path.join(lowercase					,  'inf_time.csv')).exists())
                 self.assertTrue(Path(os.path.join(lowercase					,  'inf_mem.csv')).exists())
                 self.assertTrue(Path(os.path.join(lowercase					,  'env.csv')).exists())

   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          a__						:	Union[str, Any] =				'sshleifer/tiny-gpt2'

          def _check_summary_is_not_empty(lowercase):
                 self.assertTrue(hasattr(lowercase					,  'sequential'))
                 self.assertTrue(hasattr(lowercase					,  'cumulative'))
                 self.assertTrue(hasattr(lowercase					,  'current'))
                 self.assertTrue(hasattr(lowercase					,  'total'))

          with tempfile.TemporaryDirectory() as tmp_dir:
                 a__						:	List[str] =				TensorFlowBenchmarkArguments(
                     models=[MODEL_ID]					,  inference=lowercase					,  sequence_lengths=[8]					,  batch_sizes=[1]					,  log_filename=os.path.join(lowercase					,  'log.txt')					,  log_print=lowercase					,  trace_memory_line_by_line=lowercase					,  eager_mode=lowercase					,  multi_process=lowercase					,  )
                 a__						:	List[str] =				TensorFlowBenchmark(lowercase)
                 a__						:	Any =				benchmark.run()
                 _check_summary_is_not_empty(result.inference_summary)
                 self.assertTrue(Path(os.path.join(lowercase					,  'log.txt')).exists())


