





"""simple docstring"""





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


SCREAMING_SNAKE_CASE__					=   get_logger(__name__)

class 		lowercase					:





      def __init__(       self      ,						lowercase = None )		->     List[Any]:
            lowerCAmelCase  						=       (
                os.path.join(lowercase      ,						config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH
            )
            lowerCAmelCase  						=       Extractor





      def     _snake_case			(       self      ,						lowercase )		->     str:
            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"
            lowerCAmelCase  						=       os.path.abspath(lowercase )
            return os.path.join(self.extract_dir      ,						hash_url_to_filename(lowercase ) )





      def     _snake_case			(       self      ,						lowercase      ,						lowercase )		->     bool:
            return force_extract or (
                not os.path.isfile(lowercase ) and not (os.path.isdir(lowercase ) and os.listdir(lowercase ))
            )





      def     _snake_case			(       self      ,						lowercase      ,						lowercase = False )		->     str:
            lowerCAmelCase  						=       self.extractor.infer_extractor_format(lowercase )
            if not extractor_format:
                  return input_path
            lowerCAmelCase  						=       self._get_output_path(lowercase )
            if self._do_extract(lowercase      ,						lowercase ):
                  self.extractor.extract(lowercase      ,						lowercase      ,						lowercase )
            return output_path







class 		lowercase					(					_UpperCAmelCase					):





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





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







class 		lowercase					(					_UpperCAmelCase     ,  _UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      []





      @staticmethod
      def     _snake_case			(       lowercase      ,						lowercase )		->     Union[str, Any]:
            with open(lowercase      ,						"""rb""" ) as f:
                  return f.read(lowercase )





      @classmethod
      def     _snake_case			(       cls      ,						lowercase      ,						lowercase = b"" )		->     bool:
            if not magic_number:
                  lowerCAmelCase  						=       max(len(lowercase ) for cls_magic_number in cls.magic_numbers )
                  try:
                        lowerCAmelCase  						=       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 		lowercase					(					_UpperCAmelCase					):





      @classmethod
      def     _snake_case			(       cls      ,						lowercase      ,						**lowercase )		->     bool:
            return tarfile.is_tarfile(lowercase )





      @staticmethod
      def     _snake_case			(       lowercase      ,						lowercase )		->     Optional[int]:

            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
                  lowerCAmelCase  						=       resolved(os.path.join(lowercase      ,						os.path.dirname(info.name ) ) )
                  return badpath(info.linkname      ,						base=lowercase )

            lowerCAmelCase  						=       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     _snake_case			(       lowercase      ,						lowercase )		->     None:
            os.makedirs(lowercase      ,						exist_ok=lowercase )
            lowerCAmelCase  						=       tarfile.open(lowercase )
            tar_file.extractall(lowercase      ,						members=TarExtractor.safemembers(lowercase      ,						lowercase ) )
            tar_file.close()







class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      [B'\x1F\x8B']





      @staticmethod
      def     _snake_case			(       lowercase      ,						lowercase )		->     None:
            with gzip.open(lowercase      ,						"""rb""" ) as gzip_file:
                  with open(lowercase      ,						"""wb""" ) as extracted_file:
                        shutil.copyfileobj(lowercase      ,						lowercase )







class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      [
          B'PK\x03\x04',
          B'PK\x05\x06',  # empty archive
          B'PK\x07\x08',  # spanned archive
      ]





      @classmethod
      def     _snake_case			(       cls      ,						lowercase      ,						lowercase = b"" )		->     bool:
            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:
                        lowerCAmelCase  						=       _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:
                                          lowerCAmelCase  						=       fp.read(lowercase )  # CD is where we expect it to be
                                          if len(lowercase ) == sizeCentralDir:
                                                lowerCAmelCase  						=       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     _snake_case			(       lowercase      ,						lowercase )		->     None:
            os.makedirs(lowercase      ,						exist_ok=lowercase )
            with zipfile.ZipFile(lowercase      ,						"""r""" ) as zip_file:
                  zip_file.extractall(lowercase )
                  zip_file.close()







class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      [B'\xFD\x37\x7A\x58\x5A\x00']





      @staticmethod
      def     _snake_case			(       lowercase      ,						lowercase )		->     None:
            with lzma.open(lowercase ) as compressed_file:
                  with open(lowercase      ,						"""wb""" ) as extracted_file:
                        shutil.copyfileobj(lowercase      ,						lowercase )







class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      [B'Rar!\x1a\x07\x00', B'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID





      @staticmethod
      def     _snake_case			(       lowercase      ,						lowercase )		->     None:
            if not config.RARFILE_AVAILABLE:
                  raise ImportError("""Please pip install rarfile""" )
            import rarfile

            os.makedirs(lowercase      ,						exist_ok=lowercase )
            lowerCAmelCase  						=       rarfile.RarFile(lowercase )
            rf.extractall(lowercase )
            rf.close()







class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      [B'\x28\xb5\x2F\xFD']





      @staticmethod
      def     _snake_case			(       lowercase      ,						lowercase )		->     None:
            if not config.ZSTANDARD_AVAILABLE:
                  raise ImportError("""Please pip install zstandard""" )
            import zstandard as zstd

            lowerCAmelCase  						=       zstd.ZstdDecompressor()
            with open(lowercase      ,						"""rb""" ) as ifh, open(lowercase      ,						"""wb""" ) as ofh:
                  dctx.copy_stream(lowercase      ,						lowercase )







class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      [B'\x42\x5A\x68']





      @staticmethod
      def     _snake_case			(       lowercase      ,						lowercase )		->     None:
            with bza.open(lowercase      ,						"""rb""" ) as compressed_file:
                  with open(lowercase      ,						"""wb""" ) as extracted_file:
                        shutil.copyfileobj(lowercase      ,						lowercase )







class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      [B'\x37\x7A\xBC\xAF\x27\x1C']





      @staticmethod
      def     _snake_case			(       lowercase      ,						lowercase )		->     None:
            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 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      [B'\x04\x22\x4D\x18']





      @staticmethod
      def     _snake_case			(       lowercase      ,						lowercase )		->     None:
            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 		lowercase					:
      #  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
      _SCREAMING_SNAKE_CASE					=      {
          "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     _snake_case			(       cls )		->     List[str]:
            return max(
                len(lowercase )
                for extractor in cls.extractors.values()
                if issubclass(lowercase      ,						lowercase )
                for extractor_magic_number in extractor.magic_numbers )





      @staticmethod
      def     _snake_case			(       lowercase      ,						lowercase )		->     str:
            try:
                  return MagicNumberBaseExtractor.read_magic_number(lowercase      ,						magic_number_length=lowercase )
            except OSError:
                  return b""





      @classmethod
      def     _snake_case			(       cls      ,						lowercase      ,						lowercase = False )		->     bool:
            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      ,						)
            lowerCAmelCase  						=       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     _snake_case			(       cls      ,						lowercase )		->     str:  # <Added version="2.4.0"/>
            lowerCAmelCase  						=       cls._get_magic_number_max_length()
            lowerCAmelCase  						=       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     _snake_case			(       cls      ,						lowercase      ,						lowercase      ,						lowercase = None      ,						lowercase = "deprecated"      ,						)		->     None:
            os.makedirs(os.path.dirname(lowercase )      ,						exist_ok=lowercase )
            # Prevent parallel extractions
            lowerCAmelCase  						=       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      ,						)
                              lowerCAmelCase  						=       extractor if extractor != """deprecated""" else extractor_format
                        else:
                              lowerCAmelCase  						=       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 )













"""simple docstring"""





from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


if TYPE_CHECKING:
       from ... import FeatureExtractionMixin, TensorType

SCREAMING_SNAKE_CASE__					=   logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__					=   {
    "openai/imagegpt-small": "",
    "openai/imagegpt-medium": "",
    "openai/imagegpt-large": "",
}

class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      'imagegpt'
      _SCREAMING_SNAKE_CASE					=      ['past_key_values']
      _SCREAMING_SNAKE_CASE					=      {
          'hidden_size': 'n_embd',
          'max_position_embeddings': 'n_positions',
          'num_attention_heads': 'n_head',
          'num_hidden_layers': 'n_layer',
      }





      def __init__(       self      ,						lowercase=512 + 1      ,						lowercase=32 * 32      ,						lowercase=512      ,						lowercase=24      ,						lowercase=8      ,						lowercase=None      ,						lowercase="quick_gelu"      ,						lowercase=0.1      ,						lowercase=0.1      ,						lowercase=0.1      ,						lowercase=1e-5      ,						lowercase=0.02      ,						lowercase=True      ,						lowercase=True      ,						lowercase=False      ,						lowercase=False      ,						lowercase=False      ,						**lowercase      ,						)		->     Any:
            lowerCAmelCase  						=       vocab_size
            lowerCAmelCase  						=       n_positions
            lowerCAmelCase  						=       n_embd
            lowerCAmelCase  						=       n_layer
            lowerCAmelCase  						=       n_head
            lowerCAmelCase  						=       n_inner
            lowerCAmelCase  						=       activation_function
            lowerCAmelCase  						=       resid_pdrop
            lowerCAmelCase  						=       embd_pdrop
            lowerCAmelCase  						=       attn_pdrop
            lowerCAmelCase  						=       layer_norm_epsilon
            lowerCAmelCase  						=       initializer_range
            lowerCAmelCase  						=       scale_attn_weights
            lowerCAmelCase  						=       use_cache
            lowerCAmelCase  						=       scale_attn_by_inverse_layer_idx
            lowerCAmelCase  						=       reorder_and_upcast_attn
            lowerCAmelCase  						=       tie_word_embeddings

            super().__init__(tie_word_embeddings=lowercase      ,						**lowercase )







class 		lowercase					(					_UpperCAmelCase					):





      @property
      def     _snake_case			(       self )		->     Mapping[str, Mapping[int, str]]:
            return OrderedDict(
                [
                    ("""input_ids""", {0: """batch""", 1: """sequence"""}),
                ] )





      def     _snake_case			(       self      ,						lowercase      ,						lowercase = 1      ,						lowercase = -1      ,						lowercase = False      ,						lowercase = None      ,						lowercase = 3      ,						lowercase = 32      ,						lowercase = 32      ,						)		->     Mapping[str, Any]:
            lowerCAmelCase  						=       self._generate_dummy_images(lowercase      ,						lowercase      ,						lowercase      ,						lowercase )
            lowerCAmelCase  						=       dict(preprocessor(images=lowercase      ,						return_tensors=lowercase ) )

            return inputs






