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


UpperCamelCase__     :	List[Any]				=			get_logger(__name__)


class 				_lowercase	:
      '''simple docstring'''


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



         '''simple docstring'''



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




      def 		lowerCAmelCase__					(				self					,lowerCamelCase_							)			->			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__							:				Any   				=  os.path.abspath(lowerCamelCase_							)
         return os.path.join(self.extract_dir					,hash_url_to_filename(lowerCamelCase_							)							)




      def 		lowerCAmelCase__					(				self					,lowerCamelCase_					,lowerCamelCase_							)			->			bool:



         '''simple docstring'''



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




      def 		lowerCAmelCase__					(				self					,lowerCamelCase_					,lowerCamelCase_ = False							)			->			str:



         '''simple docstring'''



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




class 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      @classmethod
      @abstractmethod
      def 		lowerCAmelCase__					(				cls					,lowerCamelCase_					,**lowerCamelCase_							)			->			bool:



         '''simple docstring'''



         ...




      @staticmethod
      @abstractmethod
      def 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			None:



         '''simple docstring'''



         ...




class 				_lowercase	(      lowerCAmelCase		,lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      List[bytes]      							=   []




      @staticmethod
      def 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			List[Any]:



         '''simple docstring'''



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




      @classmethod
      def 		lowerCAmelCase__					(				cls					,lowerCamelCase_					,lowerCamelCase_ = b""							)			->			bool:



         '''simple docstring'''



         if not magic_number:
            UpperCAmelCase__							:				Union[str, Any]   				=  max(len(lowerCamelCase_							) for cls_magic_number in cls.magic_numbers							)
            try:
               UpperCAmelCase__							:				Any   				=  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 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      @classmethod
      def 		lowerCAmelCase__					(				cls					,lowerCamelCase_					,**lowerCamelCase_							)			->			bool:



         '''simple docstring'''



         return tarfile.is_tarfile(lowerCamelCase_							)




      @staticmethod
      def 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			Any:



         '''simple docstring'''



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

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

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

         UpperCAmelCase__							:				Optional[Any]   				=  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 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			None:



         '''simple docstring'''



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




class 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      List[Any]      							=   [b'''\x1F\x8B''']




      @staticmethod
      def 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			None:



         '''simple docstring'''



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




class 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      Optional[Any]      							=   [
          b'''PK\x03\x04''',
          b'''PK\x05\x06''',  # empty archive
          b'''PK\x07\x08''',  # spanned archive
      ]




      @classmethod
      def 		lowerCAmelCase__					(				cls					,lowerCamelCase_					,lowerCamelCase_ = b""							)			->			bool:



         '''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:
               UpperCAmelCase__							:				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:
                        UpperCAmelCase__							:				Union[str, Any]   				=  fp.read(lowerCamelCase_							)  # CD is where we expect it to be
                        if len(lowerCamelCase_							) == sizeCentralDir:
                           UpperCAmelCase__							:				Dict   				=  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 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			None:



         '''simple docstring'''



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




class 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      Optional[int]      							=   [b'''\xFD\x37\x7A\x58\x5A\x00''']




      @staticmethod
      def 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			None:



         '''simple docstring'''



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




class 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      Optional[Any]      							=   [b'''Rar!\x1a\x07\x00''', b'''Rar!\x1a\x07\x01\x00''']  # RAR_ID  # RAR5_ID




      @staticmethod
      def 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			None:



         '''simple docstring'''



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

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




class 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      List[Any]      							=   [b'''\x28\xb5\x2F\xFD''']




      @staticmethod
      def 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			None:



         '''simple docstring'''



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

         UpperCAmelCase__							:				Union[str, Any]   				=  zstd.ZstdDecompressor()
         with open(lowerCamelCase_					,'''rb'''							) as ifh, open(lowerCamelCase_					,'''wb'''							) as ofh:
            dctx.copy_stream(lowerCamelCase_					,lowerCamelCase_							)




class 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      int      							=   [b'''\x42\x5A\x68''']




      @staticmethod
      def 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			None:



         '''simple docstring'''



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




class 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      Tuple      							=   [b'''\x37\x7A\xBC\xAF\x27\x1C''']




      @staticmethod
      def 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			None:



         '''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 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      Union[str, Any]      							=   [b'''\x04\x22\x4D\x18''']




      @staticmethod
      def 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			None:



         '''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 				_lowercase	:
      '''simple docstring'''


      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 		lowerCAmelCase__					(				cls							)			->			Optional[Any]:



         '''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 		lowerCAmelCase__					(				lowerCamelCase_					,lowerCamelCase_							)			->			Union[str, Any]:



         '''simple docstring'''



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




      @classmethod
      def 		lowerCAmelCase__					(				cls					,lowerCamelCase_					,lowerCamelCase_ = 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=lowerCamelCase_					,)
         UpperCAmelCase__							:				Union[str, Any]   				=  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 		lowerCAmelCase__					(				cls					,lowerCamelCase_							)			->			str:  # <Added version="2.4.0"/>



         '''simple docstring'''



         UpperCAmelCase__							:				Dict   				=  cls._get_magic_number_max_length()
         UpperCAmelCase__							:				Optional[Any]   				=  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 		lowerCAmelCase__					(				cls					,lowerCamelCase_					,lowerCamelCase_					,lowerCamelCase_ = None					,lowerCamelCase_ = "deprecated"					,)			->			None:



         '''simple docstring'''



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

import warnings

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


class 				_lowercase	(      lowerCAmelCase   ):
      '''simple docstring'''


      UpperCAmelCase_      :      Tuple      							=   ['''image_processor''', '''tokenizer''']
      UpperCAmelCase_      :      str      							=   '''CLIPImageProcessor'''
      UpperCAmelCase_      :      Dict      							=   ('''CLIPTokenizer''', '''CLIPTokenizerFast''')




      def __init__(				self					,lowerCamelCase_=None					,lowerCamelCase_=None					,**lowerCamelCase_							)			->			Any:



         '''simple docstring'''



         UpperCAmelCase__							:				Any   				=  None
         if "feature_extractor" in kwargs:
            warnings.warn(
                '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
                ''' instead.'''					,lowerCamelCase_					,)
            UpperCAmelCase__							:				str   				=  kwargs.pop('''feature_extractor'''							)

         UpperCAmelCase__							:				Optional[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__(lowerCamelCase_					,lowerCamelCase_							)




      def __call__(				self					,lowerCamelCase_=None					,lowerCamelCase_=None					,lowerCamelCase_=None					,**lowerCamelCase_							)			->			Dict:



         '''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:
            UpperCAmelCase__							:				Tuple   				=  self.tokenizer(lowerCamelCase_					,return_tensors=lowerCamelCase_					,**lowerCamelCase_							)

         if images is not None:
            UpperCAmelCase__							:				Optional[int]   				=  self.image_processor(lowerCamelCase_					,return_tensors=lowerCamelCase_					,**lowerCamelCase_							)

         if text is not None and images is not None:
            UpperCAmelCase__							:				str   				=  image_features.pixel_values
            return encoding
         elif text is not None:
            return encoding
         else:
            return BatchEncoding(data=dict(**lowerCamelCase_							)					,tensor_type=lowerCamelCase_							)




      def 		lowerCAmelCase__					(				self					,*lowerCamelCase_					,**lowerCamelCase_							)			->			Tuple:



         '''simple docstring'''



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




      def 		lowerCAmelCase__					(				self					,*lowerCamelCase_					,**lowerCamelCase_							)			->			Tuple:



         '''simple docstring'''



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




      @property
      def 		lowerCAmelCase__					(				self							)			->			List[str]:



         '''simple docstring'''



         UpperCAmelCase__							:				Optional[Any]   				=  self.tokenizer.model_input_names
         UpperCAmelCase__							:				Optional[Any]   				=  self.image_processor.model_input_names
         return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names							)							)




      @property
      def 		lowerCAmelCase__					(				self							)			->			List[Any]:



         '''simple docstring'''



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




      @property
      def 		lowerCAmelCase__					(				self							)			->			List[str]:



         '''simple docstring'''



         warnings.warn(
             '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''					,lowerCamelCase_					,)
         return self.image_processor




