



'''simple docstring'''



# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import importlib.metadata
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Union

from packaging import version

from ..utils import is_torch_available, logging


if is_torch_available():
	import torch


lowerCAmelCase	:		str				=   logging.get_logger(__name__)






@dataclass
class 					UpperCAmelCase__	:



					def __init__(    self			,				UpperCamelCase=False			,				UpperCamelCase=False			,				UpperCamelCase=6.0			,				UpperCamelCase=None			,				UpperCamelCase=False			,				UpperCamelCase=False			,				UpperCamelCase=None			,				UpperCamelCase="fp4"			,				UpperCamelCase=False			,				**UpperCamelCase			,				)     ->			Optional[Any]:
						__lowerCAmelCase												=  load_in_abit
						__lowerCAmelCase												=  load_in_abit
						__lowerCAmelCase												=  llm_inta_threshold
						__lowerCAmelCase												=  llm_inta_skip_modules
						__lowerCAmelCase												=  llm_inta_enable_fpaa_cpu_offload
						__lowerCAmelCase												=  llm_inta_has_fpaa_weight
						__lowerCAmelCase												=  bnb_abit_quant_type
						__lowerCAmelCase												=  bnb_abit_use_double_quant

						if bnb_abit_compute_dtype is None:
							__lowerCAmelCase												=  torch.floataa
						elif isinstance(UpperCamelCase			,				UpperCamelCase     ):
							__lowerCAmelCase												=  getattr(UpperCamelCase			,				UpperCamelCase     )
						elif isinstance(UpperCamelCase			,				torch.dtype     ):
							__lowerCAmelCase												=  bnb_abit_compute_dtype
						else:
							raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype"     )

						self.post_init()



					def        UpperCAmelCase_ (    self     )     ->			Dict:
						if not isinstance(self.llm_inta_threshold			,				UpperCamelCase     ):
							raise ValueError("llm_int8_threshold must be a float"     )

						if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules			,				UpperCamelCase     ):
							raise ValueError("llm_int8_skip_modules must be a list of strings"     )
						if not isinstance(self.llm_inta_enable_fpaa_cpu_offload			,				UpperCamelCase     ):
							raise ValueError("llm_int8_enable_fp32_cpu_offload must be a boolean"     )

						if not isinstance(self.llm_inta_has_fpaa_weight			,				UpperCamelCase     ):
							raise ValueError("llm_int8_has_fp16_weight must be a boolean"     )

						if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype			,				torch.dtype     ):
							raise ValueError("bnb_4bit_compute_dtype must be torch.dtype"     )

						if not isinstance(self.bnb_abit_quant_type			,				UpperCamelCase     ):
							raise ValueError("bnb_4bit_quant_type must be a string"     )

						if not isinstance(self.bnb_abit_use_double_quant			,				UpperCamelCase     ):
							raise ValueError("bnb_4bit_use_double_quant must be a boolean"     )

						if self.load_in_abit and not version.parse(importlib.metadata.version("bitsandbytes"     )     ) >= version.parse(
						    "0.39.0"     ):
							raise ValueError(
							    "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version"     )



					def        UpperCAmelCase_ (    self     )     ->			List[str]:
						return self.load_in_abit or self.load_in_abit



					def        UpperCAmelCase_ (    self     )     ->			str:
						if self.load_in_abit:
							return "llm_int8"
						elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
							return "fp4"
						elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
							return "nf4"
						else:
							return None



					@classmethod
					def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				UpperCamelCase			,				**UpperCamelCase     )     ->			Any:
						__lowerCAmelCase												=  cls(**UpperCamelCase     )

						__lowerCAmelCase												=  []
						for key, value in kwargs.items():
							if hasattr(UpperCamelCase			,				UpperCamelCase     ):
								setattr(UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase     )
								to_remove.append(UpperCamelCase     )
						for key in to_remove:
							kwargs.pop(UpperCamelCase			,				UpperCamelCase     )

						if return_unused_kwargs:
							return config, kwargs
						else:
							return config



					def        UpperCAmelCase_ (    self			,				UpperCamelCase     )     ->			Optional[Any]:
						with open(UpperCamelCase			,				"w"			,				encoding="utf-8"     ) as writer:
							__lowerCAmelCase												=  self.to_dict()
							__lowerCAmelCase												=  json.dumps(UpperCamelCase			,				indent=2			,				sort_keys=UpperCamelCase     ) + "\n"

							writer.write(UpperCamelCase     )



					def        UpperCAmelCase_ (    self     )     ->			Dict[str, Any]:
						__lowerCAmelCase												=  copy.deepcopy(self.__dict__     )
						__lowerCAmelCase												=  str(output["bnb_4bit_compute_dtype"]     ).split("."     )[1]

						return output



					def __repr__(    self     )     ->			List[str]:
						return F'''{self.__class__.__name__} {self.to_json_string()}'''



					def        UpperCAmelCase_ (    self			,				UpperCamelCase = True     )     ->			str:
						if use_diff is True:
							__lowerCAmelCase												=  self.to_diff_dict()
						else:
							__lowerCAmelCase												=  self.to_dict()
						return json.dumps(UpperCamelCase			,				indent=2			,				sort_keys=UpperCamelCase     ) + "\n"



					def        UpperCAmelCase_ (    self     )     ->			Dict[str, Any]:
						__lowerCAmelCase												=  self.to_dict()

						# get the default config dict
						__lowerCAmelCase												=  BitsAndBytesConfig().to_dict()

						__lowerCAmelCase												=  {}

						# only serialize values that differ from the default config
						for key, value in config_dict.items():
							if value != default_config_dict[key]:
								__lowerCAmelCase												=  value

						return serializable_config_dict




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


lowerCAmelCase	:		List[Any]				=   get_logger(__name__)






class 					UpperCAmelCase__	:



					def __init__(    self			,				UpperCamelCase = None     )     ->			Union[str, Any]:
						__lowerCAmelCase												=  (
						    os.path.join(UpperCamelCase			,				config.EXTRACTED_DATASETS_DIR     ) if cache_dir else config.EXTRACTED_DATASETS_PATH
						)
						__lowerCAmelCase												=  Extractor



					def        UpperCAmelCase_ (    self			,				UpperCamelCase     )     ->			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(UpperCamelCase     )
						return os.path.join(self.extract_dir			,				hash_url_to_filename(UpperCamelCase     )     )



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



					def        UpperCAmelCase_ (    self			,				UpperCamelCase			,				UpperCamelCase = False     )     ->			str:
						__lowerCAmelCase												=  self.extractor.infer_extractor_format(UpperCamelCase     )
						if not extractor_format:
							return input_path
						__lowerCAmelCase												=  self._get_output_path(UpperCamelCase     )
						if self._do_extract(UpperCamelCase			,				UpperCamelCase     ):
							self.extractor.extract(UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase     )
						return output_path






class 					UpperCAmelCase__	(		UpperCamelCase__ ):



					@classmethod
					@abstractmethod
					def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				**UpperCamelCase     )     ->			bool:
						...



					@staticmethod
					@abstractmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						...






class 					UpperCAmelCase__	(		UpperCamelCase__							,       UpperCamelCase__ ):
					a      :     List[bytes]        =							[]



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			List[Any]:
						with open(UpperCamelCase			,				"rb"     ) as f:
							return f.read(UpperCamelCase     )



					@classmethod
					def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				UpperCamelCase = b""     )     ->			bool:
						if not magic_number:
							__lowerCAmelCase												=  max(len(UpperCamelCase     ) for cls_magic_number in cls.magic_numbers     )
							try:
								__lowerCAmelCase												=  cls.read_magic_number(UpperCamelCase			,				UpperCamelCase     )
							except OSError:
								return False
						return any(magic_number.startswith(UpperCamelCase     ) for cls_magic_number in cls.magic_numbers     )






class 					UpperCAmelCase__	(		UpperCamelCase__ ):



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



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			Dict:

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

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

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

						__lowerCAmelCase												=  resolved(UpperCamelCase     )

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



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						os.makedirs(UpperCamelCase			,				exist_ok=UpperCamelCase     )
						__lowerCAmelCase												=  tarfile.open(UpperCamelCase     )
						tar_file.extractall(UpperCamelCase			,				members=TarExtractor.safemembers(UpperCamelCase			,				UpperCamelCase     )     )
						tar_file.close()






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     Any        =							[B"""\x1F\x8B"""]



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






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     List[Any]        =							[
					    B"""PK\x03\x04""",
					    B"""PK\x05\x06""",  # empty archive
					    B"""PK\x07\x08""",  # spanned archive
					]



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






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     Tuple        =							[B"""\xFD\x37\x7A\x58\x5A\x00"""]



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






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     str        =							[B"""Rar!\x1a\x07\x00""", B"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID



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

						os.makedirs(UpperCamelCase			,				exist_ok=UpperCamelCase     )
						__lowerCAmelCase												=  rarfile.RarFile(UpperCamelCase     )
						rf.extractall(UpperCamelCase     )
						rf.close()






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     int        =							[B"""\x28\xb5\x2F\xFD"""]



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

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






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     Any        =							[B"""\x42\x5A\x68"""]



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






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     Any        =							[B"""\x37\x7A\xBC\xAF\x27\x1C"""]



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						if not config.PY7ZR_AVAILABLE:
							raise ImportError("Please pip install py7zr"     )
						import pyazr

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






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
					a      :     Any        =							[B"""\x04\x22\x4D\x18"""]



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
						if not config.LZ4_AVAILABLE:
							raise ImportError("Please pip install lz4"     )
						import lza.frame

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






class 					UpperCAmelCase__	:
					#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
					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        UpperCAmelCase_ (    cls     )     ->			Optional[Any]:
						return max(
						    len(UpperCamelCase     )
						    for extractor in cls.extractors.values()
						    if issubclass(UpperCamelCase			,				UpperCamelCase     )
						    for extractor_magic_number in extractor.magic_numbers     )



					@staticmethod
					def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			Dict:
						try:
							return MagicNumberBaseExtractor.read_magic_number(UpperCamelCase			,				magic_number_length=UpperCamelCase     )
						except OSError:
							return b""



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



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