




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




class 			UpperCAmelCase_      :




							'''simple docstring'''



							def __init__(					self       :	str       ,     a       :	Optional[str] = None			)			->					Dict:
										SCREAMING_SNAKE_CASE           =					(
										    os.path.join(a       ,     config.EXTRACTED_DATASETS_DIR			) if cache_dir else config.EXTRACTED_DATASETS_PATH
										)
										SCREAMING_SNAKE_CASE           =					Extractor





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





							def    _UpperCAmelCase     (					self       :	Dict       ,     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       :	Dict       ,     a       :	str       ,     a       :	bool = False			)			->					str:
										SCREAMING_SNAKE_CASE           =					self.extractor.infer_extractor_format(a			)
										if not extractor_format:
													return input_path
										SCREAMING_SNAKE_CASE           =					self._get_output_path(a			)
										if self._do_extract(a       ,     a			):
													self.extractor.extract(a       ,     a       ,     a			)
										return output_path





class 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							@classmethod
							@abstractmethod
							def    _UpperCAmelCase     (					cls       :	Dict       ,     a       :	Union[Path, str]       ,     **a       :	int			)			->					bool:
										...







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





class 			UpperCAmelCase_      (   A		,      A       ):




							'''simple docstring'''



							a__						  =     []





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







							@classmethod
							def    _UpperCAmelCase     (					cls       :	Tuple       ,     a       :	Union[Path, str]       ,     a       :	bytes = b""			)			->					bool:
										if not magic_number:
													SCREAMING_SNAKE_CASE           =					max(len(a			) for cls_magic_number in cls.magic_numbers			)
													try:
																SCREAMING_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 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							@classmethod
							def    _UpperCAmelCase     (					cls       :	List[Any]       ,     a       :	Union[Path, str]       ,     **a       :	List[Any]			)			->					bool:
										return tarfile.is_tarfile(a			)





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

										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       :	Any       ,     a       :	str			) -> bool:
													# Links are interpreted relative to the directory containing the link
													SCREAMING_SNAKE_CASE           =					resolved(os.path.join(a       ,     os.path.dirname(info.name			)			)			)
													return badpath(info.linkname       ,     base=a			)

										SCREAMING_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			)
										SCREAMING_SNAKE_CASE           =					tarfile.open(a			)
										tar_file.extractall(a       ,     members=TarExtractor.safemembers(a       ,     a			)			)
										tar_file.close()





class 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     [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 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     [
							    B'''PK\x03\x04''',
							    B'''PK\x05\x06''',  # empty archive
							    B'''PK\x07\x08''',  # spanned archive
							]





							@classmethod
							def    _UpperCAmelCase     (					cls       :	str       ,     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:
																SCREAMING_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:
																									SCREAMING_SNAKE_CASE           =					fp.read(a			)  # CD is where we expect it to be
																									if len(a			) == sizeCentralDir:
																												SCREAMING_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 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     [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 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     [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			)
										SCREAMING_SNAKE_CASE           =					rarfile.RarFile(a			)
										rf.extractall(a			)
										rf.close()





class 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     [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

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





class 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     [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 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     [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 			UpperCAmelCase_      (   A       ):




							'''simple docstring'''



							a__						  =     [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 			UpperCAmelCase_      :




							'''simple docstring'''



							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       :	str			)			->					List[Any]:
										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			)			->					List[str]:
										try:
													return MagicNumberBaseExtractor.read_magic_number(a       ,     magic_number_length=a			)
										except OSError:
													return b""





							@classmethod
							def    _UpperCAmelCase     (					cls       :	Tuple       ,     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       ,     )
										SCREAMING_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       :	int       ,     a       :	Union[Path, str]			)			->					str:  # <Added version="2.4.0"/>
										SCREAMING_SNAKE_CASE           =					cls._get_magic_number_max_length()
										SCREAMING_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       :	List[str]       ,     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
										SCREAMING_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       ,     )
																			SCREAMING_SNAKE_CASE           =					extractor if extractor != """deprecated""" else extractor_format
																else:
																			SCREAMING_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 argparse

from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt


if __name__ == "__main__":
		__A						:							Tuple							=  argparse.ArgumentParser()

		parser.add_argument(
		    """--checkpoint_path""", default=None, type=str, required=True, help="""Path to the checkpoint to convert."""
		)
		parser.add_argument(
		    """--original_config_file""",
		    type=str,
		    required=True,
		    help="""The YAML config file corresponding to the original architecture.""",
		)
		parser.add_argument(
		    """--num_in_channels""",
		    default=None,
		    type=int,
		    help="""The number of input channels. If `None` number of input channels will be automatically inferred.""",
		)
		parser.add_argument(
		    """--image_size""",
		    default=5_1_2,
		    type=int,
		    help=(
		        """The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2"""
		        """ Base. Use 768 for Stable Diffusion v2."""
		    ),
		)
		parser.add_argument(
		    """--extract_ema""",
		    action="""store_true""",
		    help=(
		        """Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights"""
		        """ or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield"""
		        """ higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning."""
		    ),
		)
		parser.add_argument(
		    """--upcast_attention""",
		    action="""store_true""",
		    help=(
		        """Whether the attention computation should always be upcasted. This is necessary when running stable"""
		        """ diffusion 2.1."""
		    ),
		)
		parser.add_argument(
		    """--from_safetensors""",
		    action="""store_true""",
		    help="""If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.""",
		)
		parser.add_argument(
		    """--to_safetensors""",
		    action="""store_true""",
		    help="""Whether to store pipeline in safetensors format or not.""",
		)
		parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""")
		parser.add_argument("""--device""", type=str, help="""Device to use (e.g. cpu, cuda:0, cuda:1, etc.)""")
		def 					lowerCamelCase_    (    SCREAMING_SNAKE_CASE   ):
					'''simple docstring'''
					if string == "True":
								return True
					elif string == "False":
								return False
					else:
								raise ValueError(f"""could not parse string as bool {string}"""   )

		parser.add_argument(
		    """--use_linear_projection""", help="""Override for use linear projection""", required=False, type=parse_bool
		)

		parser.add_argument("""--cross_attention_dim""", help="""Override for cross attention_dim""", required=False, type=int)

		__A						:							Union[str, Any]							=  parser.parse_args()

		__A						:							Any							=  download_controlnet_from_original_ckpt(
		    checkpoint_path=args.checkpoint_path,
		    original_config_file=args.original_config_file,
		    image_size=args.image_size,
		    extract_ema=args.extract_ema,
		    num_in_channels=args.num_in_channels,
		    upcast_attention=args.upcast_attention,
		    from_safetensors=args.from_safetensors,
		    device=args.device,
		    use_linear_projection=args.use_linear_projection,
		    cross_attention_dim=args.cross_attention_dim,
		)




		controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)






