





import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
      import torch

      snake_case 				=       True
except ImportError:
      snake_case 				=       False


try:
      from torch.hub import _get_torch_home

      snake_case 				=       _get_torch_home()
except ImportError:
      snake_case 				=       os.path.expanduser(
          os.getenv("""TORCH_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """torch"""))
      )

snake_case 				=       os.path.join(torch_cache_home, """transformers""")

snake_case 				=       """https://cdn.huggingface.co"""
snake_case 				=       """https://s3.amazonaws.com/models.huggingface.co/bert"""
snake_case 				=       """/""".join(str(Path(__file__).resolve()).split("""/""")[:-1])
snake_case 				=       os.path.join(PATH, """config.yaml""")
snake_case 				=       os.path.join(PATH, """attributes.txt""")
snake_case 				=       os.path.join(PATH, """objects.txt""")
snake_case 				=       os.getenv("""PYTORCH_PRETRAINED_BERT_CACHE""", default_cache_path)
snake_case 				=       os.getenv("""PYTORCH_TRANSFORMERS_CACHE""", PYTORCH_PRETRAINED_BERT_CACHE)
snake_case 				=       os.getenv("""TRANSFORMERS_CACHE""", PYTORCH_TRANSFORMERS_CACHE)
snake_case 				=       """pytorch_model.bin"""
snake_case 				=       """config.yaml"""

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Optional[int]=OBJECTS			,							snake_case__  :Union[str, Any]=ATTRIBUTES     )      ->						List[Any]:
  _lowercase							= []
  with open(__snake_case     ) as f:
    for object in f.readlines():
      vg_classes.append(object.split(','     )[0].lower().strip()     )

  _lowercase							= []
  with open(__snake_case     ) as f:
    for object in f.readlines():
      vg_attrs.append(object.split(','     )[0].lower().strip()     )
  return vg_classes, vg_attrs

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :str     )      ->						Any:
  _lowercase							= OrderedDict()
  with open(__snake_case			,							'rb'     ) as f:
    _lowercase							= pkl.load(__snake_case     )['model']
  for k in copy.deepcopy(list(ckp.keys()     )     ):
    _lowercase							= ckp.pop(__snake_case     )
    if isinstance(__snake_case			,							np.ndarray     ):
      _lowercase							= torch.tensor(__snake_case     )
    else:
      assert isinstance(__snake_case			,							torch.tensor     ), type(__snake_case     )
    _lowercase							= v
  return r





class 				A_				:







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Optional[Any]      =  {}







       def __init__(    self	:	Dict						,__A	:	Tuple						,__A	:	int = "root"						,__A	:	str=0  )						->					Dict:
         _lowercase							= name
         _lowercase							= level
         _lowercase							= {}
         for k, v in dictionary.items():
           if v is None:
             raise ValueError()
           _lowercase							= copy.deepcopy(__lowerCAmelCase  )
           _lowercase							= copy.deepcopy(__lowerCAmelCase  )
           if isinstance(__lowerCAmelCase						,__lowerCAmelCase  ):
             _lowercase							= Config(__lowerCAmelCase						,name=__lowerCAmelCase						,level=level + 1  )
           _lowercase							= v
           setattr(self						,__lowerCAmelCase						,__lowerCAmelCase  )

         _lowercase							= d







       def __repr__(    self	:	Tuple  )						->					Union[str, Any]:
         return str(list((self._pointer.keys())  )  )







       def __setattr__(    self	:	int						,__A	:	Optional[Any]						,__A	:	Optional[int]  )						->					List[str]:
         _lowercase							= val
         _lowercase							= val
         _lowercase							= key.split('.'  )
         _lowercase							= len(__lowerCAmelCase  ) - 1
         _lowercase							= self._pointer
         if len(__lowerCAmelCase  ) > 1:
           for i, l in enumerate(__lowerCAmelCase  ):
             if hasattr(self						,__lowerCAmelCase  ) and isinstance(getattr(self						,__lowerCAmelCase  )						,__lowerCAmelCase  ):
               setattr(getattr(self						,__lowerCAmelCase  )						,'.'.join(levels[i:]  )						,__lowerCAmelCase  )
             if l == last_level:
               _lowercase							= val
             else:
               _lowercase							= pointer[l]







       def    __UpperCAmelCase (    self	:	List[Any]  )						->					Any:
         return self._pointer







       def    __UpperCAmelCase (    self	:	List[Any]						,__A	:	List[Any]						,__A	:	List[Any]  )						->					int:







         with open(F"""{file_name}"""						,'w'  ) as stream:
           dump(__lowerCAmelCase						,__lowerCAmelCase  )







       def    __UpperCAmelCase (    self	:	str						,__A	:	List[str]						,__A	:	Optional[Any]  )						->					List[Any]:







         with open(F"""{file_name}"""						,'w'  ) as stream:
           json.dump(__lowerCAmelCase						,__lowerCAmelCase  )







       @staticmethod
       def    __UpperCAmelCase (    __A	:	Optional[int]  )						->					Tuple:







         with open(__lowerCAmelCase  ) as stream:
           _lowercase							= load(__lowerCAmelCase						,Loader=__lowerCAmelCase  )
         return data







       def __str__(    self	:	Any  )						->					List[str]:
         _lowercase							= '    '
         if self._name != "root":
           _lowercase							= F"""{t * (self._level-1)}{self._name}:\n"""
         else:
           _lowercase							= ''
         _lowercase							= self._level
         for i, (k, v) in enumerate(self._pointer.items()  ):
           if isinstance(__lowerCAmelCase						,__lowerCAmelCase  ):
             r += F"""{t * (self._level)}{v}\n"""
             self._level += 1
           else:
             r += F"""{t * (self._level)}{k}: {v} ({type(__lowerCAmelCase  ).__name__})\n"""
           _lowercase							= level
         return r[:-1]







       @classmethod
       def    __UpperCAmelCase (    cls	:	List[Any]						,__A	:	Optional[Any]						,**__A	:	Dict  )						->					Optional[Any]:
         _lowercase						,		_lowercase							= cls.get_config_dict(__lowerCAmelCase						,**__lowerCAmelCase  )
         return cls(__lowerCAmelCase  )







       @classmethod
       def    __UpperCAmelCase (    cls	:	Any						,__A	:	List[Any]						,**__A	:	Tuple  )						->					int:
         _lowercase							= kwargs.pop('cache_dir'						,__lowerCAmelCase  )
         _lowercase							= kwargs.pop('force_download'						,__lowerCAmelCase  )
         _lowercase							= kwargs.pop('resume_download'						,__lowerCAmelCase  )
         _lowercase							= kwargs.pop('proxies'						,__lowerCAmelCase  )
         _lowercase							= kwargs.pop('local_files_only'						,__lowerCAmelCase  )

         if os.path.isdir(__lowerCAmelCase  ):
           _lowercase							= os.path.join(__lowerCAmelCase						,__lowerCAmelCase  )
         elif os.path.isfile(__lowerCAmelCase  ) or is_remote_url(__lowerCAmelCase  ):
           _lowercase							= pretrained_model_name_or_path
         else:
           _lowercase							= hf_bucket_url(__lowerCAmelCase						,filename=__lowerCAmelCase						,use_cdn=__lowerCAmelCase  )

         try:
           # Load from URL or cache if already cached
           _lowercase							= cached_path(
               __lowerCAmelCase						,cache_dir=__lowerCAmelCase						,force_download=__lowerCAmelCase						,proxies=__lowerCAmelCase						,resume_download=__lowerCAmelCase						,local_files_only=__lowerCAmelCase						,)
           # Load config dict
           if resolved_config_file is None:
             raise EnvironmentError

           _lowercase							= Config.load_yaml(__lowerCAmelCase  )

         except EnvironmentError:
           _lowercase							= 'Can\'t load config for'
           raise EnvironmentError(__lowerCAmelCase  )

         if resolved_config_file == config_file:
           print('loading configuration file from path'  )
         else:
           print('loading configuration file cache'  )

         return Config.load_yaml(__lowerCAmelCase  ), kwargs

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Optional[Any]     )      ->						str:
  _lowercase							= torch.load('dump.pt'			,							map_location=in_tensor.device     )
  _lowercase							= in_tensor.numpy()
  _lowercase							= out_tensor.numpy()[0]
  print(na.shape			,							na[0, 0, :5]     )
  print(na.shape			,							na[0, 0, :5]     )
  assert np.allclose(__snake_case			,							__snake_case			,							rtol=0.01			,							atol=0.1     ), (
      F"""{sum([1 for x in np.isclose(__snake_case			,							__snake_case			,							rtol=0.01			,							atol=0.1     ).flatten() if x is False]     )/len(na.flatten()     )*100:.4f} %"""
      " element-wise mismatch"
  )
  raise Exception('tensors are all good'     )

  # Hugging face functions below

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Tuple     )      ->						str:
  _lowercase							= urlparse(__snake_case     )
  return parsed.scheme in ("http", "https")

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Optional[int]			,							snake_case__  :int			,							snake_case__  :Tuple=True     )      ->						str:
  _lowercase							= CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
  _lowercase							= '/' not in model_id
  if legacy_format:
    return F"""{endpoint}/{model_id}-{filename}"""
  else:
    return F"""{endpoint}/{model_id}/{filename}"""

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Dict			,							snake_case__  :Dict			,							snake_case__  :Optional[Any]=None			,							snake_case__  :Union[str, Any]=0			,							snake_case__  :Optional[int]=None			,							)      ->						int:
  _lowercase							= 'python/{}'.format(sys.version.split()[0]     )
  if _torch_available:
    ua += "; torch/{}".format(torch.__version__     )
  if isinstance(__snake_case			,							__snake_case     ):
    ua += "; " + "; ".join('{}/{}'.format(__snake_case			,							__snake_case     ) for k, v in user_agent.items()     )
  elif isinstance(__snake_case			,							__snake_case     ):
    ua += "; " + user_agent
  _lowercase							= {'user-agent': ua}
  if resume_size > 0:
    _lowercase							= 'bytes=%d-' % (resume_size,)
  _lowercase							= requests.get(__snake_case			,							stream=__snake_case			,							proxies=__snake_case			,							headers=__snake_case     )
  if response.status_code == 416:  # Range not satisfiable
    return
  _lowercase							= response.headers.get('Content-Length'     )
  _lowercase							= resume_size + int(__snake_case     ) if content_length is not None else None
  _lowercase							= tqdm(
      unit='B'			,							unit_scale=__snake_case			,							total=__snake_case			,							initial=__snake_case			,							desc='Downloading'			,							)
  for chunk in response.iter_content(chunk_size=1024     ):
    if chunk:  # filter out keep-alive new chunks
      progress.update(len(__snake_case     )     )
      temp_file.write(__snake_case     )
  progress.close()

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Any			,							snake_case__  :List[str]=None			,							snake_case__  :Optional[int]=False			,							snake_case__  :Optional[int]=None			,							snake_case__  :Dict=10			,							snake_case__  :str=False			,							snake_case__  :Union[str, Any]=None			,							snake_case__  :Dict=False			,							)      ->						str:







  if cache_dir is None:
    _lowercase							= TRANSFORMERS_CACHE
  if isinstance(__snake_case			,							__snake_case     ):
    _lowercase							= str(__snake_case     )

  os.makedirs(__snake_case			,							exist_ok=__snake_case     )

  _lowercase							= None
  if not local_files_only:
    try:
      _lowercase							= requests.head(__snake_case			,							allow_redirects=__snake_case			,							proxies=__snake_case			,							timeout=__snake_case     )
      if response.status_code == 200:
        _lowercase							= response.headers.get('ETag'     )
    except (EnvironmentError, requests.exceptions.Timeout):
      # etag is already None
      pass

  _lowercase							= url_to_filename(__snake_case			,							__snake_case     )

  # get cache path to put the file
  _lowercase							= os.path.join(__snake_case			,							__snake_case     )

  # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
  # try to get the last downloaded one
  if etag is None:
    if os.path.exists(__snake_case     ):
      return cache_path
    else:
      _lowercase							= [
          file
          for file in fnmatch.filter(os.listdir(__snake_case     )			,							filename + '.*'     )
          if not file.endswith('.json'     ) and not file.endswith('.lock'     )
      ]
      if len(__snake_case     ) > 0:
        return os.path.join(__snake_case			,							matching_files[-1]     )
      else:
        # If files cannot be found and local_files_only=True,
        # the models might've been found if local_files_only=False
        # Notify the user about that
        if local_files_only:
          raise ValueError(
              'Cannot find the requested files in the cached path and outgoing traffic has been'
              ' disabled. To enable model look-ups and downloads online, set \'local_files_only\''
              ' to False.'     )
        return None

    # From now on, etag is not None.
  if os.path.exists(__snake_case     ) and not force_download:
    return cache_path

  # Prevent parallel downloads of the same file with a lock.
  _lowercase							= cache_path + '.lock'
  with FileLock(__snake_case     ):
    # If the download just completed while the lock was activated.
    if os.path.exists(__snake_case     ) and not force_download:
      # Even if returning early like here, the lock will be released.
      return cache_path

    if resume_download:
      _lowercase							= cache_path + '.incomplete'

      @contextmanager
      def _resumable_file_manager():
        with open(__snake_case			,							'a+b'     ) as f:
          yield f

      _lowercase							= _resumable_file_manager
      if os.path.exists(__snake_case     ):
        _lowercase							= os.stat(__snake_case     ).st_size
      else:
        _lowercase							= 0
    else:
      _lowercase							= partial(tempfile.NamedTemporaryFile			,							dir=__snake_case			,							delete=__snake_case     )
      _lowercase							= 0

    # Download to temporary file, then copy to cache dir once finished.
    # Otherwise you get corrupt cache entries if the download gets interrupted.
    with temp_file_manager() as temp_file:
      print(
          '%s not found in cache or force_download set to True, downloading to %s'			,							__snake_case			,							temp_file.name			,							)

      http_get(
          __snake_case			,							__snake_case			,							proxies=__snake_case			,							resume_size=__snake_case			,							user_agent=__snake_case			,							)

    os.replace(temp_file.name			,							__snake_case     )

    _lowercase							= {'url': url, 'etag': etag}
    _lowercase							= cache_path + '.json'
    with open(__snake_case			,							'w'     ) as meta_file:
      json.dump(__snake_case			,							__snake_case     )

  return cache_path

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Union[str, Any]			,							snake_case__  :Any=None     )      ->						Optional[int]:
  _lowercase							= url.encode('utf-8'     )
  _lowercase							= shaaaa(__snake_case     )
  _lowercase							= url_hash.hexdigest()

  if etag:
    _lowercase							= etag.encode('utf-8'     )
    _lowercase							= shaaaa(__snake_case     )
    filename += "." + etag_hash.hexdigest()

  if url.endswith('.h5'     ):
    filename += ".h5"

  return filename

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Optional[int]			,							snake_case__  :List[str]=None			,							snake_case__  :List[str]=False			,							snake_case__  :str=None			,							snake_case__  :Tuple=False			,							snake_case__  :int=None			,							snake_case__  :Union[str, Any]=False			,							snake_case__  :Tuple=False			,							snake_case__  :List[Any]=False			,							)      ->						List[Any]:







  if cache_dir is None:
    _lowercase							= TRANSFORMERS_CACHE
  if isinstance(__snake_case			,							__snake_case     ):
    _lowercase							= str(__snake_case     )
  if isinstance(__snake_case			,							__snake_case     ):
    _lowercase							= str(__snake_case     )

  if is_remote_url(__snake_case     ):
    # URL, so get it from the cache (downloading if necessary)
    _lowercase							= get_from_cache(
        __snake_case			,							cache_dir=__snake_case			,							force_download=__snake_case			,							proxies=__snake_case			,							resume_download=__snake_case			,							user_agent=__snake_case			,							local_files_only=__snake_case			,							)
  elif os.path.exists(__snake_case     ):
    # File, and it exists.
    _lowercase							= url_or_filename
  elif urlparse(__snake_case     ).scheme == "":
    # File, but it doesn't exist.
    raise EnvironmentError('file {} not found'.format(__snake_case     )     )
  else:
    # Something unknown
    raise ValueError('unable to parse {} as a URL or as a local path'.format(__snake_case     )     )

  if extract_compressed_file:
    if not is_zipfile(__snake_case     ) and not tarfile.is_tarfile(__snake_case     ):
      return output_path

    # Path where we extract compressed archives
    # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
    _lowercase						,		_lowercase							= os.path.split(__snake_case     )
    _lowercase							= output_file.replace('.'			,							'-'     ) + '-extracted'
    _lowercase							= os.path.join(__snake_case			,							__snake_case     )

    if os.path.isdir(__snake_case     ) and os.listdir(__snake_case     ) and not force_extract:
      return output_path_extracted

    # Prevent parallel extractions
    _lowercase							= output_path + '.lock'
    with FileLock(__snake_case     ):
      shutil.rmtree(__snake_case			,							ignore_errors=__snake_case     )
      os.makedirs(__snake_case     )
      if is_zipfile(__snake_case     ):
        with ZipFile(__snake_case			,							'r'     ) as zip_file:
          zip_file.extractall(__snake_case     )
          zip_file.close()
      elif tarfile.is_tarfile(__snake_case     ):
        _lowercase							= tarfile.open(__snake_case     )
        tar_file.extractall(__snake_case     )
        tar_file.close()
      else:
        raise EnvironmentError('Archive format of {} could not be identified'.format(__snake_case     )     )

    return output_path_extracted

  return output_path

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :int			,							snake_case__  :Optional[int]=","     )      ->						Any:
  assert isinstance(__snake_case			,							__snake_case     )
  if os.path.isfile(__snake_case     ):
    with open(__snake_case     ) as f:
      _lowercase							= eval(f.read()     )
  else:
    _lowercase							= requests.get(__snake_case     )
    try:
      _lowercase							= requests.json()
    except Exception:
      _lowercase							= req.content.decode()
      assert data is not None, "could not connect"
      try:
        _lowercase							= eval(__snake_case     )
      except Exception:
        _lowercase							= data.split('\n'     )
    req.close()
  return data

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :List[Any]     )      ->						Dict:
  _lowercase							= requests.get(__snake_case     )
  _lowercase							= np.array(Image.open(BytesIO(response.content     )     )     )
  return img

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :int     )      ->						int:
  _lowercase							= url.split('/'     )[-1]
  if fn not in os.listdir(os.getcwd()     ):
    wget.download(__snake_case     )
  with open(__snake_case			,							'rb'     ) as stream:
    _lowercase							= pkl.load(__snake_case     )
  _lowercase							= weights.pop('model'     )
  _lowercase							= {}
  for k, v in model.items():
    _lowercase							= torch.from_numpy(__snake_case     )
    if "running_var" in k:
      _lowercase							= torch.tensor([0]     )
      _lowercase							= k.replace('running_var'			,							'num_batches_tracked'     )
      _lowercase							= zero
  return new

def 							SCREAMING_SNAKE_CASE__       (  )      ->						Any:
  print(F"""{os.path.abspath(os.path.join(__snake_case			,							os.pardir     )     )}/demo.ipynb"""     )

def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :str			,							snake_case__  :Any="RGB"     )      ->						Optional[Any]:
  assert isinstance(__snake_case			,							__snake_case     )
  if os.path.isfile(__snake_case     ):
    _lowercase							= cva.imread(__snake_case     )
  else:
    _lowercase							= get_image_from_url(__snake_case     )
    assert img is not None, F"""could not connect to: {im}"""
  _lowercase							= cva.cvtColor(__snake_case			,							cva.COLOR_BGR2RGB     )
  if input_format == "RGB":
    _lowercase							= img[:, :, ::-1]
  return img







def 							SCREAMING_SNAKE_CASE__       (  snake_case__  :Tuple			,							snake_case__  :List[str]=1     )      ->						Any:
  return (images[i : i + batch] for i in range(0			,							len(__snake_case     )			,							__snake_case     ))








snake_case 				=       """0.18.2"""

from .configuration_utils import ConfigMixin
from .utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_onnx_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    logging,
)


try:
      if not is_onnx_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_onnx_objects import *  # noqa F403
else:
      from .pipelines import OnnxRuntimeModel

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_pt_objects import *  # noqa F403
else:
      from .models import (
          AutoencoderKL,
          ControlNetModel,
          ModelMixin,
          PriorTransformer,
          TaFilmDecoder,
          TransformeraDModel,
          UNetaDModel,
          UNetaDConditionModel,
          UNetaDModel,
          UNetaDConditionModel,
          VQModel,
      )
      from .optimization import (
          get_constant_schedule,
          get_constant_schedule_with_warmup,
          get_cosine_schedule_with_warmup,
          get_cosine_with_hard_restarts_schedule_with_warmup,
          get_linear_schedule_with_warmup,
          get_polynomial_decay_schedule_with_warmup,
          get_scheduler,
      )
      from .pipelines import (
          AudioPipelineOutput,
          ConsistencyModelPipeline,
          DanceDiffusionPipeline,
          DDIMPipeline,
          DDPMPipeline,
          DiffusionPipeline,
          DiTPipeline,
          ImagePipelineOutput,
          KarrasVePipeline,
          LDMPipeline,
          LDMSuperResolutionPipeline,
          PNDMPipeline,
          RePaintPipeline,
          ScoreSdeVePipeline,
      )
      from .schedulers import (
          CMStochasticIterativeScheduler,
          DDIMInverseScheduler,
          DDIMParallelScheduler,
          DDIMScheduler,
          DDPMParallelScheduler,
          DDPMScheduler,
          DEISMultistepScheduler,
          DPMSolverMultistepInverseScheduler,
          DPMSolverMultistepScheduler,
          DPMSolverSinglestepScheduler,
          EulerAncestralDiscreteScheduler,
          EulerDiscreteScheduler,
          HeunDiscreteScheduler,
          IPNDMScheduler,
          KarrasVeScheduler,
          KDPMaAncestralDiscreteScheduler,
          KDPMaDiscreteScheduler,
          PNDMScheduler,
          RePaintScheduler,
          SchedulerMixin,
          ScoreSdeVeScheduler,
          UnCLIPScheduler,
          UniPCMultistepScheduler,
          VQDiffusionScheduler,
      )
      from .training_utils import EMAModel

try:
      if not (is_torch_available() and is_scipy_available()):
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
      from .schedulers import LMSDiscreteScheduler

try:
      if not (is_torch_available() and is_torchsde_available()):
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
      from .schedulers import DPMSolverSDEScheduler

try:
      if not (is_torch_available() and is_transformers_available()):
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_torch_and_transformers_objects import *  # noqa F403
else:
      from .pipelines import (
          AltDiffusionImgaImgPipeline,
          AltDiffusionPipeline,
          AudioLDMPipeline,
          CycleDiffusionPipeline,
          IFImgaImgPipeline,
          IFImgaImgSuperResolutionPipeline,
          IFInpaintingPipeline,
          IFInpaintingSuperResolutionPipeline,
          IFPipeline,
          IFSuperResolutionPipeline,
          ImageTextPipelineOutput,
          KandinskyImgaImgPipeline,
          KandinskyInpaintPipeline,
          KandinskyPipeline,
          KandinskyPriorPipeline,
          KandinskyVaaControlnetImgaImgPipeline,
          KandinskyVaaControlnetPipeline,
          KandinskyVaaImgaImgPipeline,
          KandinskyVaaInpaintPipeline,
          KandinskyVaaPipeline,
          KandinskyVaaPriorEmbaEmbPipeline,
          KandinskyVaaPriorPipeline,
          LDMTextToImagePipeline,
          PaintByExamplePipeline,
          SemanticStableDiffusionPipeline,
          ShapEImgaImgPipeline,
          ShapEPipeline,
          StableDiffusionAttendAndExcitePipeline,
          StableDiffusionControlNetImgaImgPipeline,
          StableDiffusionControlNetInpaintPipeline,
          StableDiffusionControlNetPipeline,
          StableDiffusionDepthaImgPipeline,
          StableDiffusionDiffEditPipeline,
          StableDiffusionImageVariationPipeline,
          StableDiffusionImgaImgPipeline,
          StableDiffusionInpaintPipeline,
          StableDiffusionInpaintPipelineLegacy,
          StableDiffusionInstructPixaPixPipeline,
          StableDiffusionLatentUpscalePipeline,
          StableDiffusionLDMaDPipeline,
          StableDiffusionModelEditingPipeline,
          StableDiffusionPanoramaPipeline,
          StableDiffusionParadigmsPipeline,
          StableDiffusionPipeline,
          StableDiffusionPipelineSafe,
          StableDiffusionPixaPixZeroPipeline,
          StableDiffusionSAGPipeline,
          StableDiffusionUpscalePipeline,
          StableUnCLIPImgaImgPipeline,
          StableUnCLIPPipeline,
          TextToVideoSDPipeline,
          TextToVideoZeroPipeline,
          UnCLIPImageVariationPipeline,
          UnCLIPPipeline,
          UniDiffuserModel,
          UniDiffuserPipeline,
          UniDiffuserTextDecoder,
          VersatileDiffusionDualGuidedPipeline,
          VersatileDiffusionImageVariationPipeline,
          VersatileDiffusionPipeline,
          VersatileDiffusionTextToImagePipeline,
          VideoToVideoSDPipeline,
          VQDiffusionPipeline,
      )

try:
      if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()):
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import *  # noqa F403
else:
      from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline

try:
      if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import *  # noqa F403
else:
      from .pipelines import StableDiffusionKDiffusionPipeline

try:
      if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_torch_and_transformers_and_onnx_objects import *  # noqa F403
else:
      from .pipelines import (
          OnnxStableDiffusionImgaImgPipeline,
          OnnxStableDiffusionInpaintPipeline,
          OnnxStableDiffusionInpaintPipelineLegacy,
          OnnxStableDiffusionPipeline,
          OnnxStableDiffusionUpscalePipeline,
          StableDiffusionOnnxPipeline,
      )

try:
      if not (is_torch_available() and is_librosa_available()):
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_torch_and_librosa_objects import *  # noqa F403
else:
      from .pipelines import AudioDiffusionPipeline, Mel

try:
      if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_transformers_and_torch_and_note_seq_objects import *  # noqa F403
else:
      from .pipelines import SpectrogramDiffusionPipeline

try:
      if not is_flax_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_flax_objects import *  # noqa F403
else:
      from .models.controlnet_flax import FlaxControlNetModel
      from .models.modeling_flax_utils import FlaxModelMixin
      from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel
      from .models.vae_flax import FlaxAutoencoderKL
      from .pipelines import FlaxDiffusionPipeline
      from .schedulers import (
          FlaxDDIMScheduler,
          FlaxDDPMScheduler,
          FlaxDPMSolverMultistepScheduler,
          FlaxKarrasVeScheduler,
          FlaxLMSDiscreteScheduler,
          FlaxPNDMScheduler,
          FlaxSchedulerMixin,
          FlaxScoreSdeVeScheduler,
      )


try:
      if not (is_flax_available() and is_transformers_available()):
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_flax_and_transformers_objects import *  # noqa F403
else:
      from .pipelines import (
          FlaxStableDiffusionControlNetPipeline,
          FlaxStableDiffusionImgaImgPipeline,
          FlaxStableDiffusionInpaintPipeline,
          FlaxStableDiffusionPipeline,
      )

try:
      if not (is_note_seq_available()):
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      from .utils.dummy_note_seq_objects import *  # noqa F403
else:
      from .pipelines import MidiProcessor