





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        snake_case_    :






  def __init__(							self			:					str       ,  _snake_case			:					Optional[Any] = None      )->str:






   '''simple docstring'''

   __lowerCAmelCase					:	Optional[Any]      =       (
       os.path.join(_UpperCAmelCase       ,  config.EXTRACTED_DATASETS_DIR      ) if cache_dir else config.EXTRACTED_DATASETS_PATH
   )
   __lowerCAmelCase					:	Dict      =       Extractor






  def 				UpperCAmelCase__						(							self			:					Dict       ,  _snake_case			:					Optional[Any]      )->List[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"
   __lowerCAmelCase					:	List[str]      =       os.path.abspath(_UpperCAmelCase      )
   return os.path.join(self.extract_dir       ,  hash_url_to_filename(_UpperCAmelCase      )      )






  def 				UpperCAmelCase__						(							self			:					Dict       ,  _snake_case			:					Union[str, Any]       ,  _snake_case			:					List[str]      )->int:






   '''simple docstring'''

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






  def 				UpperCAmelCase__						(							self			:					Optional[int]       ,  _snake_case			:					List[str]       ,  _snake_case			:					Dict = False      )->int:






   '''simple docstring'''

   __lowerCAmelCase					:	Tuple      =       self.extractor.infer_extractor_format(_UpperCAmelCase      )
   if not extractor_format:
    return input_path
   __lowerCAmelCase					:	int      =       self._get_output_path(_UpperCAmelCase      )
   if self._do_extract(_UpperCAmelCase       ,  _UpperCAmelCase      ):
    self.extractor.extract(_UpperCAmelCase       ,  _UpperCAmelCase       ,  _UpperCAmelCase      )
   return output_path






class        snake_case_    (		_UpperCAmelCase						):






  @classmethod
  @abstractmethod
  def 				UpperCAmelCase__						(							cls			:					Union[str, Any]       ,  _snake_case			:					List[str]       ,  **_snake_case			:					Optional[Any]      )->Optional[Any]:






   '''simple docstring'''

   ...






  @staticmethod
  @abstractmethod
  def 				UpperCAmelCase__						(							_snake_case			:					Union[str, Any]       ,  _snake_case			:					Union[str, Any]      )->Optional[int]:






   '''simple docstring'''

   ...






class        snake_case_    (		_UpperCAmelCase					,_UpperCAmelCase						):
  A_      							=   []






  @staticmethod
  def 				UpperCAmelCase__						(							_snake_case			:					Optional[Any]       ,  _snake_case			:					int      )->List[Any]:






   '''simple docstring'''

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






  @classmethod
  def 				UpperCAmelCase__						(							cls			:					Any       ,  _snake_case			:					Any       ,  _snake_case			:					int = b""      )->List[str]:






   '''simple docstring'''

   if not magic_number:
    __lowerCAmelCase					:	Dict      =       max(len(_UpperCAmelCase      ) for cls_magic_number in cls.magic_numbers      )
    try:
     __lowerCAmelCase					:	Optional[int]      =       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        snake_case_    (		_UpperCAmelCase						):






  @classmethod
  def 				UpperCAmelCase__						(							cls			:					List[str]       ,  _snake_case			:					int       ,  **_snake_case			:					int      )->Any:






   '''simple docstring'''

   return tarfile.is_tarfile(_UpperCAmelCase      )






  @staticmethod
  def 				UpperCAmelCase__						(							_snake_case			:					Dict       ,  _snake_case			:					Any      )->List[Any]:






   '''simple docstring'''

   def resolved(_snake_case			:					Dict      ) -> str:
    return os.path.realpath(os.path.abspath(_UpperCAmelCase      )      )

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

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

   __lowerCAmelCase					:	int      =       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__						(							_snake_case			:					List[str]       ,  _snake_case			:					Optional[int]      )->Optional[int]:






   '''simple docstring'''

   os.makedirs(_UpperCAmelCase       ,  exist_ok=_UpperCAmelCase      )
   __lowerCAmelCase					:	str      =       tarfile.open(_UpperCAmelCase      )
   tar_file.extractall(_UpperCAmelCase       ,  members=TarExtractor.safemembers(_UpperCAmelCase       ,  _UpperCAmelCase      )      )
   tar_file.close()






class        snake_case_    (		_UpperCAmelCase						):
  A_      							=   [B"\x1F\x8B"]






  @staticmethod
  def 				UpperCAmelCase__						(							_snake_case			:					Union[str, Any]       ,  _snake_case			:					Optional[int]      )->Optional[Any]:






   '''simple docstring'''

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






class        snake_case_    (		_UpperCAmelCase						):
  A_      							=   [
      B"PK\x03\x04",
      B"PK\x05\x06",  # empty archive
      B"PK\x07\x08",  # spanned archive
  ]






  @classmethod
  def 				UpperCAmelCase__						(							cls			:					Tuple       ,  _snake_case			:					List[Any]       ,  _snake_case			:					List[Any] = b""      )->Optional[int]:






   '''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:
     __lowerCAmelCase					:	Union[str, Any]      =       _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					:	int      =       fp.read(_UpperCAmelCase      )  # CD is where we expect it to be
        if len(_UpperCAmelCase      ) == sizeCentralDir:
         __lowerCAmelCase					:	str      =       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__						(							_snake_case			:					int       ,  _snake_case			:					Tuple      )->List[Any]:






   '''simple docstring'''

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






class        snake_case_    (		_UpperCAmelCase						):
  A_      							=   [B"\xFD\x37\x7A\x58\x5A\x00"]






  @staticmethod
  def 				UpperCAmelCase__						(							_snake_case			:					Optional[int]       ,  _snake_case			:					Tuple      )->Optional[Any]:






   '''simple docstring'''

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






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






  @staticmethod
  def 				UpperCAmelCase__						(							_snake_case			:					Optional[int]       ,  _snake_case			:					str      )->Optional[int]:






   '''simple docstring'''

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

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






class        snake_case_    (		_UpperCAmelCase						):
  A_      							=   [B"\x28\xb5\x2F\xFD"]






  @staticmethod
  def 				UpperCAmelCase__						(							_snake_case			:					Any       ,  _snake_case			:					Dict      )->str:






   '''simple docstring'''

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

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






class        snake_case_    (		_UpperCAmelCase						):
  A_      							=   [B"\x42\x5A\x68"]






  @staticmethod
  def 				UpperCAmelCase__						(							_snake_case			:					Dict       ,  _snake_case			:					Dict      )->Tuple:






   '''simple docstring'''

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






class        snake_case_    (		_UpperCAmelCase						):
  A_      							=   [B"\x37\x7A\xBC\xAF\x27\x1C"]






  @staticmethod
  def 				UpperCAmelCase__						(							_snake_case			:					Optional[int]       ,  _snake_case			:					Tuple      )->Union[str, Any]:






   '''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        snake_case_    (		_UpperCAmelCase						):
  A_      							=   [B"\x04\x22\x4D\x18"]






  @staticmethod
  def 				UpperCAmelCase__						(							_snake_case			:					Any       ,  _snake_case			:					List[Any]      )->Optional[int]:






   '''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        snake_case_    :
  A_      							=   {
      "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			:					int      )->Any:






   '''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 				UpperCAmelCase__						(							_snake_case			:					List[Any]       ,  _snake_case			:					Dict      )->List[Any]:






   '''simple docstring'''

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






  @classmethod
  def 				UpperCAmelCase__						(							cls			:					Dict       ,  _snake_case			:					List[str]       ,  _snake_case			:					Dict = False      )->Tuple:






   '''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       ,  )
   __lowerCAmelCase					:	List[str]      =       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			:					Optional[Any]       ,  _snake_case			:					Optional[int]      )->List[str]:  # <Added version="2.4.0"/>






   '''simple docstring'''

   __lowerCAmelCase					:	int      =       cls._get_magic_number_max_length()
   __lowerCAmelCase					:	List[Any]      =       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			:					List[str]       ,  _snake_case			:					int       ,  _snake_case			:					Union[str, Any]       ,  _snake_case			:					Optional[Any] = None       ,  _snake_case			:					Dict = "deprecated"       ,  )->Dict:






   '''simple docstring'''

   os.makedirs(os.path.dirname(_UpperCAmelCase      )       ,  exist_ok=_UpperCAmelCase      )
   # Prevent parallel extractions
   __lowerCAmelCase					:	Optional[int]      =       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					:	int      =       extractor if extractor != '''deprecated''' else extractor_format
     else:
      __lowerCAmelCase					:	Union[str, Any]      =       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      )






import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding






class        snake_case_    (		__lowercase						):
  A_      							=   ['image_processor', 'tokenizer']
  A_      							=   'ChineseCLIPImageProcessor'
  A_      							=   ('BertTokenizer', 'BertTokenizerFast')






  def __init__(							self			:					Optional[Any]       ,  _snake_case			:					List[Any]=None       ,  _snake_case			:					str=None       ,  **_snake_case			:					int      )->List[str]:






   '''simple docstring'''

   __lowerCAmelCase					:	str      =       None
   if "feature_extractor" in kwargs:
    warnings.warn(
        """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
        """ instead."""       ,  _snake_case       ,  )
    __lowerCAmelCase					:	List[str]      =       kwargs.pop("""feature_extractor"""      )

   __lowerCAmelCase					:	Union[str, Any]      =       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__(_snake_case       ,  _snake_case      )
   __lowerCAmelCase					:	Any      =       self.image_processor






  def __call__(							self			:					Optional[Any]       ,  _snake_case			:					Tuple=None       ,  _snake_case			:					Tuple=None       ,  _snake_case			:					List[str]=None       ,  **_snake_case			:					Any      )->Union[str, Any]:






   '''simple docstring'''

   if text is None and images is None:
    raise ValueError("""You have to specify either text or images. Both cannot be none."""      )

   if text is not None:
    __lowerCAmelCase					:	List[Any]      =       self.tokenizer(_snake_case       ,  return_tensors=_snake_case       ,  **_snake_case      )

   if images is not None:
    __lowerCAmelCase					:	Tuple      =       self.image_processor(_snake_case       ,  return_tensors=_snake_case       ,  **_snake_case      )

   if text is not None and images is not None:
    __lowerCAmelCase					:	Optional[Any]      =       image_features.pixel_values
    return encoding
   elif text is not None:
    return encoding
   else:
    return BatchEncoding(data=dict(**_snake_case      )       ,  tensor_type=_snake_case      )






  def 				UpperCAmelCase__						(							self			:					Optional[int]       ,  *_snake_case			:					Union[str, Any]       ,  **_snake_case			:					int      )->Optional[Any]:






   '''simple docstring'''

   return self.tokenizer.batch_decode(*_snake_case       ,  **_snake_case      )






  def 				UpperCAmelCase__						(							self			:					Dict       ,  *_snake_case			:					Dict       ,  **_snake_case			:					Any      )->Dict:






   '''simple docstring'''

   return self.tokenizer.decode(*_snake_case       ,  **_snake_case      )






  @property
  def 				UpperCAmelCase__						(							self			:					Optional[int]      )->str:






   '''simple docstring'''

   __lowerCAmelCase					:	Tuple      =       self.tokenizer.model_input_names
   __lowerCAmelCase					:	Tuple      =       self.image_processor.model_input_names
   return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names      )      )






  @property
  def 				UpperCAmelCase__						(							self			:					Dict      )->Union[str, Any]:






   '''simple docstring'''

   warnings.warn(
       """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."""       ,  _snake_case       ,  )
   return self.image_processor_class