


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


UpperCamelCase__    							= get_logger(__name__)





class 					A							:


   def __init__(self					:						List[str]	,  __UpperCAmelCase					:						Optional[str] = None		)						->    Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  (
             os.path.join(__UpperCAmelCase	,  config.EXTRACTED_DATASETS_DIR		) if cache_dir else config.EXTRACTED_DATASETS_PATH
         )
         UpperCAmelCase__								=  Extractor


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


   def       lowercase_				(self					:						int	,  __UpperCAmelCase					:						str	,  __UpperCAmelCase					:						bool		)						->    bool:
         """simple docstring"""



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





   def       lowercase_				(self					:						Union[str, Any]	,  __UpperCAmelCase					:						str	,  __UpperCAmelCase					:						bool = False		)						->    str:
         """simple docstring"""



         UpperCAmelCase__								=  self.extractor.infer_extractor_format(__UpperCAmelCase		)
         if not extractor_format:
               return input_path
         UpperCAmelCase__								=  self._get_output_path(__UpperCAmelCase		)
         if self._do_extract(__UpperCAmelCase	,  __UpperCAmelCase		):
               self.extractor.extract(__UpperCAmelCase	,  __UpperCAmelCase	,  __UpperCAmelCase		)
         return output_path





class 					A							(    UpperCAmelCase_					):


   @classmethod
   @abstractmethod
   def       lowercase_				(cls					:						Dict	,  __UpperCAmelCase					:						Union[Path, str]	,  **__UpperCAmelCase					:						Dict		)						->    bool:
         """simple docstring"""



         ...





   @staticmethod
   @abstractmethod
   def       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Union[Path, str]		)						->    None:
         """simple docstring"""



         ...





class 					A							(    UpperCAmelCase_		,    UpperCAmelCase_					):
   __UpperCAmelCase			:			List[bytes]              =      []


   @staticmethod
   def       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						int		)						->    Dict:
         """simple docstring"""



         with open(__UpperCAmelCase	,  "rb"		) as f:
               return f.read(__UpperCAmelCase		)





   @classmethod
   def       lowercase_				(cls					:						Any	,  __UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						bytes = b""		)						->    bool:
         """simple docstring"""



         if not magic_number:
               UpperCAmelCase__								=  max(len(__UpperCAmelCase		) for cls_magic_number in cls.magic_numbers		)
               try:
                     UpperCAmelCase__								=  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 					A							(    UpperCAmelCase_					):


   @classmethod
   def       lowercase_				(cls					:						Optional[int]	,  __UpperCAmelCase					:						Union[Path, str]	,  **__UpperCAmelCase					:						Tuple		)						->    bool:
         """simple docstring"""



         return tarfile.is_tarfile(__UpperCAmelCase		)


   @staticmethod
   def       lowercase_				(__UpperCAmelCase					:						Union[str, Any]	,  __UpperCAmelCase					:						List[Any]		)						->    int:
         """simple docstring"""



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

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

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

         UpperCAmelCase__								=  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       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Union[Path, str]		)						->    None:
         """simple docstring"""



         os.makedirs(__UpperCAmelCase	,  exist_ok=__UpperCAmelCase		)
         UpperCAmelCase__								=  tarfile.open(__UpperCAmelCase		)
         tar_file.extractall(__UpperCAmelCase	,  members=TarExtractor.safemembers(__UpperCAmelCase	,  __UpperCAmelCase		)		)
         tar_file.close()





class 					A							(    UpperCAmelCase_					):
   __UpperCAmelCase			:			Optional[int]              =      [b'\x1F\x8B']


   @staticmethod
   def       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Union[Path, str]		)						->    None:
         """simple docstring"""



         with gzip.open(__UpperCAmelCase	,  "rb"		) as gzip_file:
               with open(__UpperCAmelCase	,  "wb"		) as extracted_file:
                     shutil.copyfileobj(__UpperCAmelCase	,  __UpperCAmelCase		)





class 					A							(    UpperCAmelCase_					):
   __UpperCAmelCase			:			Tuple              =      [
       b'PK\x03\x04',
       b'PK\x05\x06',  # empty archive
       b'PK\x07\x08',  # spanned archive
   ]


   @classmethod
   def       lowercase_				(cls					:						Optional[Any]	,  __UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						bytes = b""		)						->    bool:
         """simple docstring"""



         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:
                     UpperCAmelCase__								=  _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:
                                       UpperCAmelCase__								=  fp.read(__UpperCAmelCase		)  # CD is where we expect it to be
                                       if len(__UpperCAmelCase		) == sizeCentralDir:
                                             UpperCAmelCase__								=  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       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Union[Path, str]		)						->    None:
         """simple docstring"""



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





class 					A							(    UpperCAmelCase_					):
   __UpperCAmelCase			:			str              =      [b'\xFD\x37\x7A\x58\x5A\x00']


   @staticmethod
   def       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Union[Path, str]		)						->    None:
         """simple docstring"""



         with lzma.open(__UpperCAmelCase		) as compressed_file:
               with open(__UpperCAmelCase	,  "wb"		) as extracted_file:
                     shutil.copyfileobj(__UpperCAmelCase	,  __UpperCAmelCase		)





class 					A							(    UpperCAmelCase_					):
   __UpperCAmelCase			:			Union[str, Any]              =      [b'Rar!\x1a\x07\x00', b'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID


   @staticmethod
   def       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Union[Path, str]		)						->    None:
         """simple docstring"""



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

         os.makedirs(__UpperCAmelCase	,  exist_ok=__UpperCAmelCase		)
         UpperCAmelCase__								=  rarfile.RarFile(__UpperCAmelCase		)
         rf.extractall(__UpperCAmelCase		)
         rf.close()





class 					A							(    UpperCAmelCase_					):
   __UpperCAmelCase			:			str              =      [b'\x28\xb5\x2F\xFD']


   @staticmethod
   def       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Union[Path, str]		)						->    None:
         """simple docstring"""



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

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





class 					A							(    UpperCAmelCase_					):
   __UpperCAmelCase			:			Tuple              =      [b'\x42\x5A\x68']


   @staticmethod
   def       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Union[Path, str]		)						->    None:
         """simple docstring"""



         with bza.open(__UpperCAmelCase	,  "rb"		) as compressed_file:
               with open(__UpperCAmelCase	,  "wb"		) as extracted_file:
                     shutil.copyfileobj(__UpperCAmelCase	,  __UpperCAmelCase		)





class 					A							(    UpperCAmelCase_					):
   __UpperCAmelCase			:			Any              =      [b'\x37\x7A\xBC\xAF\x27\x1C']


   @staticmethod
   def       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Union[Path, str]		)						->    None:
         """simple docstring"""



         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 					A							(    UpperCAmelCase_					):
   __UpperCAmelCase			:			Optional[Any]              =      [b'\x04\x22\x4D\x18']


   @staticmethod
   def       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Union[Path, str]		)						->    None:
         """simple docstring"""



         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 					A							:
   #  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
   __UpperCAmelCase			:			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					:						Optional[int]		)						->    Optional[int]:
         """simple docstring"""



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


   @staticmethod
   def       lowercase_				(__UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						int		)						->    int:
         """simple docstring"""



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


   @classmethod
   def       lowercase_				(cls					:						Union[str, Any]	,  __UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						bool = 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=__UpperCAmelCase	,  )
         UpperCAmelCase__								=  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       lowercase_				(cls					:						str	,  __UpperCAmelCase					:						Union[Path, str]		)						->    str:  # <Added version="2.4.0"/>
         """simple docstring"""



         UpperCAmelCase__								=  cls._get_magic_number_max_length()
         UpperCAmelCase__								=  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       lowercase_				(cls					:						Dict	,  __UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Union[Path, str]	,  __UpperCAmelCase					:						Optional[str] = None	,  __UpperCAmelCase					:						Optional[BaseExtractor] = "deprecated"	,  )						->    None:
         """simple docstring"""



         os.makedirs(os.path.dirname(__UpperCAmelCase		)	,  exist_ok=__UpperCAmelCase		)
         # Prevent parallel extractions
         UpperCAmelCase__								=  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	,  )
                           UpperCAmelCase__								=  extractor if extractor != "deprecated" else extractor_format
                     else:
                           UpperCAmelCase__								=  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		)




from collections import Counter
from pathlib import Path
from typing import Optional, Tuple

import yaml





class 					A							(    yaml.SafeLoader					):


   def       lowercase_				(self					:						Tuple	,  __UpperCAmelCase					:						str		)						->    Tuple:
         """simple docstring"""



         UpperCAmelCase__								=  [self.constructed_objects[key_node] for key_node, _ in node.value]
         UpperCAmelCase__								=  [tuple(__UpperCAmelCase		) if isinstance(__UpperCAmelCase	,  __UpperCAmelCase		) else key for key in keys]
         UpperCAmelCase__								=  Counter(__UpperCAmelCase		)
         UpperCAmelCase__								=  [key for key in counter if counter[key] > 1]
         if duplicate_keys:
               raise TypeError(f"""Got duplicate yaml keys: {duplicate_keys}"""		)





   def       lowercase_				(self					:						Dict	,  __UpperCAmelCase					:						Dict	,  __UpperCAmelCase					:						Any=False		)						->    Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  super().construct_mapping(__UpperCAmelCase	,  deep=__UpperCAmelCase		)
         self._check_no_duplicates_on_constructed_node(__UpperCAmelCase		)
         return mapping




def        lowerCAmelCase_			(					__A							)					->    Tuple[Optional[str], str]:







      '''simple docstring'''


      UpperCAmelCase__								=  list(readme_content.splitlines()							)
      if full_content and full_content[0] == "---" and "---" in full_content[1:]:
            UpperCAmelCase__								=  full_content[1:].index("---"							) + 1
            UpperCAmelCase__								=  "\n".join(full_content[1:sep_idx]							)
            return yamlblock, "\n".join(full_content[sep_idx + 1 :]							)

      return None, "\n".join(__A							)





class 					A							(    UpperCAmelCase_					):
   # class attributes
   __UpperCAmelCase			:			Optional[Any]              =      {'train_eval_index'}  # train-eval-index in the YAML metadata


   @classmethod
   def       lowercase_				(cls					:						List[str]	,  __UpperCAmelCase					:						Path		)						->    "DatasetMetadata":
         """simple docstring"""



         with open(__UpperCAmelCase	,  encoding="utf-8"		) as readme_file:
               UpperCAmelCase__		,				UpperCAmelCase__								=  _split_yaml_from_readme(readme_file.read()		)
         if yaml_string is not None:
               return cls.from_yaml_string(__UpperCAmelCase		)
         else:
               return cls()


   def       lowercase_				(self					:						int	,  __UpperCAmelCase					:						Path		)						->    str:
         """simple docstring"""



         if path.exists():
               with open(__UpperCAmelCase	,  encoding="utf-8"		) as readme_file:
                     UpperCAmelCase__								=  readme_file.read()
         else:
               UpperCAmelCase__								=  None
         UpperCAmelCase__								=  self._to_readme(__UpperCAmelCase		)
         with open(__UpperCAmelCase	,  "w"	,  encoding="utf-8"		) as readme_file:
               readme_file.write(__UpperCAmelCase		)


   def       lowercase_				(self					:						str	,  __UpperCAmelCase					:						Optional[str] = None		)						->    str:
         """simple docstring"""



         if readme_content is not None:
               UpperCAmelCase__		,				UpperCAmelCase__								=  _split_yaml_from_readme(__UpperCAmelCase		)
               UpperCAmelCase__								=  "---\n" + self.to_yaml_string() + "---\n" + content
         else:
               UpperCAmelCase__								=  "---\n" + self.to_yaml_string() + "---\n"
         return full_content


   @classmethod
   def       lowercase_				(cls					:						Optional[int]	,  __UpperCAmelCase					:						str		)						->    "DatasetMetadata":
         """simple docstring"""



         UpperCAmelCase__								=  yaml.load(__UpperCAmelCase	,  Loader=_NoDuplicateSafeLoader		) or {}

         # Convert the YAML keys to DatasetMetadata fields
         UpperCAmelCase__								=  {
             (key.replace("-"	,  "_"		) if key.replace("-"	,  "_"		) in cls._FIELDS_WITH_DASHES else key): value
             for key, value in metadata_dict.items()
         }
         return cls(**__UpperCAmelCase		)





   def       lowercase_				(self					:						List[str]		)						->    str:
         """simple docstring"""



         return yaml.safe_dump(
             {
                 (key.replace("_"	,  "-"		) if key in self._FIELDS_WITH_DASHES else key): value
                 for key, value in self.items()
             }	,  sort_keys=__UpperCAmelCase	,  allow_unicode=__UpperCAmelCase	,  encoding="utf-8"	,  ).decode("utf-8"		)




UpperCamelCase__    							= {
    'image-classification': [],
    'translation': [],
    'image-segmentation': [],
    'fill-mask': [],
    'automatic-speech-recognition': [],
    'token-classification': [],
    'sentence-similarity': [],
    'audio-classification': [],
    'question-answering': [],
    'summarization': [],
    'zero-shot-classification': [],
    'table-to-text': [],
    'feature-extraction': [],
    'other': [],
    'multiple-choice': [],
    'text-classification': [],
    'text-to-image': [],
    'text2text-generation': [],
    'zero-shot-image-classification': [],
    'tabular-classification': [],
    'tabular-regression': [],
    'image-to-image': [],
    'tabular-to-text': [],
    'unconditional-image-generation': [],
    'text-retrieval': [],
    'text-to-speech': [],
    'object-detection': [],
    'audio-to-audio': [],
    'text-generation': [],
    'conversational': [],
    'table-question-answering': [],
    'visual-question-answering': [],
    'image-to-text': [],
    'reinforcement-learning': [],
    'voice-activity-detection': [],
    'time-series-forecasting': [],
    'document-question-answering': [],
}


if __name__ == "__main__":
      from argparse import ArgumentParser

      UpperCamelCase__    							= ArgumentParser(usage='Validate the yaml metadata block of a README.md file.')
      ap.add_argument('readme_filepath')
      UpperCamelCase__    							= ap.parse_args()

      UpperCamelCase__    							= Path(args.readme_filepath)
      UpperCamelCase__    							= DatasetMetadata.from_readme(readme_filepath)
      print(dataset_metadata)
      dataset_metadata.to_readme(readme_filepath)



