





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


__A											=						get_logger(__name__)






class    _lowerCAmelCase  :
       """simple docstring"""




       def __init__(       self       ,					__UpperCAmelCase = None ):



         '''simple docstring'''

         lowerCAmelCase__     :Any											=				(
             os.path.join(lowerCAmelCase_       ,					config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH
         )
         lowerCAmelCase__     :List[Any]											=				Extractor






       def 	snake_case		(       self       ,					__UpperCAmelCase ):



         '''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"
         lowerCAmelCase__     :Optional[Any]											=				os.path.abspath(lowerCAmelCase_ )
         return os.path.join(self.extract_dir       ,					hash_url_to_filename(lowerCAmelCase_ ) )






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

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






       def 	snake_case		(       self       ,					__UpperCAmelCase       ,					__UpperCAmelCase = False ):



         '''simple docstring'''

         lowerCAmelCase__     :Optional[int]											=				self.extractor.infer_extractor_format(lowerCAmelCase_ )
         if not extractor_format:
           return input_path
         lowerCAmelCase__     :Any											=				self._get_output_path(lowerCAmelCase_ )
         if self._do_extract(lowerCAmelCase_       ,					lowerCAmelCase_ ):
           self.extractor.extract(lowerCAmelCase_       ,					lowerCAmelCase_       ,					lowerCAmelCase_ )
         return output_path






class    _lowerCAmelCase  (	_a			):
       """simple docstring"""




       @classmethod
       @abstractmethod
       def 	snake_case		(       cls       ,					__UpperCAmelCase       ,					**__UpperCAmelCase ):



         '''simple docstring'''

         ...






       @staticmethod
       @abstractmethod
       def 	snake_case		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

         ...






class    _lowerCAmelCase  (	_a    ,  _a			):
       """simple docstring"""




       __magic_name__	:Optional[Any]						    =   []






       @staticmethod
       def 	snake_case		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

         with open(lowerCAmelCase_       ,					'rb' ) as f:
           return f.read(lowerCAmelCase_ )






       @classmethod
       def 	snake_case		(       cls       ,					__UpperCAmelCase       ,					__UpperCAmelCase = b"" ):



         '''simple docstring'''

         if not magic_number:
           lowerCAmelCase__     :str											=				max(len(lowerCAmelCase_ ) for cls_magic_number in cls.magic_numbers )
           try:
             lowerCAmelCase__     :int											=				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    _lowerCAmelCase  (	_a			):
       """simple docstring"""




       @classmethod
       def 	snake_case		(       cls       ,					__UpperCAmelCase       ,					**__UpperCAmelCase ):



         '''simple docstring'''

         return tarfile.is_tarfile(lowerCAmelCase_ )






       @staticmethod
       def 	snake_case		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

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

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

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

         lowerCAmelCase__     :int											=				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		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

         os.makedirs(lowerCAmelCase_       ,					exist_ok=lowerCAmelCase_ )
         lowerCAmelCase__     :Any											=				tarfile.open(lowerCAmelCase_ )
         tar_file.extractall(lowerCAmelCase_       ,					members=TarExtractor.safemembers(lowerCAmelCase_       ,					lowerCAmelCase_ ) )
         tar_file.close()






class    _lowerCAmelCase  (	_a			):
       """simple docstring"""




       __magic_name__	:Tuple						    =   [b"""\x1F\x8B"""]






       @staticmethod
       def 	snake_case		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

         with gzip.open(lowerCAmelCase_       ,					'rb' ) as gzip_file:
           with open(lowerCAmelCase_       ,					'wb' ) as extracted_file:
             shutil.copyfileobj(lowerCAmelCase_       ,					lowerCAmelCase_ )






class    _lowerCAmelCase  (	_a			):
       """simple docstring"""




       __magic_name__	:Any						    =   [
           b"""PK\x03\x04""",
           b"""PK\x05\x06""",  # empty archive
           b"""PK\x07\x08""",  # spanned archive
       ]






       @classmethod
       def 	snake_case		(       cls       ,					__UpperCAmelCase       ,					__UpperCAmelCase = b"" ):



         '''simple docstring'''

         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:
             lowerCAmelCase__     :Union[str, Any]											=				_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:
                   lowerCAmelCase__     :Optional[int]											=				fp.read(lowerCAmelCase_ )  # CD is where we expect it to be
                   if len(lowerCAmelCase_ ) == sizeCentralDir:
                     lowerCAmelCase__     :Optional[Any]											=				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		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

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






class    _lowerCAmelCase  (	_a			):
       """simple docstring"""




       __magic_name__	:Tuple						    =   [b"""\xFD\x37\x7A\x58\x5A\x00"""]






       @staticmethod
       def 	snake_case		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

         with lzma.open(lowerCAmelCase_ ) as compressed_file:
           with open(lowerCAmelCase_       ,					'wb' ) as extracted_file:
             shutil.copyfileobj(lowerCAmelCase_       ,					lowerCAmelCase_ )






class    _lowerCAmelCase  (	_a			):
       """simple docstring"""




       __magic_name__	:Any						    =   [b"""Rar!\x1a\x07\x00""", b"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID






       @staticmethod
       def 	snake_case		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

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

         os.makedirs(lowerCAmelCase_       ,					exist_ok=lowerCAmelCase_ )
         lowerCAmelCase__     :List[Any]											=				rarfile.RarFile(lowerCAmelCase_ )
         rf.extractall(lowerCAmelCase_ )
         rf.close()






class    _lowerCAmelCase  (	_a			):
       """simple docstring"""




       __magic_name__	:str						    =   [b"""\x28\xb5\x2F\xFD"""]






       @staticmethod
       def 	snake_case		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

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

         lowerCAmelCase__     :List[Any]											=				zstd.ZstdDecompressor()
         with open(lowerCAmelCase_       ,					'rb' ) as ifh, open(lowerCAmelCase_       ,					'wb' ) as ofh:
           dctx.copy_stream(lowerCAmelCase_       ,					lowerCAmelCase_ )






class    _lowerCAmelCase  (	_a			):
       """simple docstring"""




       __magic_name__	:Optional[int]						    =   [b"""\x42\x5A\x68"""]






       @staticmethod
       def 	snake_case		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

         with bza.open(lowerCAmelCase_       ,					'rb' ) as compressed_file:
           with open(lowerCAmelCase_       ,					'wb' ) as extracted_file:
             shutil.copyfileobj(lowerCAmelCase_       ,					lowerCAmelCase_ )






class    _lowerCAmelCase  (	_a			):
       """simple docstring"""




       __magic_name__	:Any						    =   [b"""\x37\x7A\xBC\xAF\x27\x1C"""]






       @staticmethod
       def 	snake_case		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

         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    _lowerCAmelCase  (	_a			):
       """simple docstring"""




       __magic_name__	:List[str]						    =   [b"""\x04\x22\x4D\x18"""]






       @staticmethod
       def 	snake_case		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

         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    _lowerCAmelCase  :
       """simple docstring"""




       __magic_name__	:int						    =   {
           """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 ):



         '''simple docstring'''

         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		(       __UpperCAmelCase       ,					__UpperCAmelCase ):



         '''simple docstring'''

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






       @classmethod
       def 	snake_case		(       cls       ,					__UpperCAmelCase       ,					__UpperCAmelCase = False ):



         '''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=lowerCAmelCase_       ,					)
         lowerCAmelCase__     :str											=				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       ,					__UpperCAmelCase ):  # <Added version="2.4.0"/>



         '''simple docstring'''

         lowerCAmelCase__     :List[str]											=				cls._get_magic_number_max_length()
         lowerCAmelCase__     :Tuple											=				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       ,					__UpperCAmelCase       ,					__UpperCAmelCase       ,					__UpperCAmelCase = None       ,					__UpperCAmelCase = "deprecated"       ,					):



         '''simple docstring'''

         os.makedirs(os.path.dirname(lowerCAmelCase_ )       ,					exist_ok=lowerCAmelCase_ )
         # Prevent parallel extractions
         lowerCAmelCase__     :Union[str, Any]											=				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_       ,					)
               lowerCAmelCase__     :List[str]											=				extractor if extractor != 'deprecated' else extractor_format
             else:
               lowerCAmelCase__     :Dict											=				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 TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


_snake_case : str  				=						{
    'configuration_layoutlmv3': [
        'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'LayoutLMv3Config',
        'LayoutLMv3OnnxConfig',
    ],
    'processing_layoutlmv3': ['LayoutLMv3Processor'],
    'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'],
}

try:
				if not is_tokenizers_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_snake_case : List[str]  				=						['LayoutLMv3TokenizerFast']

try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_snake_case : Optional[int]  				=						[
				    'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST',
				    'LayoutLMv3ForQuestionAnswering',
				    'LayoutLMv3ForSequenceClassification',
				    'LayoutLMv3ForTokenClassification',
				    'LayoutLMv3Model',
				    'LayoutLMv3PreTrainedModel',
				]

try:
				if not is_tf_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_snake_case : Tuple  				=						[
				    'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST',
				    'TFLayoutLMv3ForQuestionAnswering',
				    'TFLayoutLMv3ForSequenceClassification',
				    'TFLayoutLMv3ForTokenClassification',
				    'TFLayoutLMv3Model',
				    'TFLayoutLMv3PreTrainedModel',
				]

try:
				if not is_vision_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_snake_case : List[Any]  				=						['LayoutLMv3FeatureExtractor']
				_snake_case : Tuple  				=						['LayoutLMv3ImageProcessor']


if TYPE_CHECKING:
				from .configuration_layoutlmva import (
				    LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP,
				    LayoutLMvaConfig,
				    LayoutLMvaOnnxConfig,
				)
				from .processing_layoutlmva import LayoutLMvaProcessor
				from .tokenization_layoutlmva import LayoutLMvaTokenizer

				try:
								if not is_tokenizers_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_layoutlmva import (
								    LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
								    LayoutLMvaForQuestionAnswering,
								    LayoutLMvaForSequenceClassification,
								    LayoutLMvaForTokenClassification,
								    LayoutLMvaModel,
								    LayoutLMvaPreTrainedModel,
								)

				try:
								if not is_tf_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_tf_layoutlmva import (
								    TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
								    TFLayoutLMvaForQuestionAnswering,
								    TFLayoutLMvaForSequenceClassification,
								    TFLayoutLMvaForTokenClassification,
								    TFLayoutLMvaModel,
								    TFLayoutLMvaPreTrainedModel,
								)

				try:
								if not is_vision_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor
								from .image_processing_layoutlmva import LayoutLMvaImageProcessor

else:
				import sys

				_snake_case : Any  				=						_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)

