
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		:





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





     def 		UpperCAmelCase(self				:   Optional[int]    ,   _A				:   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"
         snake_case								= os.path.abspath(_A       )
         return os.path.join(self.extract_dir    ,   hash_url_to_filename(_A       )       )





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





     def 		UpperCAmelCase(self				:   Union[str, Any]    ,   _A				:   str    ,   _A				:   bool = False       )						->						str:
         snake_case								= self.extractor.infer_extractor_format(_A       )
         if not extractor_format:
             return input_path
         snake_case								= self._get_output_path(_A       )
         if self._do_extract(_A    ,   _A       ):
             self.extractor.extract(_A    ,   _A    ,   _A       )
         return output_path







class 					lowerCamelCase		(  A_  ):





     @classmethod
     @abstractmethod
     def 		UpperCAmelCase(cls				:   Optional[Any]    ,   _A				:   Union[Path, str]    ,   **_A				:   int       )						->						bool:
         ...





     @staticmethod
     @abstractmethod
     def 		UpperCAmelCase(_A				:   Union[Path, str]    ,   _A				:   Union[Path, str]       )						->						None:
         ...







class 					lowerCamelCase		(  A_							,			A_  ):
     UpperCAmelCase__    :							List[bytes]									=		[]





     @staticmethod
     def 		UpperCAmelCase(_A				:   Union[Path, str]    ,   _A				:   int       )						->						int:
         with open(_A    ,   "rb"       ) as f:
             return f.read(_A       )





     @classmethod
     def 		UpperCAmelCase(cls				:   Any    ,   _A				:   Union[Path, str]    ,   _A				:   bytes = b""       )						->						bool:
         if not magic_number:
             snake_case								= max(len(_A       ) for cls_magic_number in cls.magic_numbers       )
             try:
                 snake_case								= 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 					lowerCamelCase		(  A_  ):





     @classmethod
     def 		UpperCAmelCase(cls				:   Dict    ,   _A				:   Union[Path, str]    ,   **_A				:   str       )						->						bool:
         return tarfile.is_tarfile(_A       )





     @staticmethod
     def 		UpperCAmelCase(_A				:   Optional[Any]    ,   _A				:   List[str]       )						->						Tuple:

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

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

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

         snake_case								= 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				:   Union[Path, str]    ,   _A				:   Union[Path, str]       )						->						None:
         os.makedirs(_A    ,   exist_ok=_A       )
         snake_case								= tarfile.open(_A       )
         tar_file.extractall(_A    ,   members=TarExtractor.safemembers(_A    ,   _A       )       )
         tar_file.close()







class 					lowerCamelCase		(  A_  ):
     UpperCAmelCase__    :							str									=		[B"\x1F\x8B"]





     @staticmethod
     def 		UpperCAmelCase(_A				:   Union[Path, str]    ,   _A				:   Union[Path, str]       )						->						None:
         with gzip.open(_A    ,   "rb"       ) as gzip_file:
             with open(_A    ,   "wb"       ) as extracted_file:
                 shutil.copyfileobj(_A    ,   _A       )







class 					lowerCamelCase		(  A_  ):
     UpperCAmelCase__    :							Union[str, Any]									=		[
         B"PK\x03\x04",
         B"PK\x05\x06",  # empty archive
         B"PK\x07\x08",  # spanned archive
     ]





     @classmethod
     def 		UpperCAmelCase(cls				:   int    ,   _A				:   Union[Path, str]    ,   _A				:   bytes = 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:
                 snake_case								= _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:
                             snake_case								= fp.read(_A       )  # CD is where we expect it to be
                             if len(_A       ) == sizeCentralDir:
                                 snake_case								= 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				:   Union[Path, str]    ,   _A				:   Union[Path, str]       )						->						None:
         os.makedirs(_A    ,   exist_ok=_A       )
         with zipfile.ZipFile(_A    ,   "r"       ) as zip_file:
             zip_file.extractall(_A       )
             zip_file.close()







class 					lowerCamelCase		(  A_  ):
     UpperCAmelCase__    :							Union[str, Any]									=		[B"\xFD\x37\x7A\x58\x5A\x00"]





     @staticmethod
     def 		UpperCAmelCase(_A				:   Union[Path, str]    ,   _A				:   Union[Path, str]       )						->						None:
         with lzma.open(_A       ) as compressed_file:
             with open(_A    ,   "wb"       ) as extracted_file:
                 shutil.copyfileobj(_A    ,   _A       )







class 					lowerCamelCase		(  A_  ):
     UpperCAmelCase__    :							Tuple									=		[B"Rar!\x1a\x07\x00", B"Rar!\x1a\x07\x01\x00"]  # RAR_ID  # RAR5_ID





     @staticmethod
     def 		UpperCAmelCase(_A				:   Union[Path, str]    ,   _A				:   Union[Path, str]       )						->						None:
         if not config.RARFILE_AVAILABLE:
             raise ImportError("Please pip install rarfile"       )
         import rarfile

         os.makedirs(_A    ,   exist_ok=_A       )
         snake_case								= rarfile.RarFile(_A       )
         rf.extractall(_A       )
         rf.close()







class 					lowerCamelCase		(  A_  ):
     UpperCAmelCase__    :							str									=		[B"\x28\xb5\x2F\xFD"]





     @staticmethod
     def 		UpperCAmelCase(_A				:   Union[Path, str]    ,   _A				:   Union[Path, str]       )						->						None:
         if not config.ZSTANDARD_AVAILABLE:
             raise ImportError("Please pip install zstandard"       )
         import zstandard as zstd

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







class 					lowerCamelCase		(  A_  ):
     UpperCAmelCase__    :							str									=		[B"\x42\x5A\x68"]





     @staticmethod
     def 		UpperCAmelCase(_A				:   Union[Path, str]    ,   _A				:   Union[Path, str]       )						->						None:
         with bza.open(_A    ,   "rb"       ) as compressed_file:
             with open(_A    ,   "wb"       ) as extracted_file:
                 shutil.copyfileobj(_A    ,   _A       )







class 					lowerCamelCase		(  A_  ):
     UpperCAmelCase__    :							List[str]									=		[B"\x37\x7A\xBC\xAF\x27\x1C"]





     @staticmethod
     def 		UpperCAmelCase(_A				:   Union[Path, str]    ,   _A				:   Union[Path, str]       )						->						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 					lowerCamelCase		(  A_  ):
     UpperCAmelCase__    :							Optional[int]									=		[B"\x04\x22\x4D\x18"]





     @staticmethod
     def 		UpperCAmelCase(_A				:   Union[Path, str]    ,   _A				:   Union[Path, 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 					lowerCamelCase		:
     #  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 		UpperCAmelCase(cls				:   str       )						->						Optional[int]:
         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				:   Union[Path, str]    ,   _A				:   int       )						->						Any:
         try:
             return MagicNumberBaseExtractor.read_magic_number(_A    ,   magic_number_length=_A       )
         except OSError:
             return b""





     @classmethod
     def 		UpperCAmelCase(cls				:   Optional[int]    ,   _A				:   Union[Path, str]    ,   _A				:   bool = 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    ,   )
         snake_case								= 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				:   str    ,   _A				:   Union[Path, str]       )						->						str:  # <Added version="2.4.0"/>
         snake_case								= cls._get_magic_number_max_length()
         snake_case								= 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[Path, str]    ,   _A				:   Union[Path, str]    ,   _A				:   Optional[str] = None    ,   _A				:   Optional[BaseExtractor] = "deprecated"    ,   )						->						None:
         os.makedirs(os.path.dirname(_A       )    ,   exist_ok=_A       )
         # Prevent parallel extractions
         snake_case								= 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    ,   )
                     snake_case								= extractor if extractor != "deprecated" else extractor_format
                 else:
                     snake_case								= 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 warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType







class 					lowerCamelCase		(  A_  ):
     UpperCAmelCase__    :							Dict									=		["image_processor", "tokenizer"]
     UpperCAmelCase__    :							Dict									=		"LayoutLMv2ImageProcessor"
     UpperCAmelCase__    :							Optional[Any]									=		("LayoutXLMTokenizer", "LayoutXLMTokenizerFast")





     def __init__(self				:   str    ,   _A				:   Any=None    ,   _A				:   Tuple=None    ,   **_A				:   Optional[Any]       )						->						Optional[int]:
         if "feature_extractor" in kwargs:
             warnings.warn(
                 "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
                 " instead."    ,   _A    ,   )
             snake_case								= kwargs.pop("feature_extractor"       )

         snake_case								= image_processor if image_processor is not None else feature_extractor
         if image_processor is None:
             raise ValueError("You need to specify an `image_processor`."       )
         if tokenizer is None:
             raise ValueError("You need to specify a `tokenizer`."       )

         super().__init__(_A    ,   _A       )





     def __call__(self				:   int    ,   _A				:   List[str]    ,   _A				:   Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None    ,   _A				:   Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None    ,   _A				:   Union[List[List[int]], List[List[List[int]]]] = None    ,   _A				:   Optional[Union[List[int], List[List[int]]]] = None    ,   _A				:   bool = True    ,   _A				:   Union[bool, str, PaddingStrategy] = False    ,   _A				:   Union[bool, str, TruncationStrategy] = None    ,   _A				:   Optional[int] = None    ,   _A				:   int = 0    ,   _A				:   Optional[int] = None    ,   _A				:   Optional[bool] = None    ,   _A				:   Optional[bool] = None    ,   _A				:   bool = False    ,   _A				:   bool = False    ,   _A				:   bool = False    ,   _A				:   bool = False    ,   _A				:   bool = True    ,   _A				:   Optional[Union[str, TensorType]] = None    ,   **_A				:   Dict    ,   )						->						BatchEncoding:
         # verify input
         if self.image_processor.apply_ocr and (boxes is not None):
             raise ValueError(
                 "You cannot provide bounding boxes "
                 "if you initialized the image processor with apply_ocr set to True."       )

         if self.image_processor.apply_ocr and (word_labels is not None):
             raise ValueError(
                 "You cannot provide word labels if you initialized the image processor with apply_ocr set to True."       )

         if return_overflowing_tokens is True and return_offsets_mapping is False:
             raise ValueError("You cannot return overflowing tokens without returning the offsets mapping."       )

         # first, apply the image processor
         snake_case								= self.image_processor(images=_A    ,   return_tensors=_A       )

         # second, apply the tokenizer
         if text is not None and self.image_processor.apply_ocr and text_pair is None:
             if isinstance(_A    ,   _A       ):
                 snake_case								= [text]  # add batch dimension (as the image processor always adds a batch dimension)
             snake_case								= features["words"]

         snake_case								= self.tokenizer(
             text=text if text is not None else features["words"]    ,   text_pair=text_pair if text_pair is not None else None    ,   boxes=boxes if boxes is not None else features["boxes"]    ,   word_labels=_A    ,   add_special_tokens=_A    ,   padding=_A    ,   truncation=_A    ,   max_length=_A    ,   stride=_A    ,   pad_to_multiple_of=_A    ,   return_token_type_ids=_A    ,   return_attention_mask=_A    ,   return_overflowing_tokens=_A    ,   return_special_tokens_mask=_A    ,   return_offsets_mapping=_A    ,   return_length=_A    ,   verbose=_A    ,   return_tensors=_A    ,   **_A    ,   )

         # add pixel values
         snake_case								= features.pop("pixel_values"       )
         if return_overflowing_tokens is True:
             snake_case								= self.get_overflowing_images(_A    ,   encoded_inputs["overflow_to_sample_mapping"]       )
         snake_case								= images

         return encoded_inputs





     def 		UpperCAmelCase(self				:   Dict    ,   _A				:   Dict    ,   _A				:   List[str]       )						->						Optional[int]:
         # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
         snake_case								= []
         for sample_idx in overflow_to_sample_mapping:
             images_with_overflow.append(images[sample_idx]       )

         if len(_A       ) != len(_A       ):
             raise ValueError(
                 "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"
                 f' {len(_A       )} and {len(_A       )}'       )

         return images_with_overflow





     def 		UpperCAmelCase(self				:   Tuple    ,   *_A				:   int    ,   **_A				:   Dict       )						->						str:
         return self.tokenizer.batch_decode(*_A    ,   **_A       )





     def 		UpperCAmelCase(self				:   str    ,   *_A				:   List[Any]    ,   **_A				:   List[Any]       )						->						Optional[Any]:
         return self.tokenizer.decode(*_A    ,   **_A       )





     @property
     def 		UpperCAmelCase(self				:   Tuple       )						->						Optional[int]:
         return ["input_ids", "bbox", "attention_mask", "image"]





     @property
     def 		UpperCAmelCase(self				:   List[Any]       )						->						int:
         warnings.warn(
             "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."    ,   _A    ,   )
         return self.image_processor_class





     @property
     def 		UpperCAmelCase(self				:   Dict       )						->						Union[str, Any]:
         warnings.warn(
             "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."    ,   _A    ,   )
         return self.image_processor

