


'''simple docstring'''







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

  a__    :   int								=			True
except ImportError:
  a__    :   Any								=			False


try:
  from torch.hub import _get_torch_home

  a__    :   Optional[int]								=			_get_torch_home()
except ImportError:
  a__    :   Dict								=			os.path.expanduser(
      os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
  )

a__    :   Optional[Any]								=			os.path.join(torch_cache_home, 'transformers')

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







def _UpperCamelCase			(	__A=OBJECTS ,     __A=ATTRIBUTES       )				->						Optional[int]:


      '''simple docstring'''



      UpperCamelCase__      =							[]
      with open(SCREAMING_SNAKE_CASE_       ) as f:
            for object in f.readlines():
                  vg_classes.append(object.split(","       )[0].lower().strip()       )

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







def _UpperCamelCase			(	__A       )				->						str:


      '''simple docstring'''



      UpperCamelCase__      =							OrderedDict()
      with open(SCREAMING_SNAKE_CASE_ ,     "rb"       ) as f:
            UpperCamelCase__      =							pkl.load(SCREAMING_SNAKE_CASE_       )['model']
      for k in copy.deepcopy(list(ckp.keys()       )       ):
            UpperCamelCase__      =							ckp.pop(SCREAMING_SNAKE_CASE_       )
            if isinstance(SCREAMING_SNAKE_CASE_ ,     np.ndarray       ):
                  UpperCamelCase__      =							torch.tensor(SCREAMING_SNAKE_CASE_       )
            else:
                  assert isinstance(SCREAMING_SNAKE_CASE_ ,     torch.tensor       ), type(SCREAMING_SNAKE_CASE_       )
            UpperCamelCase__      =							v
      return r
class    lowercase_	:
    __UpperCAmelCase       =      {}


    def __init__(	self    ,   a    ,   a = "root"    ,   a=0       ):
          UpperCamelCase__      =							name
          UpperCamelCase__      =							level
          UpperCamelCase__      =							{}
          for k, v in dictionary.items():
                if v is None:
                      raise ValueError()
                UpperCamelCase__      =							copy.deepcopy(_a       )
                UpperCamelCase__      =							copy.deepcopy(_a       )
                if isinstance(_a    ,   _a       ):
                      UpperCamelCase__      =							Config(_a    ,   name=_a    ,   level=level + 1       )
                UpperCamelCase__      =							v
                setattr(self    ,   _a    ,   _a       )

          UpperCamelCase__      =							d


    def __repr__(	self       ):
          return str(list((self._pointer.keys())       )       )


    def __setattr__(	self    ,   a    ,   a       ):
          UpperCamelCase__      =							val
          UpperCamelCase__      =							val
          UpperCamelCase__      =							key.split("."       )
          UpperCamelCase__      =							len(_a       ) - 1
          UpperCamelCase__      =							self._pointer
          if len(_a       ) > 1:
                for i, l in enumerate(_a       ):
                      if hasattr(self    ,   _a       ) and isinstance(getattr(self    ,   _a       )    ,   _a       ):
                            setattr(getattr(self    ,   _a       )    ,   ".".join(levels[i:]       )    ,   _a       )
                      if l == last_level:
                            UpperCamelCase__      =							val
                      else:
                            UpperCamelCase__      =							pointer[l]


    def   __a				(	self       ):
          return self._pointer


    def   __a				(	self    ,   a    ,   a       ):
          with open(f'''{file_name}'''    ,   "w"       ) as stream:
                dump(_a    ,   _a       )


    def   __a				(	self    ,   a    ,   a       ):
          with open(f'''{file_name}'''    ,   "w"       ) as stream:
                json.dump(_a    ,   _a       )


    @staticmethod
    def   __a				(	a       ):
          with open(_a       ) as stream:
                UpperCamelCase__      =							load(_a    ,   Loader=_a       )
          return data


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


    @classmethod
    def   __a				(	cls    ,   a    ,   **a       ):
          UpperCamelCase__      =							cls.get_config_dict(_a    ,   **_a       )
          return cls(_a       )


    @classmethod
    def   __a				(	cls    ,   a    ,   **a       ):
          UpperCamelCase__      =							kwargs.pop("cache_dir"    ,   _a       )
          UpperCamelCase__      =							kwargs.pop("force_download"    ,   _a       )
          UpperCamelCase__      =							kwargs.pop("resume_download"    ,   _a       )
          UpperCamelCase__      =							kwargs.pop("proxies"    ,   _a       )
          UpperCamelCase__      =							kwargs.pop("local_files_only"    ,   _a       )

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

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

                UpperCamelCase__      =							Config.load_yaml(_a       )

          except EnvironmentError:
                UpperCamelCase__      =							'Can\'t load config for'
                raise EnvironmentError(_a       )

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

          return Config.load_yaml(_a       ), kwargs







def _UpperCamelCase			(	__A       )				->						Optional[Any]:


      '''simple docstring'''



      UpperCamelCase__      =							torch.load("dump.pt" ,     map_location=in_tensor.device       )
      UpperCamelCase__      =							in_tensor.numpy()
      UpperCamelCase__      =							out_tensor.numpy()[0]
      print(na.shape ,     na[0, 0, :5]       )
      print(na.shape ,     na[0, 0, :5]       )
      assert np.allclose(SCREAMING_SNAKE_CASE_ ,     SCREAMING_SNAKE_CASE_ ,     rtol=0.01 ,     atol=0.1       ), (
          F'''{sum([1 for x in np.isclose(SCREAMING_SNAKE_CASE_ ,     SCREAMING_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 _UpperCamelCase			(	__A       )				->						Any:


      '''simple docstring'''



      UpperCamelCase__      =							urlparse(SCREAMING_SNAKE_CASE_       )
      return parsed.scheme in ("http", "https")







def _UpperCamelCase			(	__A ,     __A ,     __A=True       )				->						Union[str, Any]:


      '''simple docstring'''



      UpperCamelCase__      =							CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
      UpperCamelCase__      =							'/' not in model_id
      if legacy_format:
            return F'''{endpoint}/{model_id}-{filename}'''
      else:
            return F'''{endpoint}/{model_id}/{filename}'''







def _UpperCamelCase			(	__A ,     __A ,     __A=None ,     __A=0 ,     __A=None ,     )				->						Any:


      '''simple docstring'''



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







def _UpperCamelCase			(	__A ,     __A=None ,     __A=False ,     __A=None ,     __A=10 ,     __A=False ,     __A=None ,     __A=False ,     )				->						Optional[int]:


      '''simple docstring'''



      if cache_dir is None:
            UpperCamelCase__      =							TRANSFORMERS_CACHE
      if isinstance(SCREAMING_SNAKE_CASE_ ,     SCREAMING_SNAKE_CASE_       ):
            UpperCamelCase__      =							str(SCREAMING_SNAKE_CASE_       )

      os.makedirs(SCREAMING_SNAKE_CASE_ ,     exist_ok=SCREAMING_SNAKE_CASE_       )

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

      UpperCamelCase__      =							url_to_filename(SCREAMING_SNAKE_CASE_ ,     SCREAMING_SNAKE_CASE_       )

      # get cache path to put the file
      UpperCamelCase__      =							os.path.join(SCREAMING_SNAKE_CASE_ ,     SCREAMING_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(SCREAMING_SNAKE_CASE_       ):
                  return cache_path
            else:
                  UpperCamelCase__      =							[
                      file
                      for file in fnmatch.filter(os.listdir(SCREAMING_SNAKE_CASE_       ) ,     filename + ".*"       )
                      if not file.endswith(".json"       ) and not file.endswith(".lock"       )
                  ]
                  if len(SCREAMING_SNAKE_CASE_       ) > 0:
                        return os.path.join(SCREAMING_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(SCREAMING_SNAKE_CASE_       ) and not force_download:
            return cache_path

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

            if resume_download:
                  UpperCamelCase__      =							cache_path + '.incomplete'

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

                  UpperCamelCase__      =							_resumable_file_manager
                  if os.path.exists(SCREAMING_SNAKE_CASE_       ):
                        UpperCamelCase__      =							os.stat(SCREAMING_SNAKE_CASE_       ).st_size
                  else:
                        UpperCamelCase__      =							0
            else:
                  UpperCamelCase__      =							partial(tempfile.NamedTemporaryFile ,     dir=SCREAMING_SNAKE_CASE_ ,     delete=SCREAMING_SNAKE_CASE_       )
                  UpperCamelCase__      =							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" ,     SCREAMING_SNAKE_CASE_ ,     temp_file.name ,     )

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

            os.replace(temp_file.name ,     SCREAMING_SNAKE_CASE_       )

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

      return cache_path







def _UpperCamelCase			(	__A ,     __A=None       )				->						Optional[Any]:


      '''simple docstring'''



      UpperCamelCase__      =							url.encode("utf-8"       )
      UpperCamelCase__      =							shaaaa(SCREAMING_SNAKE_CASE_       )
      UpperCamelCase__      =							url_hash.hexdigest()

      if etag:
            UpperCamelCase__      =							etag.encode("utf-8"       )
            UpperCamelCase__      =							shaaaa(SCREAMING_SNAKE_CASE_       )
            filename += "." + etag_hash.hexdigest()

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

      return filename







def _UpperCamelCase			(	__A ,     __A=None ,     __A=False ,     __A=None ,     __A=False ,     __A=None ,     __A=False ,     __A=False ,     __A=False ,     )				->						List[str]:


      '''simple docstring'''



      if cache_dir is None:
            UpperCamelCase__      =							TRANSFORMERS_CACHE
      if isinstance(SCREAMING_SNAKE_CASE_ ,     SCREAMING_SNAKE_CASE_       ):
            UpperCamelCase__      =							str(SCREAMING_SNAKE_CASE_       )
      if isinstance(SCREAMING_SNAKE_CASE_ ,     SCREAMING_SNAKE_CASE_       ):
            UpperCamelCase__      =							str(SCREAMING_SNAKE_CASE_       )

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

      if extract_compressed_file:
            if not is_zipfile(SCREAMING_SNAKE_CASE_       ) and not tarfile.is_tarfile(SCREAMING_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/"
            UpperCamelCase__      =							os.path.split(SCREAMING_SNAKE_CASE_       )
            UpperCamelCase__      =							output_file.replace("." ,     "-"       ) + '-extracted'
            UpperCamelCase__      =							os.path.join(SCREAMING_SNAKE_CASE_ ,     SCREAMING_SNAKE_CASE_       )

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

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

            return output_path_extracted

      return output_path







def _UpperCamelCase			(	__A ,     __A=","       )				->						Union[str, Any]:


      '''simple docstring'''



      assert isinstance(SCREAMING_SNAKE_CASE_ ,     SCREAMING_SNAKE_CASE_       )
      if os.path.isfile(SCREAMING_SNAKE_CASE_       ):
            with open(SCREAMING_SNAKE_CASE_       ) as f:
                  UpperCamelCase__      =							eval(f.read()       )
      else:
            UpperCamelCase__      =							requests.get(SCREAMING_SNAKE_CASE_       )
            try:
                  UpperCamelCase__      =							requests.json()
            except Exception:
                  UpperCamelCase__      =							req.content.decode()
                  assert data is not None, "could not connect"
                  try:
                        UpperCamelCase__      =							eval(SCREAMING_SNAKE_CASE_       )
                  except Exception:
                        UpperCamelCase__      =							data.split("\n"       )
            req.close()
      return data







def _UpperCamelCase			(	__A       )				->						int:


      '''simple docstring'''



      UpperCamelCase__      =							requests.get(SCREAMING_SNAKE_CASE_       )
      UpperCamelCase__      =							np.array(Image.open(BytesIO(response.content       )       )       )
      return img







def _UpperCamelCase			(	__A       )				->						Any:


      '''simple docstring'''



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







def _UpperCamelCase			(	)				->						str:


      '''simple docstring'''



      print(F'''{os.path.abspath(os.path.join(SCREAMING_SNAKE_CASE_ ,     os.pardir       )       )}/demo.ipynb'''       )







def _UpperCamelCase			(	__A ,     __A="RGB"       )				->						List[str]:


      '''simple docstring'''



      assert isinstance(SCREAMING_SNAKE_CASE_ ,     SCREAMING_SNAKE_CASE_       )
      if os.path.isfile(SCREAMING_SNAKE_CASE_       ):
            UpperCamelCase__      =							cva.imread(SCREAMING_SNAKE_CASE_       )
      else:
            UpperCamelCase__      =							get_image_from_url(SCREAMING_SNAKE_CASE_       )
            assert img is not None, F'''could not connect to: {im}'''
      UpperCamelCase__      =							cva.cvtColor(SCREAMING_SNAKE_CASE_ ,     cva.COLOR_BGR2RGB       )
      if input_format == "RGB":
            UpperCamelCase__      =							img[:, :, ::-1]
      return img







def _UpperCamelCase			(	__A ,     __A=1       )				->						Any:


      '''simple docstring'''



      return (images[i : i + batch] for i in range(0 ,     len(SCREAMING_SNAKE_CASE_       ) ,     SCREAMING_SNAKE_CASE_       ))






'''simple docstring'''




import os

from packaging import version

from .. import __version__
from .accelerate_utils import apply_forward_hook
from .constants import (
    CONFIG_NAME,
    DEPRECATED_REVISION_ARGS,
    DIFFUSERS_CACHE,
    DIFFUSERS_DYNAMIC_MODULE_NAME,
    FLAX_WEIGHTS_NAME,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    ONNX_EXTERNAL_WEIGHTS_NAME,
    ONNX_WEIGHTS_NAME,
    SAFETENSORS_WEIGHTS_NAME,
    TEXT_ENCODER_ATTN_MODULE,
    WEIGHTS_NAME,
)
from .deprecation_utils import deprecate
from .doc_utils import replace_example_docstring
from .dynamic_modules_utils import get_class_from_dynamic_module
from .hub_utils import (
    HF_HUB_OFFLINE,
    _add_variant,
    _get_model_file,
    extract_commit_hash,
    http_user_agent,
)
from .import_utils import (
    BACKENDS_MAPPING,
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    is_accelerate_available,
    is_accelerate_version,
    is_bsa_available,
    is_flax_available,
    is_ftfy_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_omegaconf_available,
    is_onnx_available,
    is_safetensors_available,
    is_scipy_available,
    is_tensorboard_available,
    is_tf_available,
    is_torch_available,
    is_torch_version,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    is_wandb_available,
    is_xformers_available,
    requires_backends,
)
from .logging import get_logger
from .outputs import BaseOutput
from .pil_utils import PIL_INTERPOLATION, numpy_to_pil, pt_to_pil
from .torch_utils import is_compiled_module, randn_tensor


if is_torch_available():
 from .testing_utils import (
     floats_tensor,
     load_hf_numpy,
     load_image,
     load_numpy,
     load_pt,
     nightly,
     parse_flag_from_env,
     print_tensor_test,
     require_torch_a,
     require_torch_gpu,
     skip_mps,
     slow,
     torch_all_close,
     torch_device,
 )
 from .torch_utils import maybe_allow_in_graph

from .testing_utils import export_to_gif, export_to_video


_A										= get_logger(__name__)

def _UpperCamelCase (							SCREAMING_SNAKE_CASE_				):
     if version.parse(SCREAMING_SNAKE_CASE_				) < version.parse(SCREAMING_SNAKE_CASE_				):
          if "dev" in min_version:
               lowercase_       :							Tuple  					=       (
                   'This example requires a source install from HuggingFace diffusers (see '
                   '`https://huggingface.co/docs/diffusers/installation#install-from-source`),'
               )
          else:
               lowercase_       :							List[Any]  					=       f'''This example requires a minimum version of {min_version},'''
          error_message += f''' but the version found is {__version__}.\n'''
          raise ImportError(SCREAMING_SNAKE_CASE_				)




