






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[str]     						=						get_logger(__name__)


class        __UpperCamelCase    :







	def __init__(  self      :							List[str]       ,				_lowerCAmelCase      :							Optional[str] = None			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  (
		    os.path.join(_lowerCAmelCase       ,				config.EXTRACTED_DATASETS_DIR			) if cache_dir else config.EXTRACTED_DATASETS_PATH
		)
		__lowercase             =  Extractor







	def  _a   (  self      :							str       ,				_lowerCAmelCase      :							str			)		-> 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"
		__lowercase             =  os.path.abspath(_lowerCAmelCase			)
		return os.path.join(self.extract_dir       ,				hash_url_to_filename(_lowerCAmelCase			)			)







	def  _a   (  self      :							Optional[Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							bool			)		-> bool:
		"""simple docstring"""







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







	def  _a   (  self      :							List[Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							bool = False			)		-> str:
		"""simple docstring"""







		__lowercase             =  self.extractor.infer_extractor_format(_lowerCAmelCase			)
		if not extractor_format:
			return input_path
		__lowercase             =  self._get_output_path(_lowerCAmelCase			)
		if self._do_extract(_lowerCAmelCase       ,				_lowerCAmelCase			):
			self.extractor.extract(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
		return output_path


class        __UpperCamelCase    (     _lowerCAmelCase   ):







	@classmethod
	@abstractmethod
	def  _a   (  cls      :							List[str]       ,				_lowerCAmelCase      :							Union[Path, str]       ,				**_lowerCAmelCase      :							str			)		-> bool:
		"""simple docstring"""







		...







	@staticmethod
	@abstractmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> None:
		"""simple docstring"""







		...


class        __UpperCamelCase    (     _lowerCAmelCase   ,			_lowerCAmelCase   ):
	__snake_case	:List[bytes]   =       []







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							int			)		-> List[Any]:
		"""simple docstring"""







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







	@classmethod
	def  _a   (  cls      :							Any       ,				_lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							bytes = b""			)		-> bool:
		"""simple docstring"""







		if not magic_number:
			__lowercase             =  max(len(_lowerCAmelCase			) for cls_magic_number in cls.magic_numbers			)
			try:
				__lowercase             =  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        __UpperCamelCase    (     _lowerCAmelCase   ):







	@classmethod
	def  _a   (  cls      :							Dict       ,				_lowerCAmelCase      :							Union[Path, str]       ,				**_lowerCAmelCase      :							str			)		-> bool:
		"""simple docstring"""







		return tarfile.is_tarfile(_lowerCAmelCase			)







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							Optional[Any]			)		-> List[str]:
		"""simple docstring"""







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

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

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

		__lowercase             =  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  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> None:
		"""simple docstring"""







		os.makedirs(_lowerCAmelCase       ,				exist_ok=_lowerCAmelCase			)
		__lowercase             =  tarfile.open(_lowerCAmelCase			)
		tar_file.extractall(_lowerCAmelCase       ,				members=TarExtractor.safemembers(_lowerCAmelCase       ,				_lowerCAmelCase			)			)
		tar_file.close()


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:List[Any]   =       [B'\x1F\x8B']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> None:
		"""simple docstring"""







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


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Dict   =       [
	    B'PK\x03\x04',
	    B'PK\x05\x06',  # empty archive
	    B'PK\x07\x08',  # spanned archive
	]







	@classmethod
	def  _a   (  cls      :							Optional[Any]       ,				_lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							bytes = 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:
				__lowercase             =  _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:
							__lowercase             =  fp.read(_lowerCAmelCase			)  # CD is where we expect it to be
							if len(_lowerCAmelCase			) == sizeCentralDir:
								__lowercase             =  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  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> 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        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Tuple   =       [B'\xFD\x37\x7A\x58\x5A\x00']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> None:
		"""simple docstring"""







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


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Union[str, Any]   =       [B'Rar!\x1a\x07\x00', B'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> None:
		"""simple docstring"""







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

		os.makedirs(_lowerCAmelCase       ,				exist_ok=_lowerCAmelCase			)
		__lowercase             =  rarfile.RarFile(_lowerCAmelCase			)
		rf.extractall(_lowerCAmelCase			)
		rf.close()


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Dict   =       [B'\x28\xb5\x2F\xFD']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> None:
		"""simple docstring"""







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

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


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:List[Any]   =       [B'\x42\x5A\x68']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> None:
		"""simple docstring"""







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


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Any   =       [B'\x37\x7A\xBC\xAF\x27\x1C']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> 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        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Tuple   =       [B'\x04\x22\x4D\x18']







	@staticmethod
	def  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> 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        __UpperCamelCase    :
	#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
	__snake_case	: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      :							Union[str, Any]			)		-> Union[str, 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  _a   (  _lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							int			)		-> Dict:
		"""simple docstring"""







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







	@classmethod
	def  _a   (  cls      :							str       ,				_lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							bool = 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       ,				)
		__lowercase             =  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  _a   (  cls      :							Optional[int]       ,				_lowerCAmelCase      :							Union[Path, str]			)		-> str:  # <Added version="2.4.0"/>
		"""simple docstring"""







		__lowercase             =  cls._get_magic_number_max_length()
		__lowercase             =  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  _a   (  cls      :							List[str]       ,				_lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Union[Path, str]       ,				_lowerCAmelCase      :							Optional[str] = None       ,				_lowerCAmelCase      :							Optional[BaseExtractor] = "deprecated"       ,				)		-> None:
		"""simple docstring"""







		os.makedirs(os.path.dirname(_lowerCAmelCase			)       ,				exist_ok=_lowerCAmelCase			)
		# Prevent parallel extractions
		__lowercase             =  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       ,				)
					__lowercase             =  extractor if extractor != """deprecated""" else extractor_format
				else:
					__lowercase             =  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			)









import random
import unittest

import torch

from diffusers import IFInpaintingPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin


@skip_mps
class        __UpperCamelCase    (     _lowerCAmelCase   ,			_lowerCAmelCase   ,			unittest.TestCase   ):
	__snake_case	:Any   =       IFInpaintingPipeline
	__snake_case	:str   =       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'}
	__snake_case	:Optional[int]   =       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
	__snake_case	:str   =       PipelineTesterMixin.required_optional_params - {'latents'}







	def  _a   (  self      :							Union[str, Any]			)		-> Tuple:
		"""simple docstring"""







		return self._get_dummy_components()







	def  _a   (  self      :							Optional[int]       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Dict=0			)		-> Any:
		"""simple docstring"""







		if str(_lowerCAmelCase			).startswith("""mps"""			):
			__lowercase             =  torch.manual_seed(_lowerCAmelCase			)
		else:
			__lowercase             =  torch.Generator(device=_lowerCAmelCase			).manual_seed(_lowerCAmelCase			)

		__lowercase             =  floats_tensor((1, 3, 32, 32)       ,				rng=random.Random(_lowerCAmelCase			)			).to(_lowerCAmelCase			)
		__lowercase             =  floats_tensor((1, 3, 32, 32)       ,				rng=random.Random(_lowerCAmelCase			)			).to(_lowerCAmelCase			)

		__lowercase             =  {
		    """prompt""": """A painting of a squirrel eating a burger""",
		    """image""": image,
		    """mask_image""": mask_image,
		    """generator""": generator,
		    """num_inference_steps""": 2,
		    """output_type""": """numpy""",
		}

		return inputs







	@unittest.skipIf(
	    torch_device != """cuda""" or not is_xformers_available()       ,				reason="""XFormers attention is only available with CUDA and `xformers` installed"""       ,				)
	def  _a   (  self      :							Tuple			)		-> Dict:
		"""simple docstring"""







		self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3			)







	def  _a   (  self      :							Union[str, Any]			)		-> Dict:
		"""simple docstring"""







		self._test_save_load_optional_components()







	@unittest.skipIf(torch_device != """cuda"""       ,				reason="""float16 requires CUDA"""			)
	def  _a   (  self      :							List[str]			)		-> Tuple:
		"""simple docstring"""







		super().test_save_load_floataa(expected_max_diff=1e-1			)







	def  _a   (  self      :							Tuple			)		-> Optional[Any]:
		"""simple docstring"""







		self._test_attention_slicing_forward_pass(expected_max_diff=1e-2			)







	def  _a   (  self      :							str			)		-> Optional[int]:
		"""simple docstring"""







		self._test_save_load_local()







	def  _a   (  self      :							List[str]			)		-> List[Any]:
		"""simple docstring"""







		self._test_inference_batch_single_identical(
		    expected_max_diff=1e-2       ,				)

