






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


     def __init__(					self							:						Optional[Any]       ,			UpperCAmelCase_							:						Optional[str] = None   ):
       SCREAMING_SNAKE_CASE							:   List[str]						    =     (
           os.path.join(UpperCAmelCase_       ,			config.EXTRACTED_DATASETS_DIR   ) if cache_dir else config.EXTRACTED_DATASETS_PATH
       )
       SCREAMING_SNAKE_CASE							:   int						    =     Extractor


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


     def 					_A							(					self							:						List[str]       ,			UpperCAmelCase_							:						str       ,			UpperCAmelCase_							:						bool   ):
       return force_extract or (
           not os.path.isfile(UpperCAmelCase_   ) and not (os.path.isdir(UpperCAmelCase_   ) and os.listdir(UpperCAmelCase_   ))
       )






     def 					_A							(					self							:						Optional[int]       ,			UpperCAmelCase_							:						str       ,			UpperCAmelCase_							:						bool = False   ):
       SCREAMING_SNAKE_CASE							:   Union[str, Any]						    =     self.extractor.infer_extractor_format(UpperCAmelCase_   )
       if not extractor_format:
         return input_path
       SCREAMING_SNAKE_CASE							:   Optional[Any]						    =     self._get_output_path(UpperCAmelCase_   )
       if self._do_extract(UpperCAmelCase_       ,			UpperCAmelCase_   ):
         self.extractor.extract(UpperCAmelCase_       ,			UpperCAmelCase_       ,			UpperCAmelCase_   )
       return output_path





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


     @classmethod
     @abstractmethod
     def 					_A							(					cls							:						Any       ,			UpperCAmelCase_							:						Union[Path, str]       ,			**UpperCAmelCase_							:						str   ):
       ...






     @staticmethod
     @abstractmethod
     def 					_A							(					UpperCAmelCase_							:						Union[Path, str]       ,			UpperCAmelCase_							:						Union[Path, str]   ):
       ...





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


     UpperCamelCase_				:		List[bytes]								=						[]


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






     @classmethod
     def 					_A							(					cls							:						str       ,			UpperCAmelCase_							:						Union[Path, str]       ,			UpperCAmelCase_							:						bytes = b""   ):
       if not magic_number:
         SCREAMING_SNAKE_CASE							:   List[str]						    =     max(len(UpperCAmelCase_   ) for cls_magic_number in cls.magic_numbers   )
         try:
           SCREAMING_SNAKE_CASE							:   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 			SCREAMING_SNAKE_CASE      (      lowerCAmelCase       ):
     '''simple docstring'''


     @classmethod
     def 					_A							(					cls							:						Dict       ,			UpperCAmelCase_							:						Union[Path, str]       ,			**UpperCAmelCase_							:						Any   ):
       return tarfile.is_tarfile(UpperCAmelCase_   )


     @staticmethod
     def 					_A							(					UpperCAmelCase_							:						Optional[Any]       ,			UpperCAmelCase_							:						Tuple   ):

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

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

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

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





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


     UpperCamelCase_				:		Optional[Any]								=						[b'''\x1F\x8B''']


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





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


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


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





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


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


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





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


     UpperCamelCase_				:		Union[str, Any]								=						[b'''Rar!\x1a\x07\x00''', b'''Rar!\x1a\x07\x01\x00''']  # RAR_ID  # RAR5_ID


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

       os.makedirs(UpperCAmelCase_       ,			exist_ok=UpperCAmelCase_   )
       SCREAMING_SNAKE_CASE							:   int						    =     rarfile.RarFile(UpperCAmelCase_   )
       rf.extractall(UpperCAmelCase_   )
       rf.close()





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


     UpperCamelCase_				:		str								=						[b'''\x28\xb5\x2F\xFD''']


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

       SCREAMING_SNAKE_CASE							:   Dict						    =     zstd.ZstdDecompressor()
       with open(UpperCAmelCase_       ,			"rb"   ) as ifh, open(UpperCAmelCase_       ,			"wb"   ) as ofh:
         dctx.copy_stream(UpperCAmelCase_       ,			UpperCAmelCase_   )





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


     UpperCamelCase_				:		Optional[Any]								=						[b'''\x42\x5A\x68''']


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





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


     UpperCamelCase_				:		Union[str, Any]								=						[b'''\x37\x7A\xBC\xAF\x27\x1C''']


     @staticmethod
     def 					_A							(					UpperCAmelCase_							:						Union[Path, str]       ,			UpperCAmelCase_							:						Union[Path, str]   ):
       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 			SCREAMING_SNAKE_CASE      (      lowerCAmelCase       ):
     '''simple docstring'''


     UpperCamelCase_				:		Tuple								=						[b'''\x04\x22\x4D\x18''']


     @staticmethod
     def 					_A							(					UpperCAmelCase_							:						Union[Path, str]       ,			UpperCAmelCase_							:						Union[Path, str]   ):
       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 			SCREAMING_SNAKE_CASE      :
     '''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 					_A							(					cls							:						Optional[Any]   ):
       return max(
           len(UpperCAmelCase_   )
           for extractor in cls.extractors.values()
           if issubclass(UpperCAmelCase_       ,			UpperCAmelCase_   )
           for extractor_magic_number in extractor.magic_numbers   )


     @staticmethod
     def 					_A							(					UpperCAmelCase_							:						Union[Path, str]       ,			UpperCAmelCase_							:						int   ):
       try:
         return MagicNumberBaseExtractor.read_magic_number(UpperCAmelCase_       ,			magic_number_length=UpperCAmelCase_   )
       except OSError:
         return b""


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













'''simple docstring'''

from ...utils import (
    OptionalDependencyNotAvailable,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)


try:
  if not (is_transformers_available() and is_torch_available()):
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline
else:
  from .pipeline_kandinsky import KandinskyPipeline
  from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline
  from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline
  from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput
  from .text_encoder import MultilingualCLIP



