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


__magic_name__       =			get_logger(__name__)
class 						SCREAMING_SNAKE_CASE_ :




		"""simple docstring"""





		def __init__(     self							,  lowerCAmelCase__ = None):
				__SCREAMING_SNAKE_CASE            = (
				    os.path.join(lowerCAmelCase__							,  config.EXTRACTED_DATASETS_DIR) if cache_dir else config.EXTRACTED_DATASETS_PATH
				)
				__SCREAMING_SNAKE_CASE            = Extractor




		def 	snake_case_     (     self							,  lowerCAmelCase__):
				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"
				__SCREAMING_SNAKE_CASE            = os.path.abspath(lowerCAmelCase__)
				return os.path.join(self.extract_dir							,  hash_url_to_filename(lowerCAmelCase__))




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__):
				return force_extract or (
				    not os.path.isfile(lowerCAmelCase__) and not (os.path.isdir(lowerCAmelCase__) and os.listdir(lowerCAmelCase__))
				)




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__ = False):
				__SCREAMING_SNAKE_CASE            = self.extractor.infer_extractor_format(lowerCAmelCase__)
				if not extractor_format:
						return input_path
				__SCREAMING_SNAKE_CASE            = self._get_output_path(lowerCAmelCase__)
				if self._do_extract(lowerCAmelCase__							,  lowerCAmelCase__):
						self.extractor.extract(lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__)
				return output_path



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		@classmethod
		@abstractmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  **lowerCAmelCase__):
				...




		@staticmethod
		@abstractmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				...



class 						SCREAMING_SNAKE_CASE_ (						__a     ,				__a ):




		"""simple docstring"""





		__lowercase							:  List[bytes]						   =		[]




		@staticmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				with open(lowerCAmelCase__							,  """rb""") as f:
						return f.read(lowerCAmelCase__)




		@classmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  lowerCAmelCase__ = b""):
				if not magic_number:
						__SCREAMING_SNAKE_CASE            = max(len(lowerCAmelCase__) for cls_magic_number in cls.magic_numbers)
						try:
								__SCREAMING_SNAKE_CASE            = cls.read_magic_number(lowerCAmelCase__							,  lowerCAmelCase__)
						except OSError:
								return False
				return any(magic_number.startswith(lowerCAmelCase__) for cls_magic_number in cls.magic_numbers)



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		@classmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  **lowerCAmelCase__):
				return tarfile.is_tarfile(lowerCAmelCase__)




		@staticmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):

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

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

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

				__SCREAMING_SNAKE_CASE            = resolved(lowerCAmelCase__)

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




		@staticmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				os.makedirs(lowerCAmelCase__							,  exist_ok=lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = tarfile.open(lowerCAmelCase__)
				tar_file.extractall(lowerCAmelCase__							,  members=TarExtractor.safemembers(lowerCAmelCase__							,  lowerCAmelCase__))
				tar_file.close()



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  int						   =		[B'''\x1F\x8B''']




		@staticmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				with gzip.open(lowerCAmelCase__							,  """rb""") as gzip_file:
						with open(lowerCAmelCase__							,  """wb""") as extracted_file:
								shutil.copyfileobj(lowerCAmelCase__							,  lowerCAmelCase__)



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  Optional[Any]						   =		[
		    B'''PK\x03\x04''',
		    B'''PK\x05\x06''',  # empty archive
		    B'''PK\x07\x08''',  # spanned archive
		]




		@classmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  lowerCAmelCase__ = b""):
				if super().is_extractable(lowerCAmelCase__							,  magic_number=lowerCAmelCase__):
						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(lowerCAmelCase__							,  """rb""") as fp:
								__SCREAMING_SNAKE_CASE            = _EndRecData(lowerCAmelCase__)
								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:
														__SCREAMING_SNAKE_CASE            = fp.read(lowerCAmelCase__)  # CD is where we expect it to be
														if len(lowerCAmelCase__) == sizeCentralDir:
																__SCREAMING_SNAKE_CASE            = struct.unpack(lowerCAmelCase__							,  lowerCAmelCase__)  # 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_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				os.makedirs(lowerCAmelCase__							,  exist_ok=lowerCAmelCase__)
				with zipfile.ZipFile(lowerCAmelCase__							,  """r""") as zip_file:
						zip_file.extractall(lowerCAmelCase__)
						zip_file.close()



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  List[str]						   =		[B'''\xFD\x37\x7A\x58\x5A\x00''']




		@staticmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				with lzma.open(lowerCAmelCase__) as compressed_file:
						with open(lowerCAmelCase__							,  """wb""") as extracted_file:
								shutil.copyfileobj(lowerCAmelCase__							,  lowerCAmelCase__)



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  Any						   =		[B'''Rar!\x1a\x07\x00''', B'''Rar!\x1a\x07\x01\x00''']  # RAR_ID  # RAR5_ID




		@staticmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				if not config.RARFILE_AVAILABLE:
						raise ImportError("""Please pip install rarfile""")
				import rarfile

				os.makedirs(lowerCAmelCase__							,  exist_ok=lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = rarfile.RarFile(lowerCAmelCase__)
				rf.extractall(lowerCAmelCase__)
				rf.close()



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  Union[str, Any]						   =		[B'''\x28\xb5\x2F\xFD''']




		@staticmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				if not config.ZSTANDARD_AVAILABLE:
						raise ImportError("""Please pip install zstandard""")
				import zstandard as zstd

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



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  int						   =		[B'''\x42\x5A\x68''']




		@staticmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				with bza.open(lowerCAmelCase__							,  """rb""") as compressed_file:
						with open(lowerCAmelCase__							,  """wb""") as extracted_file:
								shutil.copyfileobj(lowerCAmelCase__							,  lowerCAmelCase__)



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





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




		@staticmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				if not config.PY7ZR_AVAILABLE:
						raise ImportError("""Please pip install py7zr""")
				import pyazr

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



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  Tuple						   =		[B'''\x04\x22\x4D\x18''']




		@staticmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				if not config.LZ4_AVAILABLE:
						raise ImportError("""Please pip install lz4""")
				import lza.frame

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



class 						SCREAMING_SNAKE_CASE_ :




		"""simple docstring"""





		__lowercase							:  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 	snake_case_     (     cls):
				return max(
				    len(lowerCAmelCase__)
				    for extractor in cls.extractors.values()
				    if issubclass(lowerCAmelCase__							,  lowerCAmelCase__)
				    for extractor_magic_number in extractor.magic_numbers)




		@staticmethod
		def 	snake_case_     (     lowerCAmelCase__							,  lowerCAmelCase__):
				try:
						return MagicNumberBaseExtractor.read_magic_number(lowerCAmelCase__							,  magic_number_length=lowerCAmelCase__)
				except OSError:
						return b""




		@classmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  lowerCAmelCase__ = False):
				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=lowerCAmelCase__							,  )
				__SCREAMING_SNAKE_CASE            = cls.infer_extractor_format(lowerCAmelCase__)
				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							,  lowerCAmelCase__):  # <Added version="2.4.0"/>
				__SCREAMING_SNAKE_CASE            = cls._get_magic_number_max_length()
				__SCREAMING_SNAKE_CASE            = cls._read_magic_number(lowerCAmelCase__							,  lowerCAmelCase__)
				for extractor_format, extractor in cls.extractors.items():
						if extractor.is_extractable(lowerCAmelCase__							,  magic_number=lowerCAmelCase__):
								return extractor_format




		@classmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = "deprecated"							,  ):
				os.makedirs(os.path.dirname(lowerCAmelCase__)							,  exist_ok=lowerCAmelCase__)
				# Prevent parallel extractions
				__SCREAMING_SNAKE_CASE            = str(Path(lowerCAmelCase__).with_suffix(""".lock"""))
				with FileLock(lowerCAmelCase__):
						shutil.rmtree(lowerCAmelCase__							,  ignore_errors=lowerCAmelCase__)
						if extractor_format or extractor != "deprecated":
								if extractor != "deprecated" or not isinstance(lowerCAmelCase__							,  lowerCAmelCase__):  # 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=lowerCAmelCase__							,  )
										__SCREAMING_SNAKE_CASE            = extractor if extractor != """deprecated""" else extractor_format
								else:
										__SCREAMING_SNAKE_CASE            = cls.extractors[extractor_format]
								return extractor.extract(lowerCAmelCase__							,  lowerCAmelCase__)
						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=lowerCAmelCase__							,  )
								for extractor in cls.extractors.values():
										if extractor.is_extractable(lowerCAmelCase__):
												return extractor.extract(lowerCAmelCase__							,  lowerCAmelCase__)






"""simple docstring"""





from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__magic_name__       =			logging.get_logger(__name__)

__magic_name__       =			{
    "huggingface/informer-tourism-monthly": (
        "https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json"
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}
class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  Dict						   =		'''informer'''
		__lowercase							:  Union[str, Any]						   =		{
		    '''hidden_size''': '''d_model''',
		    '''num_attention_heads''': '''encoder_attention_heads''',
		    '''num_hidden_layers''': '''encoder_layers''',
		}




		def __init__(     self							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = "student_t"							,  lowerCAmelCase__ = "nll"							,  lowerCAmelCase__ = 1							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = "mean"							,  lowerCAmelCase__ = 0							,  lowerCAmelCase__ = 0							,  lowerCAmelCase__ = 0							,  lowerCAmelCase__ = 0							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = 6_4							,  lowerCAmelCase__ = 3_2							,  lowerCAmelCase__ = 3_2							,  lowerCAmelCase__ = 2							,  lowerCAmelCase__ = 2							,  lowerCAmelCase__ = 2							,  lowerCAmelCase__ = 2							,  lowerCAmelCase__ = True							,  lowerCAmelCase__ = "gelu"							,  lowerCAmelCase__ = 0.05							,  lowerCAmelCase__ = 0.1							,  lowerCAmelCase__ = 0.1							,  lowerCAmelCase__ = 0.1							,  lowerCAmelCase__ = 0.1							,  lowerCAmelCase__ = 1_0_0							,  lowerCAmelCase__ = 0.02							,  lowerCAmelCase__=True							,  lowerCAmelCase__ = "prob"							,  lowerCAmelCase__ = 5							,  lowerCAmelCase__ = True							,  **lowerCAmelCase__							,  ):
				# time series specific configuration
				__SCREAMING_SNAKE_CASE            = prediction_length
				__SCREAMING_SNAKE_CASE            = context_length or prediction_length
				__SCREAMING_SNAKE_CASE            = distribution_output
				__SCREAMING_SNAKE_CASE            = loss
				__SCREAMING_SNAKE_CASE            = input_size
				__SCREAMING_SNAKE_CASE            = num_time_features
				__SCREAMING_SNAKE_CASE            = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
				__SCREAMING_SNAKE_CASE            = scaling
				__SCREAMING_SNAKE_CASE            = num_dynamic_real_features
				__SCREAMING_SNAKE_CASE            = num_static_real_features
				__SCREAMING_SNAKE_CASE            = num_static_categorical_features

				# set cardinality
				if cardinality and num_static_categorical_features > 0:
						if len(lowerCAmelCase__) != num_static_categorical_features:
								raise ValueError(
								    """The cardinality should be a list of the same length as `num_static_categorical_features`""")
						__SCREAMING_SNAKE_CASE            = cardinality
				else:
						__SCREAMING_SNAKE_CASE            = [0]

				# set embedding_dimension
				if embedding_dimension and num_static_categorical_features > 0:
						if len(lowerCAmelCase__) != num_static_categorical_features:
								raise ValueError(
								    """The embedding dimension should be a list of the same length as `num_static_categorical_features`""")
						__SCREAMING_SNAKE_CASE            = embedding_dimension
				else:
						__SCREAMING_SNAKE_CASE            = [min(5_0							,  (cat + 1) // 2) for cat in self.cardinality]

				__SCREAMING_SNAKE_CASE            = num_parallel_samples

				# Transformer architecture configuration
				__SCREAMING_SNAKE_CASE            = input_size * len(self.lags_sequence) + self._number_of_features
				__SCREAMING_SNAKE_CASE            = d_model
				__SCREAMING_SNAKE_CASE            = encoder_attention_heads
				__SCREAMING_SNAKE_CASE            = decoder_attention_heads
				__SCREAMING_SNAKE_CASE            = encoder_ffn_dim
				__SCREAMING_SNAKE_CASE            = decoder_ffn_dim
				__SCREAMING_SNAKE_CASE            = encoder_layers
				__SCREAMING_SNAKE_CASE            = decoder_layers

				__SCREAMING_SNAKE_CASE            = dropout
				__SCREAMING_SNAKE_CASE            = attention_dropout
				__SCREAMING_SNAKE_CASE            = activation_dropout
				__SCREAMING_SNAKE_CASE            = encoder_layerdrop
				__SCREAMING_SNAKE_CASE            = decoder_layerdrop

				__SCREAMING_SNAKE_CASE            = activation_function
				__SCREAMING_SNAKE_CASE            = init_std

				__SCREAMING_SNAKE_CASE            = use_cache

				# Informer
				__SCREAMING_SNAKE_CASE            = attention_type
				__SCREAMING_SNAKE_CASE            = sampling_factor
				__SCREAMING_SNAKE_CASE            = distil

				super().__init__(is_encoder_decoder=lowerCAmelCase__							,  **lowerCAmelCase__)




		@property
		def 	snake_case_     (     self):
				return (
				    sum(self.embedding_dimension)
				    + self.num_dynamic_real_features
				    + self.num_time_features
				    + self.num_static_real_features
				    + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
				)




