



'''simple docstring'''





import argparse

import torch

from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt


if __name__ == "__main__":
 SCREAMING_SNAKE_CASE__          =  argparse.ArgumentParser()

 parser.add_argument(
     "--checkpoint_path", default=None, type=str, required=True, help="Path to the checkpoint to convert."
 )
 # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml
 parser.add_argument(
     "--original_config_file",
     default=None,
     type=str,
     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(
     "--scheduler_type",
     default="pndm",
     type=str,
     help="Type of scheduler to use. Should be one of ['pndm', 'lms', 'ddim', 'euler', 'euler-ancestral', 'dpm']",
 )
 parser.add_argument(
     "--pipeline_type",
     default=None,
     type=str,
     help=(
         "The pipeline type. One of 'FrozenOpenCLIPEmbedder', 'FrozenCLIPEmbedder', 'PaintByExample'"
         ". If `None` pipeline will be automatically inferred."
     ),
 )
 parser.add_argument(
     "--image_size",
     default=None,
     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(
     "--prediction_type",
     default=None,
     type=str,
     help=(
         "The prediction type that the model was trained on. Use 'epsilon' for Stable Diffusion v1.X and Stable"
         " Diffusion v2 Base. Use 'v_prediction' 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.)")
 parser.add_argument(
     "--stable_unclip",
     type=str,
     default=None,
     required=False,
     help="Set if this is a stable unCLIP model. One of 'txt2img' or 'img2img'.",
 )
 parser.add_argument(
     "--stable_unclip_prior",
     type=str,
     default=None,
     required=False,
     help="Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.",
 )
 parser.add_argument(
     "--clip_stats_path",
     type=str,
     help="Path to the clip stats file. Only required if the stable unclip model's config specifies `model.params.noise_aug_config.params.clip_stats_path`.",
     required=False,
 )
 parser.add_argument(
     "--controlnet", action="store_true", default=None, help="Set flag if this is a controlnet checkpoint."
 )
 parser.add_argument("--half", action="store_true", help="Save weights in half precision.")
 parser.add_argument(
     "--vae_path",
     type=str,
     default=None,
     required=False,
     help="Set to a path, hub id to an already converted vae to not convert it again.",
 )
 SCREAMING_SNAKE_CASE__          =  parser.parse_args()

 SCREAMING_SNAKE_CASE__          =  download_from_original_stable_diffusion_ckpt(
     checkpoint_path=args.checkpoint_path,
     original_config_file=args.original_config_file,
     image_size=args.image_size,
     prediction_type=args.prediction_type,
     model_type=args.pipeline_type,
     extract_ema=args.extract_ema,
     scheduler_type=args.scheduler_type,
     num_in_channels=args.num_in_channels,
     upcast_attention=args.upcast_attention,
     from_safetensors=args.from_safetensors,
     device=args.device,
     stable_unclip=args.stable_unclip,
     stable_unclip_prior=args.stable_unclip_prior,
     clip_stats_path=args.clip_stats_path,
     controlnet=args.controlnet,
     vae_path=args.vae_path,
 )

 if args.half:
  pipe.to(torch_dtype=torch.floataa)

 if args.controlnet:
  # only save the controlnet model
  pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
 else:
  pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)









'''simple docstring'''





import logging
import os
import threading
import time


try:
 import warnings
except ImportError:
 SCREAMING_SNAKE_CASE__          =  None

try:
 import msvcrt
except ImportError:
 SCREAMING_SNAKE_CASE__          =  None

try:
 import fcntl
except ImportError:
 SCREAMING_SNAKE_CASE__          =  None


# Backward compatibility
# ------------------------------------------------
try:
 TimeoutError
except NameError:
 SCREAMING_SNAKE_CASE__          =  OSError


# Data
# ------------------------------------------------
SCREAMING_SNAKE_CASE__          =  [
    "Timeout",
    "BaseFileLock",
    "WindowsFileLock",
    "UnixFileLock",
    "SoftFileLock",
    "FileLock",
]

SCREAMING_SNAKE_CASE__          =  "3.0.12"


SCREAMING_SNAKE_CASE__          =  None




def 							lowerCamelCase	(					):





    '''simple docstring'''


    global _logger
    lowercase__									=    _logger or logging.getLogger(__name__							)
    return _logger


class 					snake_case			(UpperCamelCase ):



       def __init__(					self  ,UpperCAmelCase_   )	->				int:
           lowercase__									=    lock_file
           return None







       def __str__(					self   )	->				Union[str, Any]:
           lowercase__									=    F'''The file lock \'{self.lock_file}\' could not be acquired.'''
           return temp





class 					snake_case			:



       def __init__(					self  ,UpperCAmelCase_   )	->				List[Any]:
           lowercase__									=    lock
           return None



       def __enter__(					self   )	->				Optional[int]:
           return self.lock







       def __exit__(					self  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_   )	->				int:
           self.lock.release()
           return None





class 					snake_case			:



       def __init__(					self  ,UpperCAmelCase_  ,UpperCAmelCase_=-1  ,UpperCAmelCase_=None   )	->				Tuple:
           lowercase__									=    max_filename_length if max_filename_length is not None else 255
           # Hash the filename if it's too long
           lowercase__									=    self.hash_filename_if_too_long(UpperCAmelCase_  ,UpperCAmelCase_   )
           # The path to the lock file.
           lowercase__									=    lock_file

           # The file descriptor for the *_lock_file* as it is returned by the
           # os.open() function.
           # This file lock is only NOT None, if the object currently holds the
           # lock.
           lowercase__									=    None

           # The default timeout value.
           lowercase__									=    timeout

           # We use this lock primarily for the lock counter.
           lowercase__									=    threading.Lock()

           # The lock counter is used for implementing the nested locking
           # mechanism. Whenever the lock is acquired, the counter is increased and
           # the lock is only released, when this value is 0 again.
           lowercase__									=    0
           return None



       @property
       def 				_a   (					self   )	->				List[str]:
           return self._lock_file



       @property
       def 				_a   (					self   )	->				Optional[int]:
           return self._timeout



       @timeout.setter
       def 				_a   (					self  ,UpperCAmelCase_   )	->				Optional[Any]:
           lowercase__									=    float(UpperCAmelCase_   )
           return None



       def 				_a   (					self   )	->				Optional[Any]:
           raise NotImplementedError()



       def 				_a   (					self   )	->				Optional[int]:
           raise NotImplementedError()



       @property
       def 				_a   (					self   )	->				Dict:
           return self._lock_file_fd is not None



       def 				_a   (					self  ,UpperCAmelCase_=None  ,UpperCAmelCase_=0.05   )	->				Optional[Any]:
           # Use the default timeout, if no timeout is provided.
           if timeout is None:
               lowercase__									=    self.timeout

           # Increment the number right at the beginning.
           # We can still undo it, if something fails.
           with self._thread_lock:
               self._lock_counter += 1

           lowercase__									=    id(self   )
           lowercase__									=    self._lock_file
           lowercase__									=    time.time()
           try:
               while True:
                   with self._thread_lock:
                       if not self.is_locked:
                           logger().debug(F'''Attempting to acquire lock {lock_id} on {lock_filename}'''   )
                           self._acquire()

                   if self.is_locked:
                       logger().debug(F'''Lock {lock_id} acquired on {lock_filename}'''   )
                       break
                   elif timeout >= 0 and time.time() - start_time > timeout:
                       logger().debug(F'''Timeout on acquiring lock {lock_id} on {lock_filename}'''   )
                       raise Timeout(self._lock_file   )
                   else:
                       logger().debug(
                           F'''Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...'''   )
                       time.sleep(UpperCAmelCase_   )
           except:  # noqa
               # Something did go wrong, so decrement the counter.
               with self._thread_lock:
                   lowercase__									=    max(0  ,self._lock_counter - 1   )

               raise
           return _Acquire_ReturnProxy(lock=self   )



       def 				_a   (					self  ,UpperCAmelCase_=False   )	->				List[Any]:
           with self._thread_lock:
               if self.is_locked:
                   self._lock_counter -= 1

                   if self._lock_counter == 0 or force:
                       lowercase__									=    id(self   )
                       lowercase__									=    self._lock_file

                       logger().debug(F'''Attempting to release lock {lock_id} on {lock_filename}'''   )
                       self._release()
                       lowercase__									=    0
                       logger().debug(F'''Lock {lock_id} released on {lock_filename}'''   )

           return None



       def __enter__(					self   )	->				Dict:
           self.acquire()
           return self



       def __exit__(					self  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_   )	->				int:
           self.release()
           return None



       def __del__(					self   )	->				Union[str, Any]:
           self.release(force=UpperCAmelCase_   )
           return None







       def 				_a   (					self  ,UpperCAmelCase_  ,UpperCAmelCase_   )	->				str:
           lowercase__									=    os.path.basename(UpperCAmelCase_   )
           if len(UpperCAmelCase_   ) > max_length and max_length > 0:
               lowercase__									=    os.path.dirname(UpperCAmelCase_   )
               lowercase__									=    str(hash(UpperCAmelCase_   )   )
               lowercase__									=    filename[: max_length - len(UpperCAmelCase_   ) - 8] + "..." + hashed_filename + ".lock"
               return os.path.join(UpperCAmelCase_  ,UpperCAmelCase_   )
           else:
               return path





class 					snake_case			(UpperCamelCase ):



       def __init__(					self  ,UpperCAmelCase_  ,UpperCAmelCase_=-1  ,UpperCAmelCase_=None   )	->				Dict:
           from .file_utils import relative_to_absolute_path

           super().__init__(UpperCAmelCase_  ,timeout=UpperCAmelCase_  ,max_filename_length=UpperCAmelCase_   )
           lowercase__									=    "\\\\?\\" + relative_to_absolute_path(self.lock_file   )



       def 				_a   (					self   )	->				List[str]:
           lowercase__									=    os.O_RDWR | os.O_CREAT | os.O_TRUNC

           try:
               lowercase__									=    os.open(self._lock_file  ,UpperCAmelCase_   )
           except OSError:
               pass
           else:
               try:
                   msvcrt.locking(UpperCAmelCase_  ,msvcrt.LK_NBLCK  ,1   )
               except OSError:
                   os.close(UpperCAmelCase_   )
               else:
                   lowercase__									=    fd
           return None







       def 				_a   (					self   )	->				Any:
           lowercase__									=    self._lock_file_fd
           lowercase__									=    None
           msvcrt.locking(UpperCAmelCase_  ,msvcrt.LK_UNLCK  ,1   )
           os.close(UpperCAmelCase_   )

           try:
               os.remove(self._lock_file   )
           # Probably another instance of the application
           # that acquired the file lock.
           except OSError:
               pass
           return None





class 					snake_case			(UpperCamelCase ):



       def __init__(					self  ,UpperCAmelCase_  ,UpperCAmelCase_=-1  ,UpperCAmelCase_=None   )	->				int:
           lowercase__									=    os.statvfs(os.path.dirname(UpperCAmelCase_   )   ).f_namemax
           super().__init__(UpperCAmelCase_  ,timeout=UpperCAmelCase_  ,max_filename_length=UpperCAmelCase_   )



       def 				_a   (					self   )	->				List[str]:
           lowercase__									=    os.O_RDWR | os.O_CREAT | os.O_TRUNC
           lowercase__									=    os.open(self._lock_file  ,UpperCAmelCase_   )

           try:
               fcntl.flock(UpperCAmelCase_  ,fcntl.LOCK_EX | fcntl.LOCK_NB   )
           except OSError:
               os.close(UpperCAmelCase_   )
           else:
               lowercase__									=    fd
           return None







       def 				_a   (					self   )	->				int:
           # Do not remove the lockfile:
           #
           #   https://github.com/benediktschmitt/py-filelock/issues/31
           #   https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
           lowercase__									=    self._lock_file_fd
           lowercase__									=    None
           fcntl.flock(UpperCAmelCase_  ,fcntl.LOCK_UN   )
           os.close(UpperCAmelCase_   )
           return None





class 					snake_case			(UpperCamelCase ):



       def 				_a   (					self   )	->				Optional[Any]:
           lowercase__									=    os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
           try:
               lowercase__									=    os.open(self._lock_file  ,UpperCAmelCase_   )
           except OSError:
               pass
           else:
               lowercase__									=    fd
           return None







       def 				_a   (					self   )	->				Tuple:
           os.close(self._lock_file_fd   )
           lowercase__									=    None

           try:
               os.remove(self._lock_file   )
           # The file is already deleted and that's what we want.
           except OSError:
               pass
           return None





SCREAMING_SNAKE_CASE__          =  None

if msvcrt:
 SCREAMING_SNAKE_CASE__          =  WindowsFileLock
elif fcntl:
 SCREAMING_SNAKE_CASE__          =  UnixFileLock
else:
 SCREAMING_SNAKE_CASE__          =  SoftFileLock

 if warnings is not None:
  warnings.warn("only soft file lock is available")




