





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


snake_case 				=       get_logger(__name__)





class 				A_				:







       """simple docstring"""





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







       def    __UpperCAmelCase (    self	:	int						,__A	:	List[str]  )						->					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"
         _lowercase							= os.path.abspath(__A  )
         return os.path.join(self.extract_dir						,hash_url_to_filename(__A  )  )







       def    __UpperCAmelCase (    self	:	Any						,__A	:	Any						,__A	:	Optional[int]  )						->					bool:
         return force_extract or (
             not os.path.isfile(__A  ) and not (os.path.isdir(__A  ) and os.listdir(__A  ))
         )







       def    __UpperCAmelCase (    self	:	int						,__A	:	int						,__A	:	Optional[int] = False  )						->					str:
         _lowercase							= self.extractor.infer_extractor_format(__A  )
         if not extractor_format:
           return input_path
         _lowercase							= self._get_output_path(__A  )
         if self._do_extract(__A						,__A  ):
           self.extractor.extract(__A						,__A						,__A  )
         return output_path





class 				A_				(      UpperCamelCase__	):







       """simple docstring"""





       @classmethod
       @abstractmethod
       def    __UpperCAmelCase (    cls	:	Optional[Any]						,__A	:	Union[str, Any]						,**__A	:	Tuple  )						->					bool:
         ...







       @staticmethod
       @abstractmethod
       def    __UpperCAmelCase (    __A	:	Optional[Any]						,__A	:	Optional[Any]  )						->					None:
         ...





class 				A_				(      UpperCamelCase__					,	UpperCamelCase__	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : List[bytes]      =  []







       @staticmethod
       def    __UpperCAmelCase (    __A	:	List[Any]						,__A	:	Optional[Any]  )						->					List[Any]:
         with open(__A						,'rb'  ) as f:
           return f.read(__A  )







       @classmethod
       def    __UpperCAmelCase (    cls	:	Union[str, Any]						,__A	:	List[Any]						,__A	:	Any = b""  )						->					bool:
         if not magic_number:
           _lowercase							= max(len(__A  ) for cls_magic_number in cls.magic_numbers  )
           try:
             _lowercase							= cls.read_magic_number(__A						,__A  )
           except OSError:
             return False
         return any(magic_number.startswith(__A  ) for cls_magic_number in cls.magic_numbers  )





class 				A_				(      UpperCamelCase__	):







       """simple docstring"""





       @classmethod
       def    __UpperCAmelCase (    cls	:	Optional[Any]						,__A	:	List[Any]						,**__A	:	Union[str, Any]  )						->					bool:
         return tarfile.is_tarfile(__A  )







       @staticmethod
       def    __UpperCAmelCase (    __A	:	Optional[int]						,__A	:	List[Any]  )						->					Dict:

         def resolved(__A	:	Optional[int]  ) -> str:
           return os.path.realpath(os.path.abspath(__A  )  )

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

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

         _lowercase							= resolved(__A  )

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







       @staticmethod
       def    __UpperCAmelCase (    __A	:	List[Any]						,__A	:	Optional[Any]  )						->					None:
         os.makedirs(__A						,exist_ok=__A  )
         _lowercase							= tarfile.open(__A  )
         tar_file.extractall(__A						,members=TarExtractor.safemembers(__A						,__A  )  )
         tar_file.close()





class 				A_				(      UpperCamelCase__	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Any      =  [B"""\x1F\x8B"""]







       @staticmethod
       def    __UpperCAmelCase (    __A	:	List[str]						,__A	:	List[Any]  )						->					None:
         with gzip.open(__A						,'rb'  ) as gzip_file:
           with open(__A						,'wb'  ) as extracted_file:
             shutil.copyfileobj(__A						,__A  )





class 				A_				(      UpperCamelCase__	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : List[Any]      =  [
           B"""PK\x03\x04""",
           B"""PK\x05\x06""",  # empty archive
           B"""PK\x07\x08""",  # spanned archive
       ]







       @classmethod
       def    __UpperCAmelCase (    cls	:	str						,__A	:	List[Any]						,__A	:	Tuple = b""  )						->					bool:
         if super().is_extractable(__A						,magic_number=__A  ):
           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(__A						,'rb'  ) as fp:
             _lowercase							= _EndRecData(__A  )
             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:
                   _lowercase							= fp.read(__A  )  # CD is where we expect it to be
                   if len(__A  ) == sizeCentralDir:
                     _lowercase							= struct.unpack(__A						,__A  )  # 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 (    __A	:	Optional[int]						,__A	:	Any  )						->					None:
         os.makedirs(__A						,exist_ok=__A  )
         with zipfile.ZipFile(__A						,'r'  ) as zip_file:
           zip_file.extractall(__A  )
           zip_file.close()





class 				A_				(      UpperCamelCase__	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Tuple      =  [B"""\xFD\x37\x7A\x58\x5A\x00"""]







       @staticmethod
       def    __UpperCAmelCase (    __A	:	List[Any]						,__A	:	Optional[Any]  )						->					None:
         with lzma.open(__A  ) as compressed_file:
           with open(__A						,'wb'  ) as extracted_file:
             shutil.copyfileobj(__A						,__A  )





class 				A_				(      UpperCamelCase__	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : str      =  [B"""Rar!\x1a\x07\x00""", B"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID







       @staticmethod
       def    __UpperCAmelCase (    __A	:	Optional[int]						,__A	:	List[Any]  )						->					None:
         if not config.RARFILE_AVAILABLE:
           raise ImportError('Please pip install rarfile'  )
         import rarfile

         os.makedirs(__A						,exist_ok=__A  )
         _lowercase							= rarfile.RarFile(__A  )
         rf.extractall(__A  )
         rf.close()





class 				A_				(      UpperCamelCase__	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : int      =  [B"""\x28\xb5\x2F\xFD"""]







       @staticmethod
       def    __UpperCAmelCase (    __A	:	Optional[Any]						,__A	:	List[Any]  )						->					None:
         if not config.ZSTANDARD_AVAILABLE:
           raise ImportError('Please pip install zstandard'  )
         import zstandard as zstd

         _lowercase							= zstd.ZstdDecompressor()
         with open(__A						,'rb'  ) as ifh, open(__A						,'wb'  ) as ofh:
           dctx.copy_stream(__A						,__A  )





class 				A_				(      UpperCamelCase__	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Any      =  [B"""\x42\x5A\x68"""]







       @staticmethod
       def    __UpperCAmelCase (    __A	:	Tuple						,__A	:	Union[str, Any]  )						->					None:
         with bza.open(__A						,'rb'  ) as compressed_file:
           with open(__A						,'wb'  ) as extracted_file:
             shutil.copyfileobj(__A						,__A  )





class 				A_				(      UpperCamelCase__	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Any      =  [B"""\x37\x7A\xBC\xAF\x27\x1C"""]







       @staticmethod
       def    __UpperCAmelCase (    __A	:	int						,__A	:	List[Any]  )						->					None:
         if not config.PY7ZR_AVAILABLE:
           raise ImportError('Please pip install py7zr'  )
         import pyazr

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





class 				A_				(      UpperCamelCase__	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Any      =  [B"""\x04\x22\x4D\x18"""]







       @staticmethod
       def    __UpperCAmelCase (    __A	:	Optional[Any]						,__A	:	str  )						->					None:
         if not config.LZ4_AVAILABLE:
           raise ImportError('Please pip install lz4'  )
         import lza.frame

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





class 				A_				:







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : 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[int]  )						->					Optional[Any]:
         return max(
             len(__A  )
             for extractor in cls.extractors.values()
             if issubclass(__A						,__A  )
             for extractor_magic_number in extractor.magic_numbers  )







       @staticmethod
       def    __UpperCAmelCase (    __A	:	Optional[Any]						,__A	:	Dict  )						->					Dict:
         try:
           return MagicNumberBaseExtractor.read_magic_number(__A						,magic_number_length=__A  )
         except OSError:
           return b""







       @classmethod
       def    __UpperCAmelCase (    cls	:	int						,__A	:	Optional[int]						,__A	:	Optional[Any] = 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=__A						,)
         _lowercase							= cls.infer_extractor_format(__A  )
         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	:	Dict						,__A	:	Union[str, Any]  )						->					str:  # <Added version="2.4.0"/>
         _lowercase							= cls._get_magic_number_max_length()
         _lowercase							= cls._read_magic_number(__A						,__A  )
         for extractor_format, extractor in cls.extractors.items():
           if extractor.is_extractable(__A						,magic_number=__A  ):
             return extractor_format







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






import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
      import torch

      from transformers.generation import DisjunctiveConstraint





@require_torch
class 				A_				(      unittest.TestCase	):







       """simple docstring"""





       def    __UpperCAmelCase (    self	:	Union[str, Any]  )						->					List[Any]:
         # For consistency across different places the DisjunctiveConstraint is called,
         # dc.token_ids is a list of integers. It is also initialized only by integers.

         _lowercase							= [[1, 2, 4], [1, 2, 3, 4]]
         _lowercase							= DisjunctiveConstraint(__A  )
         self.assertTrue(isinstance(dc.token_ids						,__A  )  )

         with self.assertRaises(__A  ):
           DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]]  )  )

         with self.assertRaises(__A  ):
           DisjunctiveConstraint([torch.LongTensor([1, 2, 4]  ), torch.LongTensor([1, 2, 3, 4, 5]  )]  )







       def    __UpperCAmelCase (    self	:	List[Any]  )						->					str:
         # We can't have constraints that are complete subsets of another. This leads to a preverse
         # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
         # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
         # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
         # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
         _lowercase							= [[1, 2], [1, 2, 3, 4]]

         with self.assertRaises(__A  ):
           DisjunctiveConstraint(__A  )  # fails here







       def    __UpperCAmelCase (    self	:	Dict  )						->					Optional[Any]:
         _lowercase							= [[1, 2, 3], [1, 2, 4]]

         _lowercase							= DisjunctiveConstraint(__A  )

         _lowercase						,		_lowercase						,		_lowercase							= dc.update(1  )
         _lowercase							= stepped is True and completed is False and reset is False
         self.assertTrue(__A  )
         self.assertTrue(not dc.completed  )
         self.assertTrue(dc.current_seq == [1]  )

         _lowercase						,		_lowercase						,		_lowercase							= dc.update(2  )
         _lowercase							= stepped is True and completed is False and reset is False
         self.assertTrue(__A  )
         self.assertTrue(not dc.completed  )
         self.assertTrue(dc.current_seq == [1, 2]  )

         _lowercase						,		_lowercase						,		_lowercase							= dc.update(3  )
         _lowercase							= stepped is True and completed is True and reset is False
         self.assertTrue(__A  )
         self.assertTrue(dc.completed  )  # Completed!
         self.assertTrue(dc.current_seq == [1, 2, 3]  )







       def    __UpperCAmelCase (    self	:	List[Any]  )						->					Any:
         _lowercase							= [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]

         _lowercase							= DisjunctiveConstraint(__A  )

         _lowercase						,		_lowercase						,		_lowercase							= dc.update(1  )
         self.assertTrue(not dc.completed  )
         self.assertTrue(dc.current_seq == [1]  )

         _lowercase						,		_lowercase						,		_lowercase							= dc.update(2  )
         self.assertTrue(not dc.completed  )
         self.assertTrue(dc.current_seq == [1, 2]  )

         _lowercase						,		_lowercase						,		_lowercase							= dc.update(4  )
         self.assertTrue(not dc.completed  )
         self.assertTrue(dc.current_seq == [1, 2, 4]  )

         _lowercase						,		_lowercase						,		_lowercase							= dc.update(5  )
         self.assertTrue(dc.completed  )  # Completed!
         self.assertTrue(dc.current_seq == [1, 2, 4, 5]  )

         dc.reset()

         _lowercase						,		_lowercase						,		_lowercase							= dc.update(1  )
         self.assertTrue(not dc.completed  )
         self.assertTrue(dc.remaining() == 3  )
         self.assertTrue(dc.current_seq == [1]  )

         _lowercase						,		_lowercase						,		_lowercase							= dc.update(2  )
         self.assertTrue(not dc.completed  )
         self.assertTrue(dc.remaining() == 2  )
         self.assertTrue(dc.current_seq == [1, 2]  )

         _lowercase						,		_lowercase						,		_lowercase							= dc.update(5  )
         self.assertTrue(dc.completed  )  # Completed!
         self.assertTrue(dc.remaining() == 0  )
         self.assertTrue(dc.current_seq == [1, 2, 5]  )